@sequenzy/cli 0.0.197 → 0.0.198
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 +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -191,7 +191,7 @@ Check the top-level render call using <`+Be+">."}return de}}function Gr(Q,de){{i
|
|
|
191
191
|
<%s {...props} />
|
|
192
192
|
React keys must be passed directly to JSX without using spread:
|
|
193
193
|
let props = %s;
|
|
194
|
-
<%s key={someKey} {...props} />`,Qs,bi,$s,bi),gc[bi+Qs]=!0}}if(Q===n)Pr(dn);else Oo(dn);return dn}}var fr=Rl;ibe.Fragment=n,ibe.jsxDEV=fr})()});var Aw={};LZ(Aw,{program:()=>AT,createCommand:()=>hT,createOption:()=>yT,createArgument:()=>bT,Command:()=>vT,Option:()=>ET,Argument:()=>IT,Help:()=>CT,CommanderError:()=>wT,InvalidArgumentError:()=>ST,InvalidOptionArgumentError:()=>DT},{program:(BDe)=>AT=BDe,createCommand:(BDe)=>hT=BDe,createOption:(BDe)=>yT=BDe,createArgument:(BDe)=>bT=BDe,Command:(BDe)=>vT=BDe,Option:(BDe)=>ET=BDe,Argument:(BDe)=>IT=BDe,Help:(BDe)=>CT=BDe,CommanderError:(BDe)=>wT=BDe,InvalidArgumentError:(BDe)=>ST=BDe,InvalidOptionArgumentError:(BDe)=>DT=BDe});var{Argument:mT}=fh(),{Command:gw}=pT(),{CommanderError:A9,InvalidArgumentError:fT}=jm(),{Help:h9}=dw(),{Option:gT}=pw();var AT=new gw,hT=(e)=>new gw(e),yT=(e,t)=>new gT(e,t),bT=(e,t)=>new mT(e,t),vT=gw,ET=gT,IT=mT,CT=h9,wT=A9,ST=fT,DT=fT;var{program:xDe,createCommand:kDe,createArgument:RDe,createOption:TDe,CommanderError:BT,InvalidArgumentError:QDe,InvalidOptionArgumentError:$De,Command:_T,Argument:NDe,Option:ODe,Help:PDe}=Aw;var gh={name:"@sequenzy/cli",version:"0.0.197",description:"Sequenzy CLI for email marketing from the terminal",type:"module",bin:{sequenzy:"./dist/index.js"},main:"./src/index.tsx",types:"./src/index.tsx",exports:{".":"./src/index.tsx"},scripts:{dev:"bun --watch src/index.tsx",build:"bun ../../scripts/build-ink-cli.ts",start:"node dist/index.js",lint:"eslint src","type-check":"bun check",test:"sh ../../scripts/run-package-tests.sh src","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{commander:"^12.1.0",ink:"^5.0.1","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","ink-select-input":"^6.0.0","ink-table":"^3.1.0",open:"^10.1.0",react:"^18.3.1",conf:"^13.0.0"},devDependencies:{"@emailer/shared":"workspace:*","@types/bun":"latest","@types/node":"^22.0.0","@types/react":"^18.3.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist"],keywords:["sequenzy","email","cli","marketing"],license:"MIT",repository:{type:"git",url:"https://github.com/sequenzy/sequenzy"}};import{isDeepStrictEqual as Rce}from"node:util";import E1 from"node:process";import au from"node:fs";import I1 from"node:path";import ff from"node:crypto";import Tce from"node:assert";var eu=(e)=>{let t=typeof e;return e!==null&&(t==="object"||t==="function")};var hw=new Set(["__proto__","prototype","constructor"]),b9=new Set("0123456789");function Ah(e){let t=[],n="",r="start",o=!1;for(let a of e)switch(a){case"\\":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(o)n+=a;r="property",o=!o;break}case".":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="property";break}if(o){o=!1,n+=a;break}if(hw.has(n))return[];t.push(n),n="",r="property";break}case"[":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="index";break}if(o){o=!1,n+=a;break}if(r==="property"){if(hw.has(n))return[];t.push(n),n=""}r="index";break}case"]":{if(r==="index"){t.push(Number.parseInt(n,10)),n="",r="indexEnd";break}if(r==="indexEnd")throw Error("Invalid character after an index")}default:{if(r==="index"&&!b9.has(a))throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(r==="start")r="property";if(o)o=!1,n+="\\";n+=a}}if(o)n+="\\";switch(r){case"property":{if(hw.has(n))return[];t.push(n);break}case"index":throw Error("Index was not closed");case"start":{t.push("");break}}return t}function yw(e,t){if(typeof t!=="number"&&Array.isArray(e)){let n=Number.parseInt(t,10);return Number.isInteger(n)&&e[n]===e[t]}return!1}function xT(e,t){if(yw(e,t))throw Error("Cannot use string index")}function kT(e,t,n){if(!eu(e)||typeof t!=="string")return n===void 0?e:n;let r=Ah(t);if(r.length===0)return n;for(let o=0;o<r.length;o++){let a=r[o];if(yw(e,a))e=o===r.length-1?void 0:null;else e=e[a];if(e===void 0||e===null){if(o!==r.length-1)return n;break}}return e===void 0?n:e}function bw(e,t,n){if(!eu(e)||typeof t!=="string")return e;let r=e,o=Ah(t);for(let a=0;a<o.length;a++){let c=o[a];if(xT(e,c),a===o.length-1)e[c]=n;else if(!eu(e[c]))e[c]=typeof o[a+1]==="number"?[]:{};e=e[c]}return r}function RT(e,t){if(!eu(e)||typeof t!=="string")return!1;let n=Ah(t);for(let r=0;r<n.length;r++){let o=n[r];if(xT(e,o),r===n.length-1)return delete e[o],!0;if(e=e[o],!eu(e))return!1}}function TT(e,t){if(!eu(e)||typeof t!=="string")return!1;let n=Ah(t);if(n.length===0)return!1;for(let r of n){if(!eu(e)||!(r in e)||yw(e,r))return!1;e=e[r]}return!0}import Yn from"node:path";import QT from"node:os";import vw from"node:process";var Nc=QT.homedir(),Ew=QT.tmpdir(),{env:Cd}=vw,v9=(e)=>{let t=Yn.join(Nc,"Library");return{data:Yn.join(t,"Application Support",e),config:Yn.join(t,"Preferences",e),cache:Yn.join(t,"Caches",e),log:Yn.join(t,"Logs",e),temp:Yn.join(Ew,e)}},E9=(e)=>{let t=Cd.APPDATA||Yn.join(Nc,"AppData","Roaming"),n=Cd.LOCALAPPDATA||Yn.join(Nc,"AppData","Local");return{data:Yn.join(n,e,"Data"),config:Yn.join(t,e,"Config"),cache:Yn.join(n,e,"Cache"),log:Yn.join(n,e,"Log"),temp:Yn.join(Ew,e)}},I9=(e)=>{let t=Yn.basename(Nc);return{data:Yn.join(Cd.XDG_DATA_HOME||Yn.join(Nc,".local","share"),e),config:Yn.join(Cd.XDG_CONFIG_HOME||Yn.join(Nc,".config"),e),cache:Yn.join(Cd.XDG_CACHE_HOME||Yn.join(Nc,".cache"),e),log:Yn.join(Cd.XDG_STATE_HOME||Yn.join(Nc,".local","state"),e),temp:Yn.join(Ew,t,e)}};function Iw(e,{suffix:t="nodejs"}={}){if(typeof e!=="string")throw TypeError(`Expected a string, got ${typeof e}`);if(t)e+=`-${t}`;if(vw.platform==="darwin")return v9(e);if(vw.platform==="win32")return E9(e);return I9(e)}import k9 from"node:path";import nn from"node:fs";import{promisify as So}from"node:util";var C9=(e,t)=>{let{onError:n}=t;return function(...o){return e.apply(void 0,o).catch(n)}},ra=C9;var w9=(e,t)=>{let{onError:n}=t;return function(...o){try{return e.apply(void 0,o)}catch(a){return n(a)}}},bs=w9;var $T=250;var S9=(e,t)=>{let{isRetriable:n}=t;return function(o){let{timeout:a}=o,c=o.interval??$T,l=Date.now()+a;return function p(...f){return e.apply(void 0,f).catch((h)=>{if(!n(h))throw h;if(Date.now()>=l)throw h;let b=Math.round(c*Math.random());if(b>0)return new Promise((C)=>setTimeout(C,b)).then(()=>p.apply(void 0,f));else return p.apply(void 0,f)})}}},oa=S9;var D9=(e,t)=>{let{isRetriable:n}=t;return function(o){let{timeout:a}=o,c=Date.now()+a;return function(...p){while(!0)try{return e.apply(void 0,p)}catch(f){if(!n(f))throw f;if(Date.now()>=c)throw f;continue}}}},ia=D9;import OT from"node:process";var zm={isChangeErrorOk:(e)=>{if(!zm.isNodeError(e))return!1;let{code:t}=e;if(t==="ENOSYS")return!0;if(!NT&&(t==="EINVAL"||t==="EPERM"))return!0;return!1},isNodeError:(e)=>e instanceof Error,isRetriableError:(e)=>{if(!zm.isNodeError(e))return!1;let{code:t}=e;if(t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM")return!0;return!1},onChangeError:(e)=>{if(!zm.isNodeError(e))throw e;if(zm.isChangeErrorOk(e))return;throw e}},Cw=zm;var Mm={onError:Cw.onChangeError},ri={onError:()=>{return}},NT=OT.getuid?!OT.getuid():!1,ho={isRetriable:Cw.isRetriableError};var B9={attempt:{chmod:ra(So(nn.chmod),Mm),chown:ra(So(nn.chown),Mm),close:ra(So(nn.close),ri),fsync:ra(So(nn.fsync),ri),mkdir:ra(So(nn.mkdir),ri),realpath:ra(So(nn.realpath),ri),stat:ra(So(nn.stat),ri),unlink:ra(So(nn.unlink),ri),chmodSync:bs(nn.chmodSync,Mm),chownSync:bs(nn.chownSync,Mm),closeSync:bs(nn.closeSync,ri),existsSync:bs(nn.existsSync,ri),fsyncSync:bs(nn.fsync,ri),mkdirSync:bs(nn.mkdirSync,ri),realpathSync:bs(nn.realpathSync,ri),statSync:bs(nn.statSync,ri),unlinkSync:bs(nn.unlinkSync,ri)},retry:{close:oa(So(nn.close),ho),fsync:oa(So(nn.fsync),ho),open:oa(So(nn.open),ho),readFile:oa(So(nn.readFile),ho),rename:oa(So(nn.rename),ho),stat:oa(So(nn.stat),ho),write:oa(So(nn.write),ho),writeFile:oa(So(nn.writeFile),ho),closeSync:ia(nn.closeSync,ho),fsyncSync:ia(nn.fsyncSync,ho),openSync:ia(nn.openSync,ho),readFileSync:ia(nn.readFileSync,ho),renameSync:ia(nn.renameSync,ho),statSync:ia(nn.statSync,ho),writeSync:ia(nn.writeSync,ho),writeFileSync:ia(nn.writeFileSync,ho)}},Xr=B9;import tu from"node:process";var PT="utf8",ww=438,qT=511;var FT={},LT=tu.geteuid?tu.geteuid():-1,UT=tu.getegid?tu.getegid():-1;var jT=1000,zT=!!tu.getuid,fBe=tu.getuid?!tu.getuid():!1,Sw=128;var MT=(e)=>e instanceof Error&&("code"in e);var Dw=(e)=>typeof e==="string",hh=(e)=>e===void 0;import x9 from"node:path";import wd from"node:process";import HT from"node:process";var GT=HT.platform==="linux",yh=HT.platform==="win32";var Bw=["SIGHUP","SIGINT","SIGTERM"];if(!yh)Bw.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(GT)Bw.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var JT=Bw;class WT{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=(e)=>{if(this.exited)return;this.exited=!0;for(let t of this.callbacks)t();if(e)if(yh&&(e!=="SIGINT"&&e!=="SIGTERM"&&e!=="SIGKILL"))wd.kill(wd.pid,"SIGTERM");else wd.kill(wd.pid,e)},this.hook=()=>{wd.once("exit",()=>this.exit());for(let e of JT)try{wd.once(e,()=>this.exit(e))}catch{}},this.register=(e)=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}}var VT=new WT;var _9=VT.register,KT=_9;var Bi={store:{},create:(e)=>{let t=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6),n=Date.now().toString().slice(-10),r="tmp-",o=`.tmp-${n}${t}`;return`${e}${o}`},get:(e,t,n=!0)=>{let r=Bi.truncate(t(e));if(r in Bi.store)return Bi.get(e,t,n);return Bi.store[r]=n,[r,()=>delete Bi.store[r]]},purge:(e)=>{if(!Bi.store[e])return;delete Bi.store[e],Xr.attempt.unlink(e)},purgeSync:(e)=>{if(!Bi.store[e])return;delete Bi.store[e],Xr.attempt.unlinkSync(e)},purgeSyncAll:()=>{for(let e in Bi.store)Bi.purgeSync(e)},truncate:(e)=>{let t=x9.basename(e);if(t.length<=Sw)return e;let n=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(t);if(!n)return e;let r=t.length-Sw;return`${e.slice(0,-t.length)}${n[1]}${n[2].slice(0,-r)}${n[3]}`}};KT(Bi.purgeSyncAll);var Hm=Bi;function _w(e,t,n=FT){if(Dw(n))return _w(e,t,{encoding:n});let o={timeout:n.timeout??jT},a=null,c=null,l=null;try{let p=Xr.attempt.realpathSync(e),f=!!p;e=p||e,[c,a]=Hm.get(e,n.tmpCreate||Hm.create,n.tmpPurge!==!1);let h=zT&&hh(n.chown),b=hh(n.mode);if(f&&(h||b)){let v=Xr.attempt.statSync(e);if(v){if(n={...n},h)n.chown={uid:v.uid,gid:v.gid};if(b)n.mode=v.mode}}if(!f){let v=k9.dirname(e);Xr.attempt.mkdirSync(v,{mode:qT,recursive:!0})}if(l=Xr.retry.openSync(o)(c,"w",n.mode||ww),n.tmpCreated)n.tmpCreated(c);if(Dw(t))Xr.retry.writeSync(o)(l,t,0,n.encoding||PT);else if(!hh(t))Xr.retry.writeSync(o)(l,t,0,t.length,0);if(n.fsync!==!1)if(n.fsyncWait!==!1)Xr.retry.fsyncSync(o)(l);else Xr.attempt.fsync(l);if(Xr.retry.closeSync(o)(l),l=null,n.chown&&(n.chown.uid!==LT||n.chown.gid!==UT))Xr.attempt.chownSync(c,n.chown.uid,n.chown.gid);if(n.mode&&n.mode!==ww)Xr.attempt.chmodSync(c,n.mode);try{Xr.retry.renameSync(o)(c,e)}catch(v){if(!MT(v))throw v;if(v.code!=="ENAMETOOLONG")throw v;Xr.retry.renameSync(o)(c,Hm.truncate(e))}a(),c=null}finally{if(l)Xr.attempt.closeSync(l);if(c)Hm.purge(c)}}var w1=yt(aq(),1),S1=yt(xq(),1);var wie=(e,t,n,r)=>{if(n==="length"||n==="prototype")return;if(n==="arguments"||n==="caller")return;let o=Object.getOwnPropertyDescriptor(e,n),a=Object.getOwnPropertyDescriptor(t,n);if(!Sie(o,a)&&r)return;Object.defineProperty(e,n,a)},Sie=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},Die=(e,t)=>{let n=Object.getPrototypeOf(t);if(n===Object.getPrototypeOf(e))return;Object.setPrototypeOf(e,n)},Bie=(e,t)=>`/* Wrapped ${e}*/
|
|
194
|
+
<%s key={someKey} {...props} />`,Qs,bi,$s,bi),gc[bi+Qs]=!0}}if(Q===n)Pr(dn);else Oo(dn);return dn}}var fr=Rl;ibe.Fragment=n,ibe.jsxDEV=fr})()});var Aw={};LZ(Aw,{program:()=>AT,createCommand:()=>hT,createOption:()=>yT,createArgument:()=>bT,Command:()=>vT,Option:()=>ET,Argument:()=>IT,Help:()=>CT,CommanderError:()=>wT,InvalidArgumentError:()=>ST,InvalidOptionArgumentError:()=>DT},{program:(BDe)=>AT=BDe,createCommand:(BDe)=>hT=BDe,createOption:(BDe)=>yT=BDe,createArgument:(BDe)=>bT=BDe,Command:(BDe)=>vT=BDe,Option:(BDe)=>ET=BDe,Argument:(BDe)=>IT=BDe,Help:(BDe)=>CT=BDe,CommanderError:(BDe)=>wT=BDe,InvalidArgumentError:(BDe)=>ST=BDe,InvalidOptionArgumentError:(BDe)=>DT=BDe});var{Argument:mT}=fh(),{Command:gw}=pT(),{CommanderError:A9,InvalidArgumentError:fT}=jm(),{Help:h9}=dw(),{Option:gT}=pw();var AT=new gw,hT=(e)=>new gw(e),yT=(e,t)=>new gT(e,t),bT=(e,t)=>new mT(e,t),vT=gw,ET=gT,IT=mT,CT=h9,wT=A9,ST=fT,DT=fT;var{program:xDe,createCommand:kDe,createArgument:RDe,createOption:TDe,CommanderError:BT,InvalidArgumentError:QDe,InvalidOptionArgumentError:$De,Command:_T,Argument:NDe,Option:ODe,Help:PDe}=Aw;var gh={name:"@sequenzy/cli",version:"0.0.198",description:"Sequenzy CLI for email marketing from the terminal",type:"module",bin:{sequenzy:"./dist/index.js"},main:"./src/index.tsx",types:"./src/index.tsx",exports:{".":"./src/index.tsx"},scripts:{dev:"bun --watch src/index.tsx",build:"bun ../../scripts/build-ink-cli.ts",start:"node dist/index.js",lint:"eslint src","type-check":"bun check",test:"sh ../../scripts/run-package-tests.sh src","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{commander:"^12.1.0",ink:"^5.0.1","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","ink-select-input":"^6.0.0","ink-table":"^3.1.0",open:"^10.1.0",react:"^18.3.1",conf:"^13.0.0"},devDependencies:{"@emailer/shared":"workspace:*","@types/bun":"latest","@types/node":"^22.0.0","@types/react":"^18.3.0","bun-types":"latest",typescript:"^7.0.2"},files:["dist"],keywords:["sequenzy","email","cli","marketing"],license:"MIT",repository:{type:"git",url:"https://github.com/sequenzy/sequenzy"}};import{isDeepStrictEqual as Rce}from"node:util";import E1 from"node:process";import au from"node:fs";import I1 from"node:path";import ff from"node:crypto";import Tce from"node:assert";var eu=(e)=>{let t=typeof e;return e!==null&&(t==="object"||t==="function")};var hw=new Set(["__proto__","prototype","constructor"]),b9=new Set("0123456789");function Ah(e){let t=[],n="",r="start",o=!1;for(let a of e)switch(a){case"\\":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(o)n+=a;r="property",o=!o;break}case".":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="property";break}if(o){o=!1,n+=a;break}if(hw.has(n))return[];t.push(n),n="",r="property";break}case"[":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="index";break}if(o){o=!1,n+=a;break}if(r==="property"){if(hw.has(n))return[];t.push(n),n=""}r="index";break}case"]":{if(r==="index"){t.push(Number.parseInt(n,10)),n="",r="indexEnd";break}if(r==="indexEnd")throw Error("Invalid character after an index")}default:{if(r==="index"&&!b9.has(a))throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(r==="start")r="property";if(o)o=!1,n+="\\";n+=a}}if(o)n+="\\";switch(r){case"property":{if(hw.has(n))return[];t.push(n);break}case"index":throw Error("Index was not closed");case"start":{t.push("");break}}return t}function yw(e,t){if(typeof t!=="number"&&Array.isArray(e)){let n=Number.parseInt(t,10);return Number.isInteger(n)&&e[n]===e[t]}return!1}function xT(e,t){if(yw(e,t))throw Error("Cannot use string index")}function kT(e,t,n){if(!eu(e)||typeof t!=="string")return n===void 0?e:n;let r=Ah(t);if(r.length===0)return n;for(let o=0;o<r.length;o++){let a=r[o];if(yw(e,a))e=o===r.length-1?void 0:null;else e=e[a];if(e===void 0||e===null){if(o!==r.length-1)return n;break}}return e===void 0?n:e}function bw(e,t,n){if(!eu(e)||typeof t!=="string")return e;let r=e,o=Ah(t);for(let a=0;a<o.length;a++){let c=o[a];if(xT(e,c),a===o.length-1)e[c]=n;else if(!eu(e[c]))e[c]=typeof o[a+1]==="number"?[]:{};e=e[c]}return r}function RT(e,t){if(!eu(e)||typeof t!=="string")return!1;let n=Ah(t);for(let r=0;r<n.length;r++){let o=n[r];if(xT(e,o),r===n.length-1)return delete e[o],!0;if(e=e[o],!eu(e))return!1}}function TT(e,t){if(!eu(e)||typeof t!=="string")return!1;let n=Ah(t);if(n.length===0)return!1;for(let r of n){if(!eu(e)||!(r in e)||yw(e,r))return!1;e=e[r]}return!0}import Yn from"node:path";import QT from"node:os";import vw from"node:process";var Nc=QT.homedir(),Ew=QT.tmpdir(),{env:Cd}=vw,v9=(e)=>{let t=Yn.join(Nc,"Library");return{data:Yn.join(t,"Application Support",e),config:Yn.join(t,"Preferences",e),cache:Yn.join(t,"Caches",e),log:Yn.join(t,"Logs",e),temp:Yn.join(Ew,e)}},E9=(e)=>{let t=Cd.APPDATA||Yn.join(Nc,"AppData","Roaming"),n=Cd.LOCALAPPDATA||Yn.join(Nc,"AppData","Local");return{data:Yn.join(n,e,"Data"),config:Yn.join(t,e,"Config"),cache:Yn.join(n,e,"Cache"),log:Yn.join(n,e,"Log"),temp:Yn.join(Ew,e)}},I9=(e)=>{let t=Yn.basename(Nc);return{data:Yn.join(Cd.XDG_DATA_HOME||Yn.join(Nc,".local","share"),e),config:Yn.join(Cd.XDG_CONFIG_HOME||Yn.join(Nc,".config"),e),cache:Yn.join(Cd.XDG_CACHE_HOME||Yn.join(Nc,".cache"),e),log:Yn.join(Cd.XDG_STATE_HOME||Yn.join(Nc,".local","state"),e),temp:Yn.join(Ew,t,e)}};function Iw(e,{suffix:t="nodejs"}={}){if(typeof e!=="string")throw TypeError(`Expected a string, got ${typeof e}`);if(t)e+=`-${t}`;if(vw.platform==="darwin")return v9(e);if(vw.platform==="win32")return E9(e);return I9(e)}import k9 from"node:path";import nn from"node:fs";import{promisify as So}from"node:util";var C9=(e,t)=>{let{onError:n}=t;return function(...o){return e.apply(void 0,o).catch(n)}},ra=C9;var w9=(e,t)=>{let{onError:n}=t;return function(...o){try{return e.apply(void 0,o)}catch(a){return n(a)}}},bs=w9;var $T=250;var S9=(e,t)=>{let{isRetriable:n}=t;return function(o){let{timeout:a}=o,c=o.interval??$T,l=Date.now()+a;return function p(...f){return e.apply(void 0,f).catch((h)=>{if(!n(h))throw h;if(Date.now()>=l)throw h;let b=Math.round(c*Math.random());if(b>0)return new Promise((C)=>setTimeout(C,b)).then(()=>p.apply(void 0,f));else return p.apply(void 0,f)})}}},oa=S9;var D9=(e,t)=>{let{isRetriable:n}=t;return function(o){let{timeout:a}=o,c=Date.now()+a;return function(...p){while(!0)try{return e.apply(void 0,p)}catch(f){if(!n(f))throw f;if(Date.now()>=c)throw f;continue}}}},ia=D9;import OT from"node:process";var zm={isChangeErrorOk:(e)=>{if(!zm.isNodeError(e))return!1;let{code:t}=e;if(t==="ENOSYS")return!0;if(!NT&&(t==="EINVAL"||t==="EPERM"))return!0;return!1},isNodeError:(e)=>e instanceof Error,isRetriableError:(e)=>{if(!zm.isNodeError(e))return!1;let{code:t}=e;if(t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM")return!0;return!1},onChangeError:(e)=>{if(!zm.isNodeError(e))throw e;if(zm.isChangeErrorOk(e))return;throw e}},Cw=zm;var Mm={onError:Cw.onChangeError},ri={onError:()=>{return}},NT=OT.getuid?!OT.getuid():!1,ho={isRetriable:Cw.isRetriableError};var B9={attempt:{chmod:ra(So(nn.chmod),Mm),chown:ra(So(nn.chown),Mm),close:ra(So(nn.close),ri),fsync:ra(So(nn.fsync),ri),mkdir:ra(So(nn.mkdir),ri),realpath:ra(So(nn.realpath),ri),stat:ra(So(nn.stat),ri),unlink:ra(So(nn.unlink),ri),chmodSync:bs(nn.chmodSync,Mm),chownSync:bs(nn.chownSync,Mm),closeSync:bs(nn.closeSync,ri),existsSync:bs(nn.existsSync,ri),fsyncSync:bs(nn.fsync,ri),mkdirSync:bs(nn.mkdirSync,ri),realpathSync:bs(nn.realpathSync,ri),statSync:bs(nn.statSync,ri),unlinkSync:bs(nn.unlinkSync,ri)},retry:{close:oa(So(nn.close),ho),fsync:oa(So(nn.fsync),ho),open:oa(So(nn.open),ho),readFile:oa(So(nn.readFile),ho),rename:oa(So(nn.rename),ho),stat:oa(So(nn.stat),ho),write:oa(So(nn.write),ho),writeFile:oa(So(nn.writeFile),ho),closeSync:ia(nn.closeSync,ho),fsyncSync:ia(nn.fsyncSync,ho),openSync:ia(nn.openSync,ho),readFileSync:ia(nn.readFileSync,ho),renameSync:ia(nn.renameSync,ho),statSync:ia(nn.statSync,ho),writeSync:ia(nn.writeSync,ho),writeFileSync:ia(nn.writeFileSync,ho)}},Xr=B9;import tu from"node:process";var PT="utf8",ww=438,qT=511;var FT={},LT=tu.geteuid?tu.geteuid():-1,UT=tu.getegid?tu.getegid():-1;var jT=1000,zT=!!tu.getuid,fBe=tu.getuid?!tu.getuid():!1,Sw=128;var MT=(e)=>e instanceof Error&&("code"in e);var Dw=(e)=>typeof e==="string",hh=(e)=>e===void 0;import x9 from"node:path";import wd from"node:process";import HT from"node:process";var GT=HT.platform==="linux",yh=HT.platform==="win32";var Bw=["SIGHUP","SIGINT","SIGTERM"];if(!yh)Bw.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(GT)Bw.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var JT=Bw;class WT{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=(e)=>{if(this.exited)return;this.exited=!0;for(let t of this.callbacks)t();if(e)if(yh&&(e!=="SIGINT"&&e!=="SIGTERM"&&e!=="SIGKILL"))wd.kill(wd.pid,"SIGTERM");else wd.kill(wd.pid,e)},this.hook=()=>{wd.once("exit",()=>this.exit());for(let e of JT)try{wd.once(e,()=>this.exit(e))}catch{}},this.register=(e)=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}}var VT=new WT;var _9=VT.register,KT=_9;var Bi={store:{},create:(e)=>{let t=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6),n=Date.now().toString().slice(-10),r="tmp-",o=`.tmp-${n}${t}`;return`${e}${o}`},get:(e,t,n=!0)=>{let r=Bi.truncate(t(e));if(r in Bi.store)return Bi.get(e,t,n);return Bi.store[r]=n,[r,()=>delete Bi.store[r]]},purge:(e)=>{if(!Bi.store[e])return;delete Bi.store[e],Xr.attempt.unlink(e)},purgeSync:(e)=>{if(!Bi.store[e])return;delete Bi.store[e],Xr.attempt.unlinkSync(e)},purgeSyncAll:()=>{for(let e in Bi.store)Bi.purgeSync(e)},truncate:(e)=>{let t=x9.basename(e);if(t.length<=Sw)return e;let n=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(t);if(!n)return e;let r=t.length-Sw;return`${e.slice(0,-t.length)}${n[1]}${n[2].slice(0,-r)}${n[3]}`}};KT(Bi.purgeSyncAll);var Hm=Bi;function _w(e,t,n=FT){if(Dw(n))return _w(e,t,{encoding:n});let o={timeout:n.timeout??jT},a=null,c=null,l=null;try{let p=Xr.attempt.realpathSync(e),f=!!p;e=p||e,[c,a]=Hm.get(e,n.tmpCreate||Hm.create,n.tmpPurge!==!1);let h=zT&&hh(n.chown),b=hh(n.mode);if(f&&(h||b)){let v=Xr.attempt.statSync(e);if(v){if(n={...n},h)n.chown={uid:v.uid,gid:v.gid};if(b)n.mode=v.mode}}if(!f){let v=k9.dirname(e);Xr.attempt.mkdirSync(v,{mode:qT,recursive:!0})}if(l=Xr.retry.openSync(o)(c,"w",n.mode||ww),n.tmpCreated)n.tmpCreated(c);if(Dw(t))Xr.retry.writeSync(o)(l,t,0,n.encoding||PT);else if(!hh(t))Xr.retry.writeSync(o)(l,t,0,t.length,0);if(n.fsync!==!1)if(n.fsyncWait!==!1)Xr.retry.fsyncSync(o)(l);else Xr.attempt.fsync(l);if(Xr.retry.closeSync(o)(l),l=null,n.chown&&(n.chown.uid!==LT||n.chown.gid!==UT))Xr.attempt.chownSync(c,n.chown.uid,n.chown.gid);if(n.mode&&n.mode!==ww)Xr.attempt.chmodSync(c,n.mode);try{Xr.retry.renameSync(o)(c,e)}catch(v){if(!MT(v))throw v;if(v.code!=="ENAMETOOLONG")throw v;Xr.retry.renameSync(o)(c,Hm.truncate(e))}a(),c=null}finally{if(l)Xr.attempt.closeSync(l);if(c)Hm.purge(c)}}var w1=yt(aq(),1),S1=yt(xq(),1);var wie=(e,t,n,r)=>{if(n==="length"||n==="prototype")return;if(n==="arguments"||n==="caller")return;let o=Object.getOwnPropertyDescriptor(e,n),a=Object.getOwnPropertyDescriptor(t,n);if(!Sie(o,a)&&r)return;Object.defineProperty(e,n,a)},Sie=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},Die=(e,t)=>{let n=Object.getPrototypeOf(t);if(n===Object.getPrototypeOf(e))return;Object.setPrototypeOf(e,n)},Bie=(e,t)=>`/* Wrapped ${e}*/
|
|
195
195
|
${t}`,_ie=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),xie=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),kie=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=Bie.bind(null,r,t.toString());Object.defineProperty(o,"name",xie);let{writable:a,enumerable:c,configurable:l}=_ie;Object.defineProperty(e,"toString",{value:o,writable:a,enumerable:c,configurable:l})};function kS(e,t,{ignoreNonConfigurable:n=!1}={}){let{name:r}=e;for(let o of Reflect.ownKeys(t))wie(e,t,o,n);return Die(e,t),kie(e,t,r),e}var Rie=(e,t={})=>{if(typeof e!=="function")throw TypeError(`Expected the first argument to be a function, got \`${typeof e}\``);let{wait:n=0,maxWait:r=Number.POSITIVE_INFINITY,before:o=!1,after:a=!0}=t;if(n<0||r<0)throw RangeError("`wait` and `maxWait` must not be negative.");if(!o&&!a)throw Error("Both `before` and `after` are false, function wouldn't be called.");let c,l,p,f=function(...h){let b=this,v=()=>{if(c=void 0,l)clearTimeout(l),l=void 0;if(a)p=e.apply(b,h)},C=()=>{if(l=void 0,c)clearTimeout(c),c=void 0;if(a)p=e.apply(b,h)},R=o&&!c;if(clearTimeout(c),c=setTimeout(v,n),r>0&&r!==Number.POSITIVE_INFINITY&&!l)l=setTimeout(C,r);if(R)p=e.apply(b,h);return p};return kS(f,e),f.cancel=()=>{if(c)clearTimeout(c),c=void 0;if(l)clearTimeout(l),l=void 0},f},RS=Rie;var cu=yt(h1(),1);var wce=Object.prototype.toString;function b1(e,t,n){if(!e)return!1;if(e.constructor===t)return!0;return wce.call(e)===n}function v1(e){return b1(e,Uint8Array,"[object Uint8Array]")}function Sce(e){return b1(e,ArrayBuffer,"[object ArrayBuffer]")}function Dce(e){return v1(e)||Sce(e)}function Bce(e){if(!v1(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function _ce(e){if(!Dce(e))throw TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``)}function HS(e,t){if(e.length===0)return new Uint8Array(0);t??=e.reduce((o,a)=>o+a.length,0);let n=new Uint8Array(t),r=0;for(let o of e)Bce(o),n.set(o,r),r+=o.length;return n}var y1={utf8:new globalThis.TextDecoder("utf8")};function GS(e,t="utf8"){return _ce(e),y1[t]??=new globalThis.TextDecoder(t),y1[t].decode(e)}function xce(e){if(typeof e!=="string")throw TypeError(`Expected \`string\`, got \`${typeof e}\``)}var kce=new globalThis.TextEncoder;function ky(e){return xce(e),kce.encode(e)}var tRe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));var Qce=S1.default.default,C1="aes-256-cbc",Yd=()=>Object.create(null),$ce=(e)=>e!==void 0&&e!==null,Nce=(e,t)=>{let n=new Set(["undefined","symbol","function"]),r=typeof t;if(n.has(r))throw TypeError(`Setting a value of type \`${r}\` for key \`${e}\` is not allowed as it's not supported by JSON`)},Ry="__internal__",JS=`${Ry}.migrations.version`;class Ty{path;events;#r;#t;#e;#n={};constructor(e={}){let t={configName:"config",fileExtension:"json",projectSuffix:"nodejs",clearInvalidConfig:!1,accessPropertiesByDotNotation:!0,configFileMode:438,...e};if(!t.cwd){if(!t.projectName)throw Error("Please specify the `projectName` option.");t.cwd=Iw(t.projectName,{suffix:t.projectSuffix}).config}if(this.#e=t,t.schema??t.ajvOptions??t.rootSchema){if(t.schema&&typeof t.schema!=="object")throw TypeError("The `schema` option must be an object.");let a=new w1.Ajv2020({allErrors:!0,useDefaults:!0,...t.ajvOptions});Qce(a);let c={...t.rootSchema,type:"object",properties:t.schema};this.#r=a.compile(c);for(let[l,p]of Object.entries(t.schema??{}))if(p?.default)this.#n[l]=p.default}if(t.defaults)this.#n={...this.#n,...t.defaults};if(t.serialize)this._serialize=t.serialize;if(t.deserialize)this._deserialize=t.deserialize;this.events=new EventTarget,this.#t=t.encryptionKey;let n=t.fileExtension?`.${t.fileExtension}`:"";this.path=I1.resolve(t.cwd,`${t.configName??"config"}${n}`);let r=this.store,o=Object.assign(Yd(),t.defaults,r);if(t.migrations){if(!t.projectVersion)throw Error("Please specify the `projectVersion` option.");this._migrate(t.migrations,t.projectVersion,t.beforeEachMigration)}this._validate(o);try{Tce.deepEqual(r,o)}catch{this.store=o}if(t.watch)this._watch()}get(e,t){if(this.#e.accessPropertiesByDotNotation)return this._get(e,t);let{store:n}=this;return e in n?n[e]:t}set(e,t){if(typeof e!=="string"&&typeof e!=="object")throw TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof e}`);if(typeof e!=="object"&&t===void 0)throw TypeError("Use `delete()` to clear values");if(this._containsReservedKey(e))throw TypeError(`Please don't use the ${Ry} key, as it's used to manage this module internal operations.`);let{store:n}=this,r=(o,a)=>{if(Nce(o,a),this.#e.accessPropertiesByDotNotation)bw(n,o,a);else n[o]=a};if(typeof e==="object"){let o=e;for(let[a,c]of Object.entries(o))r(a,c)}else r(e,t);this.store=n}has(e){if(this.#e.accessPropertiesByDotNotation)return TT(this.store,e);return e in this.store}reset(...e){for(let t of e)if($ce(this.#n[t]))this.set(t,this.#n[t])}delete(e){let{store:t}=this;if(this.#e.accessPropertiesByDotNotation)RT(t,e);else delete t[e];this.store=t}clear(){this.store=Yd();for(let e of Object.keys(this.#n))this.reset(e)}onDidChange(e,t){if(typeof e!=="string")throw TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof e}`);if(typeof t!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this._handleChange(()=>this.get(e),t)}onDidAnyChange(e){if(typeof e!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof e}`);return this._handleChange(()=>this.store,e)}get size(){return Object.keys(this.store).length}get store(){try{let e=au.readFileSync(this.path,this.#t?null:"utf8"),t=this._encryptData(e),n=this._deserialize(t);return this._validate(n),Object.assign(Yd(),n)}catch(e){if(e?.code==="ENOENT")return this._ensureDirectory(),Yd();if(this.#e.clearInvalidConfig&&e.name==="SyntaxError")return Yd();throw e}}set store(e){this._ensureDirectory(),this._validate(e),this._write(e),this.events.dispatchEvent(new Event("change"))}*[Symbol.iterator](){for(let[e,t]of Object.entries(this.store))yield[e,t]}_encryptData(e){if(!this.#t)return typeof e==="string"?e:GS(e);try{let t=e.slice(0,16),n=ff.pbkdf2Sync(this.#t,t.toString(),1e4,32,"sha512"),r=ff.createDecipheriv(C1,n,t),o=e.slice(17),a=typeof o==="string"?ky(o):o;return GS(HS([r.update(a),r.final()]))}catch{}return e.toString()}_handleChange(e,t){let n=e(),r=()=>{let o=n,a=e();if(Rce(a,o))return;n=a,t.call(this,a,o)};return this.events.addEventListener("change",r),()=>{this.events.removeEventListener("change",r)}}_deserialize=(e)=>JSON.parse(e);_serialize=(e)=>JSON.stringify(e,void 0,"\t");_validate(e){if(!this.#r)return;if(this.#r(e)||!this.#r.errors)return;let n=this.#r.errors.map(({instancePath:r,message:o=""})=>`\`${r.slice(1)}\` ${o}`);throw Error("Config schema violation: "+n.join("; "))}_ensureDirectory(){au.mkdirSync(I1.dirname(this.path),{recursive:!0})}_write(e){let t=this._serialize(e);if(this.#t){let n=ff.randomBytes(16),r=ff.pbkdf2Sync(this.#t,n.toString(),1e4,32,"sha512"),o=ff.createCipheriv(C1,r,n);t=HS([n,ky(":"),o.update(ky(t)),o.final()])}if(E1.env.SNAP)au.writeFileSync(this.path,t,{mode:this.#e.configFileMode});else try{_w(this.path,t,{mode:this.#e.configFileMode})}catch(n){if(n?.code==="EXDEV"){au.writeFileSync(this.path,t,{mode:this.#e.configFileMode});return}throw n}}_watch(){if(this._ensureDirectory(),!au.existsSync(this.path))this._write(Yd());if(E1.platform==="win32")au.watch(this.path,{persistent:!1},RS(()=>{this.events.dispatchEvent(new Event("change"))},{wait:100}));else au.watchFile(this.path,{persistent:!1},RS(()=>{this.events.dispatchEvent(new Event("change"))},{wait:5000}))}_migrate(e,t,n){let r=this._get(JS,"0.0.0"),o=Object.keys(e).filter((c)=>this._shouldPerformMigration(c,r,t)),a={...this.store};for(let c of o)try{if(n)n(this,{fromVersion:r,toVersion:c,finalVersion:t,versions:o});let l=e[c];l?.(this),this._set(JS,c),r=c,a={...this.store}}catch(l){throw this.store=a,Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${l}`)}if(this._isVersionInRangeFormat(r)||!cu.default.eq(r,t))this._set(JS,t)}_containsReservedKey(e){if(typeof e==="object"){if(Object.keys(e)[0]===Ry)return!0}if(typeof e!=="string")return!1;if(this.#e.accessPropertiesByDotNotation){if(e.startsWith(`${Ry}.`))return!0;return!1}return!1}_isVersionInRangeFormat(e){return cu.default.clean(e)===null}_shouldPerformMigration(e,t,n){if(this._isVersionInRangeFormat(e)){if(t!=="0.0.0"&&cu.default.satisfies(t,e))return!1;return cu.default.satisfies(n,e)}if(cu.default.lte(e,t))return!1;if(cu.default.gt(e,n))return!1;return!0}_get(e,t){return kT(this.store,e,t)}_set(e,t){let{store:n}=this;bw(n,e,t),this.store=n}}var WS="com.sequenzy.cli",VS="api-key",KS=typeof globalThis.Bun<"u",nl=new Ty({projectName:"sequenzy",schema:{userId:{type:"string"},userEmail:{type:"string"},_apiKey:{type:"string"}}});async function YS(){let e=process.env.SEQUENZY_API_KEY;if(e)return e;if(KS)try{let t=await globalThis.Bun.secrets.get({service:WS,name:VS});if(t)return t}catch{}return nl.get("_apiKey")}async function D1(e){if(KS)try{await globalThis.Bun.secrets.set({service:WS,name:VS,value:e,allowUnrestrictedAccess:!1});return}catch{}nl.set("_apiKey",e)}async function B1(){if(KS)try{await globalThis.Bun.secrets.delete({service:WS,name:VS})}catch{}nl.delete("_apiKey")}async function j(){return!!await YS()}function Qy(){return{userId:nl.get("userId"),userEmail:nl.get("userEmail")}}function _1(e){if(e.userId!==void 0)nl.set("userId",e.userId);if(e.userEmail!==void 0)nl.set("userEmail",e.userEmail)}function x1(){nl.clear()}function $y(e,t=Date.now()){if(!e?.trim())return;let n=e.trim();if(/^\d+$/.test(n)){let o=Number(n);return Number.isSafeInteger(o)?o:void 0}if(!/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);if(!Number.isFinite(r)||new Date(r).toUTCString().slice(5)!==n.slice(5))return;return Math.max(0,Math.ceil((r-t)/1000))}function k1(e,t,n){if(e&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e))return e;switch(t){case 0:return"NETWORK_ERROR";case 400:case 422:return"VALIDATION_ERROR";case 401:return"UNAUTHORIZED";case 403:return"FORBIDDEN";case 404:return"NOT_FOUND";case 409:return"CONFLICT";case 429:return"RATE_LIMITED";default:return t!==void 0?t>=500?"SERVER_ERROR":"HTTP_ERROR":n}}var Oce=new Set([502,503,504]),Pce=[250,1000,2000],qce=5000,Fce=(e)=>new Promise((t)=>setTimeout(t,e));async function R1(e,t,{delaysMs:n=Pce,sleep:r=Fce}={}){let o=e==="GET"?n.length:0;for(let a=0;a<o;a+=1){let c=n[a]??0,l;try{l=await t()}catch{await r(c);continue}if(!Oce.has(l.status))return l;let p=($y(l.headers.get("Retry-After"))??0)*1000;if(p>qce)return l;await l.body?.cancel().catch(()=>{return}),await r(Math.max(c,p))}return t()}var Lce=process.env.SEQUENZY_API_URL??"https://api.sequenzy.com";class A extends Error{statusCode;rawDetails;code;retryAfterSeconds;constructor(e,t,n,r,o){super(e);this.statusCode=t;this.rawDetails=n;this.code=r;this.retryAfterSeconds=o;this.name="ApiError"}}function Uce(e,t){if(typeof e!=="string")return;if(typeof t!=="string"||t==="root")return e;let n=t.slice(1).replaceAll("/",".");return e.includes(`'${n}'`)?e:`${n}: ${e}`}function jce(e){if(!e.trim())return{message:"Request failed"};try{let t=JSON.parse(e);if(typeof t==="string")return{message:t};if(!t||typeof t!=="object"||Array.isArray(t))return{message:"Request failed"};let n=t,r=n.error&&typeof n.error==="object"?n.error:void 0,o=r?.code??n.code,a=n.type==="validation"?Uce(n.summary,n.property):void 0,c=typeof n.error==="string"?n.error:typeof a==="string"?a:r?.message??n.message;return{message:typeof c==="string"?c:"Request failed",...typeof o==="string"?{code:o}:{}}}catch{return{message:e}}}async function E(e,t,n,r,o){let a=await YS();if(!a)throw new A("Not logged in. Run `sequenzy login` first.",401);let c={"Content-Type":"application/json",Authorization:`Bearer ${a}`,"x-sequenzy-client":`cli/${gh.version}`};if(r)c["x-company-id"]=r;Object.assign(c,o);let l;try{l=await R1(e,()=>fetch(`${Lce}${t}`,{method:e,headers:c,body:n?JSON.stringify(n):void 0}))}catch(p){throw new A(p instanceof Error?p.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!l.ok){let p=await l.text(),f=jce(p);throw new A(f.message,l.status,p,f.code,$y(l.headers.get("Retry-After")))}return l.json()}var T1=!1;function ZS(e){T1=e}function Ny(){return T1}var e0="https://docs.sequenzy.com",Ka=`${e0}/concepts/cli`,XS=`${e0}/authentication`,Q1="https://sequenzy.com/dashboard";function $1(e){if(e instanceof A)return{message:e.message,statusCode:e.statusCode,code:e.code,rawDetails:e.rawDetails};if(e instanceof Error)return{message:e.message};return{message:String(e)}}function zce(e){let t=e.match(/api key is missing required scopes?:\s*(.+)$/i);if(!t?.[1])return[];return[...new Set(t[1].match(/[a-z_]+:[a-z_]+/gi)??[])]}function N1(e){let t=$1(e),n=t.message.trim()||"Unknown error",r=n.toLowerCase(),o=t.rawDetails?.trim()||n;if(t.code==="CLI_AUTH_REQUIRED"||r.includes("not logged in"))return{title:"Authentication required",description:"This command needs a Sequenzy API key, but the CLI could not find one in your local login state or environment.",howToFix:"Run `sequenzy login` and approve the session, or set `SEQUENZY_API_KEY` for non-interactive environments.",docsUrl:Ka,details:o};if(r.includes("already logged in"))return{title:"CLI already authenticated",description:"The CLI already has a saved Sequenzy login for this machine.",howToFix:"Run `sequenzy logout` first if you want to switch accounts, then run `sequenzy login` again.",docsUrl:Ka,details:o};if(t.statusCode===401||t.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The request reached Sequenzy, but the current API key was rejected.",howToFix:"Run `sequenzy login` again, or replace the key with a valid personal API key that still has access to your account.",docsUrl:XS,details:o};if(t.code==="COMPANY_CREATE_REQUIRES_PERSONAL_KEY")return{title:"Personal account key required",description:"Company creation is account-level and cannot be performed with a company/workspace-scoped API key.",howToFix:"Create or use a personal account key beginning with `seq_user_` from Account → API Keys, replace `SEQUENZY_API_KEY`, and retry the same command; alternatively, create the company in the Sequenzy dashboard. Widening the current company key or switching companies will not fix this restriction.",docsUrl:XS,details:o};let a=zce(n);if(a.length>0){let c=a.map((f)=>`\`${f}\``).join(", "),l=a.every((f)=>f.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions",p=a.includes("api_keys:manage")?` This command manages API keys, so the missing scope cannot be granted through the API by the key that is missing it. If the active key has \`account:read\`, run \`sequenzy api-keys handoff\` (add \`--replaces current\` when rotating) to get a dashboard link that opens the create-key form prefilled, then give it to the workspace owner. It creates nothing and never prints a key. If handoff is also denied because \`account:read\` is missing, open ${Q1} directly and choose the matching API Keys page.`:"";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${a.length===1?"scope":"scopes"}: ${c}.`,howToFix:`Permissions can be widened on the key you are already using - no new key and no re-login. Run \`sequenzy account\` to see the active key, its type, and its API Keys settings URL, then have the key owner enable ${c} there. Personal keys open Account → API Keys; company keys open workspace Settings → API Keys. If account metadata is unavailable, open ${Q1} directly and choose the matching API Keys page. When the active key type is \`company\` and it holds \`api_keys:manage\`, run \`sequenzy api-keys list --json\` and then \`sequenzy api-keys update <api-key-id> --scopes\` with the current scopes plus ${c}, or \`--preset\` covering all of them (${l}). Personal keys cannot be changed through \`sequenzy api-keys update\`. Both options replace the whole selection rather than merging. Retry the same command once the key is updated. Issuing a replacement key and swapping \`SEQUENZY_API_KEY\` also works but is not required.${p}`,docsUrl:Ka,details:o}}if(t.statusCode===403||r.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to perform this action or access the requested company.",howToFix:"Use an API key with access to the target company, or switch to a company you can access before retrying.",docsUrl:XS,details:o};if(t.statusCode===404||r.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the company, template, campaign, sequence, or subscriber you asked for.",howToFix:"Double-check the ID or email value and list the resource first before retrying the command.",docsUrl:Ka,details:o};if(t.statusCode===429||r.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this request because too many requests were sent in a short period.",howToFix:"Wait a moment and retry. If an agent is looping, reduce the retry frequency before calling the CLI again.",docsUrl:Ka,details:o};if(t.code==="AB_TEST_VARIANT_CONTENT_EDIT"||r.includes("update_ab_test_variant")&&(r.includes("a/b test")||r.includes("ab test")))return{title:"A/B variant copy cannot be edited here",description:n,howToFix:"Use `sequenzy ab-tests update-variant` with the `abTestId` and `variantId` from `sequenzy sequences get` or `sequenzy ab-tests get`. Repeat once per variant for a whole-step rewrite. If the sequence is live or the test has activity, pass `--confirm-live-change`. Do not retry with `sequenzy templates update` or `sequenzy sequences update-node`.",docsUrl:`${e0}/concepts/cli#editing-the-copy-of-a-sequence-ab-step`,details:o};if(r.includes("--subject")||r.includes("--template")||r.includes("is required"))return{title:"Invalid command input",description:"The CLI command arguments are incomplete or incompatible for this action.",howToFix:"Review the flags you passed, add the missing values, and run the command again.",docsUrl:Ka,details:o};if(t.code==="NETWORK_ERROR"||r.includes("fetch failed")||r.includes("failed to initiate login"))return{title:"Network or configuration error",description:"The CLI could not reach the Sequenzy API or app URL from this environment.",howToFix:"Check your network connection and verify `SEQUENZY_API_URL` or `SEQUENZY_APP_URL` if you override them locally.",docsUrl:Ka,details:o};if(t.statusCode&&t.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If the error persists, keep the details below and check the docs before escalating.",docsUrl:Ka,details:o};return{title:"Command failed",description:"The CLI could not complete the requested operation.",howToFix:"Review the details below, adjust the command or credentials, and retry.",docsUrl:Ka,details:o}}function M(){return new A("Not logged in. Run `sequenzy login` first.",401,void 0,"CLI_AUTH_REQUIRED")}function gf(e){let t=N1(e);return[`Sequenzy CLI error: ${t.title}`,`Description: ${t.description}`,`How to fix: ${t.howToFix}`,`Docs: ${t.docsUrl}`,`Details: ${t.details}`].join(`
|
|
196
196
|
`)}function Mce(e){let t=$1(e),n=N1(e),r=(t.rawDetails===t.message?n.description:t.message.trim())||n.description;return{success:!1,error:{code:k1(t.code,t.statusCode,"CLI_ERROR"),message:r.replace(/\bBearer\s+[^\s]+/gi,"Bearer [redacted]").replace(/\bseq_(?:user_)?[A-Za-z0-9_-]{8,}\b/g,"[redacted key]"),...t.statusCode!==void 0?{statusCode:t.statusCode}:{},howToFix:n.howToFix,docsUrl:n.docsUrl,...e instanceof A&&e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}}}}function k(e,t={}){console.error(t.json??Ny()?JSON.stringify(Mce(e)):gf(e))}import{readFileSync as Hce}from"node:fs";import{isatty as O1}from"node:tty";var rl;function P1(){rl=void 0}function t0(e){if(new Set(e).size>1)throw new A("Only one text input may read stdin (-) per command. Use regular files for the other inputs.",400,void 0,"CLI_INVALID_INPUT")}async function q1(){if(O1(0))throw new A("Pipe text into stdin when using a text file '-'.",400,void 0,"CLI_INVALID_INPUT");try{process.stdin.setEncoding("utf8");let e="";for await(let t of process.stdin)e+=String(t);rl={text:e}}catch(e){throw new A(`Failed to read stdin: ${e instanceof Error?e.message:"Unknown error"}`,400,void 0,"CLI_INPUT_READ_FAILED")}}function F1(e,t){if(e==="-"){if(rl){if(rl.field)t0([rl.field,t]);return rl.field=t,rl.text}if(O1(0))throw new A(`Pipe text into stdin when using ${t} file '-'.`,400,void 0,"CLI_INVALID_INPUT")}try{let n=Hce(e==="-"?0:e,"utf8");if(e==="-")rl={field:t,text:n};return n}catch(n){throw new A(`Failed to read ${t} file '${e}': ${n instanceof Error?n.message:"Unknown error"}`,400,void 0,"CLI_INPUT_READ_FAILED")}}function Oy(e){return e.optsWithGlobals().json===!0||e.commands.some(Oy)}async function Gce(e){ZS(e.optsWithGlobals().json===!0),P1();let t=Object.entries(e.optsWithGlobals()).filter(([n,r])=>r==="-"&&n.endsWith("File")||n==="audienceJson"&&r==="@-").map(([n])=>n);if(e.parent?.name()==="subscribers"&&["import","events-import"].includes(e.name())&&e.args[0]==="-")t.push("subscriber import");if(t0(t),t.length>0)await q1()}function L1(e){let t=e.configureOutput().writeErr;e.configureOutput({writeErr:(n)=>{if(!Oy(e))t?.(n)}}),e.exitOverride(),e.hook("preAction",(n,r)=>Gce(r))}async function U1(e,t){ZS(!1);try{await e.parseAsync(t)}catch(n){if(n instanceof BT){if(n.exitCode===0)return;if(Oy(e))k(new A(n.message,400,void 0,"CLI_INVALID_INPUT"),{json:!0});process.exitCode=n.exitCode;return}k(n,{json:Oy(e)}),process.exitCode=1}}var Py="Variant copy is edited with `sequenzy ab-tests update-variant`, not with `sequenzy sequences update-node`.";var j1;function ce(e,t,n){function r(l,p){if(!l._zod)Object.defineProperty(l,"_zod",{value:{def:p,constr:c,traits:new Set},enumerable:!1});if(l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,p);let f=c.prototype,h=Object.keys(f);for(let b=0;b<h.length;b++){let v=h[b];if(!(v in l))l[v]=f[v].bind(l)}}let o=n?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function c(l){var p;let f=n?.Parent?new a:this;r(f,l),(p=f._zod).deferred??(p.deferred=[]);for(let h of f._zod.deferred)h();return f}return Object.defineProperty(c,"init",{value:r}),Object.defineProperty(c,Symbol.hasInstance,{value:(l)=>{if(n?.Parent&&l instanceof n.Parent)return!0;return l?._zod?.traits?.has(e)}}),Object.defineProperty(c,"name",{value:e}),c}var URe=Symbol("zod_brand");class Ya extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Af extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(j1=globalThis).__zod_globalConfig??(j1.__zod_globalConfig={});var Zd=globalThis.__zod_globalConfig;function Za(e){if(e)Object.assign(Zd,e);return Zd}function Fy(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function yf(e,t){if(typeof t==="bigint")return t.toString();return t}function Ly(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function Uy(e){return e===null||e===void 0}function jy(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var z1=Symbol("evaluating");function hn(e,t,n){let r=void 0;Object.defineProperty(e,t,{get(){if(r===z1)return;if(r===void 0)r=z1,r=n();return r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function lu(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ol(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function r0(e){return JSON.stringify(e)}function M1(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var o0="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function hf(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var H1=Ly(()=>{if(Zd.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Xd(e){if(hf(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(hf(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function i0(e){if(Xd(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var G1=new Set(["string","number","symbol"]);function il(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function va(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function bt(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function J1(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Jce={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]};function Wce(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let a=ol(e._zod.def,{get shape(){let c={};for(let l in t){if(!(l in n.shape))throw Error(`Unrecognized key: "${l}"`);if(!t[l])continue;c[l]=n.shape[l]}return lu(this,"shape",c),c},checks:[]});return va(e,a)}function Vce(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let a=ol(e._zod.def,{get shape(){let c={...e._zod.def.shape};for(let l in t){if(!(l in n.shape))throw Error(`Unrecognized key: "${l}"`);if(!t[l])continue;delete c[l]}return lu(this,"shape",c),c},checks:[]});return va(e,a)}function Kce(e,t){if(!Xd(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let a=e._zod.def.shape;for(let c in t)if(Object.getOwnPropertyDescriptor(a,c)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=ol(e._zod.def,{get shape(){let a={...e._zod.def.shape,...t};return lu(this,"shape",a),a}});return va(e,o)}function Yce(e,t){if(!Xd(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=ol(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return lu(this,"shape",r),r}});return va(e,n)}function Zce(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=ol(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return lu(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return va(e,n)}function Xce(e,t,n){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let c=ol(t._zod.def,{get shape(){let l=t._zod.def.shape,p={...l};if(n)for(let f in n){if(!(f in l))throw Error(`Unrecognized key: "${f}"`);if(!n[f])continue;p[f]=e?new e({type:"optional",innerType:l[f]}):l[f]}else for(let f in l)p[f]=e?new e({type:"optional",innerType:l[f]}):l[f];return lu(this,"shape",p),p},checks:[]});return va(t,c)}function ele(e,t,n){let r=ol(t._zod.def,{get shape(){let o=t._zod.def.shape,a={...o};if(n)for(let c in n){if(!(c in a))throw Error(`Unrecognized key: "${c}"`);if(!n[c])continue;a[c]=new e({type:"nonoptional",innerType:o[c]})}else for(let c in o)a[c]=new e({type:"nonoptional",innerType:o[c]});return lu(this,"shape",a),a}});return va(t,r)}function uu(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function W1(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function zy(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function qy(e){return typeof e==="string"?e:e?.message}function Xa(e,t,n){let r=e.message?e.message:qy(e.inst?._zod.def?.error?.(e))??qy(t?.error?.(e))??qy(n.customError?.(e))??qy(n.localeError?.(e))??"Invalid input",{inst:o,continue:a,input:c,...l}=e;if(l.path??(l.path=[]),l.message=r,t?.reportInput)l.input=c;return l}function My(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function du(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}var V1=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,yf,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Hy=ce("$ZodError",V1),s0=ce("$ZodError",V1,{Parent:Error});function K1(e,t=(n)=>n.message){let n={},r=[];for(let o of e.issues)if(o.path.length>0)n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o));else r.push(t(o));return{formErrors:r,fieldErrors:n}}function Y1(e,t=(n)=>n.message){let n={_errors:[]},r=(o,a=[])=>{for(let c of o.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map((l)=>r({issues:l},[...a,...c.path]));else if(c.code==="invalid_key")r({issues:c.issues},[...a,...c.path]);else if(c.code==="invalid_element")r({issues:c.issues},[...a,...c.path]);else{let l=[...a,...c.path];if(l.length===0)n._errors.push(t(c));else{let p=n,f=0;while(f<l.length){let h=l[f];if(f!==l.length-1)p[h]=p[h]||{_errors:[]};else p[h]=p[h]||{_errors:[]},p[h]._errors.push(t(c));p=p[h],f++}}}};return r(e),n}var Gy=(e)=>(t,n,r,o)=>{let a=r?{...r,async:!1}:{async:!1},c=t._zod.run({value:n,issues:[]},a);if(c instanceof Promise)throw new Ya;if(c.issues.length){let l=new(o?.Err??e)(c.issues.map((p)=>Xa(p,a,Za())));throw o0(l,o?.callee),l}return c.value};var Jy=(e)=>async(t,n,r,o)=>{let a=r?{...r,async:!0}:{async:!0},c=t._zod.run({value:n,issues:[]},a);if(c instanceof Promise)c=await c;if(c.issues.length){let l=new(o?.Err??e)(c.issues.map((p)=>Xa(p,a,Za())));throw o0(l,o?.callee),l}return c.value};var bf=(e)=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new Ya;return a.issues.length?{success:!1,error:new(e??Hy)(a.issues.map((c)=>Xa(c,o,Za())))}:{success:!0,data:a.value}},Z1=bf(s0),vf=(e)=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)a=await a;return a.issues.length?{success:!1,error:new e(a.issues.map((c)=>Xa(c,o,Za())))}:{success:!0,data:a.value}},X1=vf(s0),eL=(e)=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Gy(e)(t,n,o)};var tL=(e)=>(t,n,r)=>Gy(e)(t,n,r);var nL=(e)=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Jy(e)(t,n,o)};var rL=(e)=>async(t,n,r)=>Jy(e)(t,n,r);var oL=(e)=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return bf(e)(t,n,o)};var iL=(e)=>(t,n,r)=>bf(e)(t,n,r);var sL=(e)=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return vf(e)(t,n,o)};var aL=(e)=>async(t,n,r)=>vf(e)(t,n,r);var cL=/^[cC][0-9a-z]{6,}$/,lL=/^[0-9a-z]+$/,uL=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,dL=/^[0-9a-vA-V]{20}$/,pL=/^[A-Za-z0-9]{27}$/,mL=/^[a-zA-Z0-9_-]{21}$/,fL=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var gL=/^([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})$/,a0=(e)=>{if(!e)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}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var AL=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var nle="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function hL(){return new RegExp(nle,"u")}var yL=/^(?:(?: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])$/,bL=/^(([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}|:))$/;var vL=/^((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])$/,EL=/^(([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])$/,IL=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,c0=/^[A-Za-z0-9_-]*$/;var CL=/^https?$/,wL=/^\+[1-9]\d{6,14}$/,SL="(?:(?:\\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])))",DL=new RegExp(`^${SL}$`);function BL(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.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{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function _L(e){return new RegExp(`^${BL(e)}$`)}function xL(e){let t=BL({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${t}(?:${n.join("|")})`;return new RegExp(`^${SL}T(?:${r})$`)}var kL=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var RL=/^[^A-Z]*$/,TL=/^[^a-z]*$/;var _i=ce("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var QL=ce("$ZodCheckMaxLength",(e,t)=>{var n;_i.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let o=r.value;return!Uy(o)&&o.length!==void 0}),e._zod.onattach.push((r)=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<o)r._zod.bag.maximum=t.maximum}),e._zod.check=(r)=>{let o=r.value;if(o.length<=t.maximum)return;let c=My(o);r.issues.push({origin:c,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$L=ce("$ZodCheckMinLength",(e,t)=>{var n;_i.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let o=r.value;return!Uy(o)&&o.length!==void 0}),e._zod.onattach.push((r)=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>o)r._zod.bag.minimum=t.minimum}),e._zod.check=(r)=>{let o=r.value;if(o.length>=t.minimum)return;let c=My(o);r.issues.push({origin:c,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),NL=ce("$ZodCheckLengthEquals",(e,t)=>{var n;_i.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let o=r.value;return!Uy(o)&&o.length!==void 0}),e._zod.onattach.push((r)=>{let o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=(r)=>{let o=r.value,a=o.length;if(a===t.length)return;let c=My(o),l=a>t.length;r.issues.push({origin:c,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Ef=ce("$ZodCheckStringFormat",(e,t)=>{var n,r;if(_i.init(e,t),e._zod.onattach.push((o)=>{let a=o._zod.bag;if(a.format=t.format,t.pattern)a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),OL=ce("$ZodCheckRegex",(e,t)=>{Ef.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),PL=ce("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=RL),Ef.init(e,t)}),qL=ce("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=TL),Ef.init(e,t)}),FL=ce("$ZodCheckIncludes",(e,t)=>{_i.init(e,t);let n=il(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push((o)=>{let a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),LL=ce("$ZodCheckStartsWith",(e,t)=>{_i.init(e,t);let n=new RegExp(`^${il(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((r)=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),UL=ce("$ZodCheckEndsWith",(e,t)=>{_i.init(e,t);let n=new RegExp(`.*${il(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((r)=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});var jL=ce("$ZodCheckOverwrite",(e,t)=>{_i.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class l0{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
197
197
|
`).filter((a)=>a),r=Math.min(...n.map((a)=>a.length-a.trimStart().length)),o=n.map((a)=>a.slice(r)).map((a)=>" ".repeat(this.indent*2)+a);for(let a of o)this.content.push(a)}compile(){let e=Function,t=this?.args,r=[...(this?.content??[""]).map((o)=>` ${o}`)];return new e(...t,r.join(`
|
|
@@ -314,7 +314,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
|
|
|
314
314
|
Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);if(t.setEncoding("utf8"),e){if(this.rawModeEnabledCount===0)t.ref(),t.setRawMode(!0),t.addListener("readable",this.handleReadable);this.rawModeEnabledCount++;return}if(--this.rawModeEnabledCount===0)t.setRawMode(!1),t.removeListener("readable",this.handleReadable),t.unref()};handleReadable=()=>{let e;while((e=this.props.stdin.read())!==null)this.handleInput(e),this.internal_eventEmitter.emit("input",e)};handleInput=(e)=>{if(e==="\x03"&&this.props.exitOnCtrlC)this.handleExit();if(e===Lye&&this.state.activeFocusId)this.setState({activeFocusId:void 0});if(this.state.isFocusEnabled&&this.state.focusables.length>0){if(e===qye)this.focusNext();if(e===Fye)this.focusPrevious()}};handleExit=(e)=>{if(this.isRawModeSupported())this.handleSetRawMode(!1);this.props.onExit(e)};enableFocus=()=>{this.setState({isFocusEnabled:!0})};disableFocus=()=>{this.setState({isFocusEnabled:!1})};focus=(e)=>{this.setState((t)=>{if(!t.focusables.some((r)=>r?.id===e))return t;return{activeFocusId:e}})};focusNext=()=>{this.setState((e)=>{let t=e.focusables.find((r)=>r.isActive)?.id;return{activeFocusId:this.findNextFocusable(e)??t}})};focusPrevious=()=>{this.setState((e)=>{let t=e.focusables.findLast((r)=>r.isActive)?.id;return{activeFocusId:this.findPreviousFocusable(e)??t}})};addFocusable=(e,{autoFocus:t})=>{this.setState((n)=>{let r=n.activeFocusId;if(!r&&t)r=e;return{activeFocusId:r,focusables:[...n.focusables,{id:e,isActive:!0}]}})};removeFocusable=(e)=>{this.setState((t)=>({activeFocusId:t.activeFocusId===e?void 0:t.activeFocusId,focusables:t.focusables.filter((n)=>n.id!==e)}))};activateFocusable=(e)=>{this.setState((t)=>({focusables:t.focusables.map((n)=>{if(n.id!==e)return n;return{id:e,isActive:!0}})}))};deactivateFocusable=(e)=>{this.setState((t)=>({activeFocusId:t.activeFocusId===e?void 0:t.activeFocusId,focusables:t.focusables.map((n)=>{if(n.id!==e)return n;return{id:e,isActive:!1}})}))};findNextFocusable=(e)=>{let t=e.focusables.findIndex((n)=>n.id===e.activeFocusId);for(let n=t+1;n<e.focusables.length;n++){let r=e.focusables[n];if(r?.isActive)return r.id}return};findPreviousFocusable=(e)=>{let t=e.focusables.findIndex((n)=>n.id===e.activeFocusId);for(let n=t-1;n>=0;n--){let r=e.focusables[n];if(r?.isActive)return r.id}return}}var W3=()=>{};class hv{options;log;throttledLog;isUnmounted;lastOutput;container;rootNode;fullStaticOutput;exitPromise;restoreConsole;unsubscribeResize;constructor(e){if(ED(this),this.options=e,this.rootNode=qb("ink-root"),this.rootNode.onComputeLayout=this.calculateLayout,this.rootNode.onRender=e.debug?this.onRender:Bb(this.onRender,32,{leading:!0,trailing:!0}),this.rootNode.onImmediateRender=this.onRender,this.log=S3.create(e.stdout),this.throttledLog=e.debug?this.log:Bb(this.log,void 0,{leading:!0,trailing:!0}),this.isUnmounted=!1,this.lastOutput="",this.fullStaticOutput="",this.container=Ep.createContainer(this.rootNode,0,null,!1,null,"id",()=>{},null),this.unsubscribeExit=K3.default(this.unmount,{alwaysLast:!1}),Uye.env.DEV==="true")Ep.injectIntoDevTools({bundleType:0,version:"16.13.1",rendererPackageName:"ink"});if(e.patchConsole)this.patchConsole();if(!Iu)e.stdout.on("resize",this.resized),this.unsubscribeResize=()=>{e.stdout.off("resize",this.resized)}}resized=()=>{this.calculateLayout(),this.onRender()};resolveExitPromise=()=>{};rejectExitPromise=()=>{};unsubscribeExit=()=>{};calculateLayout=()=>{let e=this.options.stdout.columns||80;this.rootNode.yogaNode.setWidth(e),this.rootNode.yogaNode.calculateLayout(void 0,void 0,Ge.DIRECTION_LTR)};onRender=()=>{if(this.isUnmounted)return;let{output:e,outputHeight:t,staticOutput:n}=A3(this.rootNode),r=n&&n!==`
|
|
315
315
|
`;if(this.options.debug){if(r)this.fullStaticOutput+=n;this.options.stdout.write(this.fullStaticOutput+e);return}if(Iu){if(r)this.options.stdout.write(n);this.lastOutput=e;return}if(r)this.fullStaticOutput+=n;if(t>=this.options.stdout.rows){this.options.stdout.write($ge+this.fullStaticOutput+e),this.lastOutput=e;return}if(r)this.log.clear(),this.options.stdout.write(n),this.log(e);if(!r&&e!==this.lastOutput)this.throttledLog(e);this.lastOutput=e};render(e){let t=V3.default.createElement(Av,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,exitOnCtrlC:this.options.exitOnCtrlC,onExit:this.unmount},e);Ep.updateContainer(t,this.container,null,W3)}writeToStdout(e){if(this.isUnmounted)return;if(this.options.debug){this.options.stdout.write(e+this.fullStaticOutput+this.lastOutput);return}if(Iu){this.options.stdout.write(e);return}this.log.clear(),this.options.stdout.write(e),this.log(this.lastOutput)}writeToStderr(e){if(this.isUnmounted)return;if(this.options.debug){this.options.stderr.write(e),this.options.stdout.write(this.fullStaticOutput+this.lastOutput);return}if(Iu){this.options.stderr.write(e);return}this.log.clear(),this.options.stderr.write(e),this.log(this.lastOutput)}unmount(e){if(this.isUnmounted)return;if(this.calculateLayout(),this.onRender(),this.unsubscribeExit(),typeof this.restoreConsole==="function")this.restoreConsole();if(typeof this.unsubscribeResize==="function")this.unsubscribeResize();if(Iu)this.options.stdout.write(this.lastOutput+`
|
|
316
316
|
`);else if(!this.options.debug)this.log.done();if(this.isUnmounted=!0,Ep.updateContainer(null,this.container,null,W3),Dp.delete(this.options.stdout),e instanceof Error)this.rejectExitPromise(e);else this.resolveExitPromise()}async waitUntilExit(){return this.exitPromise||=new Promise((e,t)=>{this.resolveExitPromise=e,this.rejectExitPromise=t}),this.exitPromise}clear(){if(!Iu&&!this.options.debug)this.log.clear()}patchConsole(){if(this.options.debug)return;this.restoreConsole=oG((e,t)=>{if(e==="stdout")this.writeToStdout(t);if(e==="stderr"){if(!t.startsWith("The above error occurred"))this.writeToStderr(t)}})}}var zye=(e,t)=>{let n={stdout:yv.stdout,stdin:yv.stdin,stderr:yv.stderr,debug:!1,exitOnCtrlC:!0,patchConsole:!0,...Mye(t)},r=Hye(n.stdout,()=>new hv(n));return r.render(e),{rerender:r.render,unmount(){r.unmount()},waitUntilExit:r.waitUntilExit,cleanup:()=>Dp.delete(n.stdout),clear:r.clear}},ag=zye,Mye=(e={})=>{if(e instanceof jye)return{stdout:e,stdin:yv.stdin};return e},Hye=(e,t)=>{let n=Dp.get(e);if(!n)n=t(),Dp.set(e,n);return n};var bv=yt(In(),1);var Gye=yt(In(),1);var Jye=yt(In(),1);var Wye=yt(In(),1);var Zye=yt(In(),1);var Vye={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},Kye=[...Object.values(Vye),"backspace"];var Yye=yt(In(),1);var Xye=yt(In(),1);var ebe=yt(In(),1);var tbe=yt(In(),1);var kB=yt(In(),1);var nbe=yt(In(),1);var Bp=yt(In(),1);var n4=yt(t4(),1);function obe({type:e="dots"}){let[t,n]=Bp.useState(0),r=n4.default[e];return Bp.useEffect(()=>{let o=setInterval(()=>{n((a)=>a===r.frames.length-1?0:a+1)},r.interval);return()=>{clearInterval(o)}},[r]),Bp.default.createElement(me,null,r.frames[t])}var Ev=obe;var ns=yt(In(),1);var _a=yt(cg(),1),r4=50;function o4(e,t=[]){return[...t,e]}function sbe(e){if(!e||e.length===0)return;let t={},n=new Set;for(let r of e){let o=r.indexOf(":"),a=o===-1?"":r.slice(0,o).trim();if(!a)throw Error(`--header must look like "Name: value", got "${r}"`);if(n.has(a.toLowerCase()))throw Error(`--header ${a} was given more than once`);n.add(a.toLowerCase()),t[a]=r.slice(o+1).trim()}return t}function i4(e){return e.option("--cc <address>","Carbon-copy recipient, visible to everyone on the email (repeatable)",o4).option("--bcc <address>","Blind-carbon-copy recipient, hidden from the other recipients (repeatable)",o4)}function _p(e){let t=new Set,n=[];for(let r of e??[])for(let o of r.split(",")){let a=o.trim();if(a.length===0)continue;let c=a.toLowerCase();if(t.has(c))continue;t.add(c),n.push(a)}return n}function s4(e){let t=new Set(e.to.map((o)=>o.toLowerCase())),n=e.cc.filter((o)=>{let a=o.toLowerCase();if(t.has(a))return!1;return t.add(a),!0}),r=e.bcc.filter((o)=>{let a=o.toLowerCase();if(t.has(a))return!1;return t.add(a),!0});return{to:e.to,cc:n,bcc:r}}function TB(e,t){if(t.length>r4)throw Error(`${e} accepts at most ${r4} email addresses`)}function abe(e,t,n,r,o){let a=e.cc??[],c=e.bcc??[];return[`Email queued for ${e.to.join(", ")}`,...a.length>0?[`Cc: ${a.join(", ")}`]:[],...c.length>0?[`Bcc: ${c.join(", ")}`]:[],`Email send ID: ${t}`,...n?[`Delivery policy: ${n}`]:[],...r?[`Tracked as: ${r.slug}`]:[],...(o??[]).map((l)=>`Header not applied: ${l.name} (${l.reason})`),`Check status: sequenzy email-sends get ${t}`]}function cbe(e){return{to:Array.isArray(e.to)?e.to:[e.to],cc:e.cc,bcc:e.bcc}}function lbe(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function ube(e){let t={};if(e.varsJson){let n;try{n=JSON.parse(e.varsJson)}catch{throw Error("--vars-json must be valid JSON")}if(!lbe(n))throw Error("--vars-json must be a JSON object");t=n}for(let n of e.var??[]){let[r,o]=n.split("=");if(r&&o)t[r]=o}return t}function dbe(e,t){let n=ube(t),r=t.emailType?.trim().toLowerCase();if(r!==void 0&&r!=="marketing"&&r!=="transactional")throw Error("--email-type must be 'marketing' or 'transactional'");let o=s4({to:_p(Array.isArray(e)?e:[e]),cc:_p(t.cc),bcc:_p(t.bcc)}),{to:a,cc:c,bcc:l}=o;if(a.length===0)throw Error("At least one recipient email address is required");if(TB("A send",a),TB("--cc",c),TB("--bcc",l),r==="marketing"&&(a.length>1||c.length>0||l.length>0))throw Error("--email-type marketing supports exactly one recipient and does not allow --cc or --bcc");let p={to:a.length===1?a[0]:a,...c.length>0?{cc:c}:{},...l.length>0?{bcc:l}:{}};if(t.template!==void 0&&(t.subject!==void 0||t.html!==void 0||t.htmlFile!==void 0))throw Error("Use either --template or --subject with --html/--html-file, not both");if(t.fromEmail&&t.senderProfileId)throw Error("Use either --from-email or --sender-profile-id, not both");if(t.fromName&&!t.fromEmail)throw Error("--from-name requires --from-email");if(t.fromName&&t.senderProfileId)throw Error("Use either --from-name with --from-email, or --sender-profile-id, not both");if(t.replyTo&&t.replyProfile)throw Error("Use either --reply-to or --reply-profile, not both");if(t.replyToName&&!t.replyTo)throw Error("--reply-to-name requires --reply-to");if(t.replyToName&&t.replyProfile)throw Error("Use either --reply-to-name with --reply-to, or --reply-profile, not both");let f=kn(t.htmlFile?void 0:t.html,t.htmlFile,"html");if(!t.template&&!f)throw Error("Either --template or --html/--html-file is required");if(!t.template&&!t.subject)throw Error("--subject is required when using --html");if(t.template!==void 0&&t.trackAs!==void 0)throw Error("--track-as only applies to --subject with --html/--html-file; saved templates already track their own stats");let h={...t.trackClicks===!1?{clickTracking:!1}:{},...t.trackOpens===!1?{openTracking:!1}:{}},b=Object.keys(h).length>0?{trackingSettings:h}:{},v=V0(t.attachmentsJson),C=v?{attachments:v}:{},R=sbe(t.header),N=R?{headers:R}:{};return t.template?{...p,slug:t.template,...r?{emailType:r}:{},...t.replyTo?{replyTo:t.replyTo}:{},...t.fromEmail?{fromEmail:t.fromEmail}:{},...t.fromName?{fromName:t.fromName}:{},...t.senderProfileId?{senderProfileId:t.senderProfileId}:{},...t.replyProfile?{replyProfileId:t.replyProfile}:{},...t.replyToName?{replyToName:t.replyToName}:{},...C,...N,...b,variables:n}:{...p,subject:t.subject,body:f,...t.trackAs!==void 0?{trackAs:t.trackAs}:{},...r?{emailType:r}:{},...t.replyTo?{replyTo:t.replyTo}:{},...t.fromEmail?{fromEmail:t.fromEmail}:{},...t.fromName?{fromName:t.fromName}:{},...t.senderProfileId?{senderProfileId:t.senderProfileId}:{},...t.replyProfile?{replyProfileId:t.replyProfile}:{},...t.replyToName?{replyToName:t.replyToName}:{},...C,...N,...b,variables:n}}async function a4(e,t){return E("POST","/api/v1/transactional/send",dbe(e,t),t.company,t.idempotencyKey?{"Idempotency-Key":t.idempotencyKey}:void 0)}function pbe({emails:e,options:t}){let[n,r]=ns.useState(!0),[o,a]=ns.useState(""),[c,l]=ns.useState(!1),[p,f]=ns.useState(""),[h,b]=ns.useState("transactional"),[v,C]=ns.useState(),[R,N]=ns.useState(),L=s4({to:_p(e),cc:_p(t.cc),bcc:_p(t.bcc)}),[K,_e]=ns.useState(null);if(ns.useEffect(()=>{async function le(){try{let Z=await a4(e,t);f(Z.emailSendId),b(Z.emailType),C(Z.transactional),N(Z.ignoredHeaders),_e(cbe(Z)),l(!0)}catch(Z){a(gf(Z))}finally{r(!1)}}le()},[e,t]),ns.useEffect(()=>{if(!n)setTimeout(()=>process.exit(o?1:0),100)},[n,o]),n)return _a.jsxDEV(Re,{padding:1,children:[_a.jsxDEV(me,{color:"cyan",children:_a.jsxDEV(Ev,{type:"dots"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_a.jsxDEV(me,{children:[" Sending email to ",L.to.join(", "),"..."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(o)return _a.jsxDEV(Re,{padding:1,children:_a.jsxDEV(me,{color:"red",children:[" ",o]},void 0,!0,void 0,this)},void 0,!1,void 0,this);return _a.jsxDEV(Re,{padding:1,flexDirection:"column",children:abe(K??L,p,h,v,R).map((le,Z)=>_a.jsxDEV(me,{color:Z===0?"green":void 0,children:[Z===0?" ":"",le]},le,!0,void 0,this))},void 0,!1,void 0,this)}async function c4(e,t){if(!await j())k(M(),{json:t.json}),process.exit(1);if(t.json){try{S(await a4(e,t))}catch(o){k(o,{json:!0}),process.exitCode=1}return}let n=Array.isArray(e)?e:[e];await ag(_a.jsxDEV(pbe,{emails:n,options:t},void 0,!1,void 0,this)).waitUntilExit()}function Rs(e){return e?"on":"off"}function mbe(e){let t={},n=ui(e.opens,"--opens");if(n!==void 0)t.openTrackingEnabled=n;let r=ui(e.clicks,"--clicks");if(r!==void 0)t.clickTrackingEnabled=r;let o=ui(e.transactionalOpens,"--transactional-opens");if(o!==void 0)t.transactionalOpenTrackingEnabled=o;let a=ui(e.transactionalClicks,"--transactional-clicks");if(a!==void 0)t.transactionalClickTrackingEnabled=a;let c=ui(e.strictBotFiltering,"--strict-bot-filtering");if(c!==void 0)t.strictBotFilteringEnabled=c;let l=ui(e.unsubscribes,"--unsubscribes");if(l!==void 0)t.unsubscribeTrackingEnabled=l;let p=ui(e.storeContent,"--store-content");if(p!==void 0)t.emailContentStorageEnabled=p;if(e.attributionWindowHours!==void 0){let v=Number(e.attributionWindowHours);if(!Number.isInteger(v)||v<j0||v>z0)throw new A(`--attribution-window-hours must be a whole number between ${j0} and ${z0}`,400);t.defaultAttributionWindowHours=v}let f=ui(e.doubleOptIn,"--double-opt-in");if(f!==void 0)t.doubleOptInEnabled=f;if(e.doubleOptInRedirectUrl!==void 0){let v=e.doubleOptInRedirectUrl.trim();t.doubleOptInRedirectUrl=v===""?null:v}let h=ui(e.autoUtm,"--auto-utm");if(h!==void 0)t.autoUtmEnabled=h;let b=[["source",e.utmSource,"--utm-source"],["medium",e.utmMedium,"--utm-medium"],["campaign",e.utmCampaign,"--utm-campaign"],["content",e.utmContent,"--utm-content"],["term",e.utmTerm,"--utm-term"]];if(e.resetUtm){if(b.some(([,v])=>v!==void 0))throw new A("--reset-utm cannot be combined with other --utm-* flags",400);t.autoUtmSettings=null}else{let v={};for(let[C,R]of b)if(R!==void 0)v[C]=R;if(Object.keys(v).length>0)t.autoUtmSettings=v}return t}async function l4(e){if(!await j())k(M()),process.exit(1);try{let t=await E("GET","/api/v1/sender-profiles",void 0,e.company);if(e.json){S(t);return}console.log(`Sender profiles (${t.senderProfiles.length})`);for(let n of t.senderProfiles){let r=[n.isDefault?"default":null,n.canSend?"can send":"cannot send"].filter(Boolean).join(", ");console.log(`- ${n.name} <${n.email}> (${r})`),console.log(` ID: ${n.id}`),console.log(` Domain: ${n.domain??"unknown"} (${n.domainStatus??"unknown"})`)}console.log(""),console.log(`Reply-to profiles (${t.replyProfiles.length})`);for(let n of t.replyProfiles){let r=n.isDefault?" (default)":"";console.log(`- ${n.name} <${n.email}>${r}`),console.log(` ID: ${n.id}`)}}catch(t){k(t instanceof A?t:t),process.exit(1)}}function fbe(e,t){if(t.name===void 0)throw new A("--name is required",400);let n=t.name.trim();if(n.length===0)throw new A("--name cannot be empty",400);return{path:t.reply?`/api/v1/reply-profiles/${encodeURIComponent(e)}`:`/api/v1/sender-profiles/${encodeURIComponent(e)}`,body:{name:n}}}async function u4(e,t){if(!await j())k(M()),process.exit(1);try{let{path:n,body:r}=fbe(e,t),o=await E("PATCH",n,r,t.company);if(t.json){S(o);return}let a=t.reply?o.replyProfile:o.senderProfile;if(!a){console.log("Profile updated");return}let c=t.reply?"Reply-to profile":"Sender profile";if(console.log(o.renamed?`${c} renamed`:`${c} already had that name (no change)`),console.log(` ${a.name} <${a.email}>`),console.log(` ID: ${a.id}`),console.log(` Account default: ${a.isDefault?"yes":"no"}`),!t.reply&&"canSend"in a)console.log(` Can send: ${a.canSend?"yes":"no"}`)}catch(n){k(n instanceof A?n:n),process.exit(1)}}function gbe(e){let t=e.trim();if(t.length===0)throw new A("Sender profile ID is required",400);return{method:"DELETE",path:`/api/v1/sender-profiles/${encodeURIComponent(t)}`}}async function d4(e,t){if(!await j())k(M()),process.exit(1);try{let n=gbe(e);if(!await mt(`Delete sender profile ${e}? This cannot be undone.`,t)){console.log("Cancelled.");return}let r=await E(n.method,n.path,void 0,t.company);if(t.json){S(r);return}if(console.log(r.message),console.log(` Deleted ID: ${r.deletedSenderProfileId}`),r.fallbackSenderProfileId)console.log(` Fallback sender ID: ${r.fallbackSenderProfileId}`)}catch(n){k(n instanceof A?n:n),process.exit(1)}}async function p4(e){if(!await j())k(M()),process.exit(1);try{let t=await E("GET","/api/v1/tracking-settings",void 0,e.company);if(e.json){S(t);return}f4(t)}catch(t){k(t instanceof A?t:t),process.exit(1)}}async function m4(e){if(!await j())k(M()),process.exit(1);try{let t=mbe(e);if(Object.keys(t).length===0)throw new A("Provide at least one setting to update (see `sequenzy tracking update --help`)",400);let n=await E("PATCH","/api/v1/tracking-settings",t,e.company);if(e.json){S(n);return}if(n.message)console.log(n.message),console.log("");f4(n)}catch(t){k(t instanceof A?t:t),process.exit(1)}}function f4(e){let{tracking:t,consent:n,autoUtm:r,trackingDomain:o,replyTracking:a}=e;if(console.log("Tracking"),console.log(` Opens: ${Rs(t.openTrackingEnabled)}`),console.log(` Clicks: ${Rs(t.clickTrackingEnabled)}`),console.log(` Transactional API opens: ${Rs(t.transactionalOpenTrackingEnabled)}`),console.log(` Transactional API clicks: ${Rs(t.transactionalClickTrackingEnabled)}`),console.log(` Strict bot filtering: ${Rs(t.strictBotFilteringEnabled)}`),console.log(` Unsubscribe: ${Rs(t.unsubscribeTrackingEnabled)}`),console.log(` Store email content: ${Rs(t.emailContentStorageEnabled!==!1)}`),console.log(` Attribution window: ${t.defaultAttributionWindowHours}h`),console.log(""),console.log("Signup consent"),console.log(` Double opt-in: ${Rs(n.doubleOptInEnabled)}`),n.doubleOptInEnabled)console.log(` Confirmation email: ${n.doubleOptInEmailId??"not configured"}`);if(n.doubleOptInEnabled||n.doubleOptInRedirectUrl)console.log(` After confirmation: ${n.doubleOptInRedirectUrl??"branded confirmation page"}`);console.log(""),console.log(`Auto UTM: ${Rs(r.enabled)}`);for(let c of Gz){let l=r.settings[c];if(typeof l==="string"&&l.length>0)console.log(` utm_${c}: ${l}`)}if(console.log(""),o){if(console.log(`Tracking domain: ${o.domain}`),console.log(` Status: ${o.status}`),o.sslStatus)console.log(` SSL: ${o.sslStatus}`);if(o.error)console.log(` Error: ${o.error}`)}else console.log("Tracking domain: none (using shared Sequenzy domain)");console.log(""),console.log("Reply tracking"),console.log(` Inbound email: ${Rs(a.inboundEmailEnabled)}`),console.log(` Reply domain mode: ${a.inboundReplyDomainMode}`),console.log(` Forward replies: ${Rs(a.forwardReplies)}`)}var Abe={unsupported_reason:"this pause reason needs a support review",waiting_for_review:"an automated sender-health review is still running",blocked_by_ai:"the automated review did not clear this pause",review_failed:"the automated review could not complete",blocked_by_admin:"automatic resume is disabled for this account"};function hbe(e){let{rate:t,count:n}=e.pauseThreshold;if(t!==null&&n!==null)return`pauses at ${t}% or ${n}`;if(t!==null)return`pauses at ${t}%`;if(n!==null)return`pauses at ${n}`;return"no pause threshold at this volume"}function Iv(e,t,n){return`- ${e}: ${t.count} of ${n} (${t.rate.toFixed(3)}%) - ${hbe(t)}`}function ybe(e){if(!e.confirmListSanitized)throw new A("Pass --confirm-list-sanitized to confirm you fixed the source of the invalid addresses and left every permanent bounce suppressed. Run `sequenzy sending status` first to see what caused the pause.",400);return{listSanitizationConfirmed:!0}}function g4(e){if(console.log(`Sending status: ${e.status}`),e.pauseReason)console.log(`Reason: ${e.pauseReason}`);if(e.pauseReasonKind)console.log(`Reason kind: ${e.pauseReasonKind}`);if(e.pausedAt)console.log(`Paused at: ${e.pausedAt}`);if(console.log(""),e.senderHealth){let t=e.senderHealth;if(console.log(`Sender health (enforcement: ${t.enforcementMode})`),console.log(Iv("Permanent bounces",t.hardBounce,t.bounceScopedSent??t.scopedSent)),console.log(Iv("Temporary bounces",t.softBounce,t.bounceScopedSent??t.scopedSent)),t.block)console.log(Iv("Blocked emails",t.block,t.blockScopedSent??t.scopedSent));console.log(Iv("Complaints",t.complaint,t.complaintScopedSent??t.scopedSent)),console.log("")}if(console.log("Measurement window"),console.log(`- Type: ${e.metricsWindow.kind} (never expires)`),console.log(`- Bounce watermark: ${e.metricsWindow.bounceResetAt??"none (counts all sends ever)"}`),console.log(`- Complaint watermark: ${e.metricsWindow.complaintResetAt??"none (counts all sends ever)"}`),console.log(`- ${e.metricsWindow.description}`),console.log(""),e.status!=="active"){let{selfResume:t}=e;if(console.log("Restore path"),console.log(`- Resume available now: ${t.canSelfResume?"yes":"no"}`),console.log(`- Automated review: ${t.aiReviewStatus}`),t.aiReviewReason)console.log(`- Review note: ${t.aiReviewReason}`);if(!t.canSelfResume&&t.unavailableReason){let n=Abe[t.unavailableReason]??t.unavailableReason;console.log(`- Blocked because: ${n}`)}if(t.canSelfResume)console.log("- Run: sequenzy sending resume --confirm-list-sanitized");console.log("")}if(console.log("Next steps"),e.remediation.steps.forEach((t,n)=>{console.log(`${n+1}. ${t}`)}),console.log(""),console.log(`Docs: ${e.remediation.docsUrl}`),console.log(`Support: ${e.remediation.supportEmail}`),e.remediation.dashboardUrl)console.log(`Dashboard: ${e.remediation.dashboardUrl}`)}async function A4(e){if(!await j())k(M()),process.exit(1);try{let t=await E("GET","/api/v1/sending-status",void 0,e.company);if(e.json){console.log(JSON.stringify(t,null,2));return}g4(t)}catch(t){k(t instanceof A?t:t),process.exit(1)}}async function h4(e){if(!await j())k(M()),process.exit(1);try{let t=await E("POST","/api/v1/sending-status/resume",ybe(e),e.company);if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(t.message??(t.resumed?"Sending resumed.":"Sending was already active.")),console.log(""),g4(t)}catch(t){k(t instanceof A?t:t),process.exit(1)}}var bbe={ab_test:"A/B test step",no_email:"no email yet",shared_email:"sends the same email as an earlier step"};function y4(e){return(e??"").split(",").map((t)=>t.trim()).filter(Boolean)}function vbe(e){for(let r of e.emails){let o=r.status==="changed"?"✓":r.status==="unchanged"?"-":"✗",a=r.error??r.summary??(r.status==="unchanged"?"No change needed.":"");console.log(`${o} ${r.label} [${r.emailId}] ${a}`.trimEnd())}for(let r of e.skipped)console.log(` Skipped ${r.label} [${r.nodeId}]: ${bbe[r.reason]}`);let t=e.emails.filter((r)=>r.status==="changed"),n=t.filter((r)=>r.saved).length;if(e.dryRun)console.log(`${t.length} of ${e.emails.length} emails would change. Nothing was saved; use --json to see the new content.`);else console.log(`Saved ${n} of ${e.emails.length} emails.${n<t.length?" Some changes couldn't be saved; run the command again for those emails.":""}`)}async function b4(e){try{if(!await j())throw M();if(!e.id)throw new A("Sequence ID is required",400);if(!e.prompt?.trim())throw new A("--prompt is required",400);let t=y4(e.emails),n=y4(e.sections);if(n.length>0&&t.length!==1)throw new A("--sections needs exactly one email in --emails",400);let r=await E("POST",`/api/v1/sequences/${encodeURIComponent(e.id)}/emails/edit`,{prompt:e.prompt,...t.length>0?{emailIds:t}:{},...n.length>0?{sectionIds:n}:{},...e.dryRun?{dryRun:!0}:{}},e.company);if(e.json)return S(r);vbe(r)}catch(t){k(t),process.exit(1)}}var v4=["close","fresh","bold"],Ebe=3000,Ibe=300;function QB(e){let t=[e.status!=="ready"?e.status:null,e.inUse?"in use":null].filter(Boolean);if(console.log(`- ${e.label} ${e.name} [${e.id}]${t.length>0?` (${t.join(", ")})`:""}`),e.summary)console.log(` ${e.summary}`);if(e.error)console.log(` Error: ${e.error}`)}async function E4(e,t){return(await E("GET",e,void 0,t)).variations}async function lg(e,t){if(!await j())k(M()),process.exit(1);try{if(!t.id)throw new A("Sequence ID is required",400);if(!t.email)throw new A("--email is required",400);let n=`/api/v1/sequences/${encodeURIComponent(t.id)}/emails/${encodeURIComponent(t.email)}/variations`,r=()=>{if(!t.variationId)throw new A("Variation ID is required",400);return`${n}/${encodeURIComponent(t.variationId)}`};if(e==="list"){let o=await E4(n,t.company);if(t.json)return S({success:!0,variations:o});if(o.length===0){console.log("No variations yet."),console.log(`Generate some: sequenzy sequences variations generate ${t.id} --email ${t.email} --prompt "A few bolder versions"`);return}console.log(`Variations (${o.length})`);for(let a of o)QB(a);return}if(e==="generate"){if(!t.prompt?.trim())throw new A("--prompt is required",400);if(t.style!==void 0&&!v4.includes(t.style))throw new A(`--style must be one of ${v4.join(", ")}`,400);let o=ot(t.count,"--count"),a=await E("POST",`${n}/generate`,{prompt:t.prompt,...o!==void 0?{count:o}:{},...t.style!==void 0?{style:t.style}:{}},t.company),c=a.variations.map((f)=>f.id);if(!t.wait){if(t.json)return S(a);console.log(`Designing ${c.length} variations:`);for(let f of a.variations)QB(f);console.log(`Check progress: sequenzy sequences variations list ${t.id} --email ${t.email}`);return}let l=ot(t.timeout,"--timeout")??Ibe,p=Date.now()+l*1000;for(;;){let f=(await E4(n,t.company)).filter((h)=>c.includes(h.id));if(f.every((h)=>h.status!=="generating")){if(t.json)return S({success:!0,variations:f});for(let h of f)QB(h);return}if(Date.now()>p)throw new A(`Variations are still generating after ${l}s. Check later with: sequenzy sequences variations list ${t.id} --email ${t.email}`,408);await new Promise((h)=>setTimeout(h,Ebe))}}if(e==="use"){let o=await E("POST",`${r()}/use`,{...t.all?{scope:"all"}:{},...t.dryRun?{dryRun:!0}:{}},t.company);if(t.json)return S(o);console.log(o.dryRun?"Would change (nothing saved):":"Changed:");for(let a of o.emails){let c=a.status!=="changed"?a.status:a.saved?"saved":o.dryRun?"would change":"not saved";if(console.log(`- ${a.label} [${a.emailId}] ${c}${a.summary?`: ${a.summary}`:""}`),a.error)console.log(` ${a.error}`)}return}if(await E("DELETE",r(),void 0,t.company),t.json)return S({success:!0,discarded:!0});console.log("Variation discarded.")}catch(n){k(n),process.exit(1)}}function Cbe(e){return Array.from(new Set((e??[]).map((t)=>t.trim()).filter((t)=>t.length>0)))}function $B(e){let t=Cbe(e.listIds),n=e.segmentId?.trim(),r=e.audienceJson!==void 0||e.audienceFile!==void 0,o=[e.all?"--all":null,t.length>0?"--list-ids":null,n?"--segment-id":null,r?"--audience-json/--audience-file":null].filter((c)=>c!==null);if(o.length===0)throw new A("Choose an audience: --all, --list-ids <ids...>, --segment-id <id>, or --audience-json/--audience-file",400);if(o.length>1)throw new A(`Use exactly one audience option, not ${o.join(" and ")}`,400);if(e.all)return{type:"all"};if(t.length>0)return{type:"lists",listIds:t};if(n)return{type:"segment",segmentId:n};let a=Oe(e.audienceJson,e.audienceFile,"audience");if(!a||typeof a!=="object"||Array.isArray(a))throw new A('Audience JSON must be an object such as {"type":"segment","segmentId":"seg_123"}',400);return a}function wbe(e){if(e.dataJson===void 0&&e.dataFile===void 0)return;if(e.dataJson!==void 0&&e.dataFile!==void 0)throw new A("Use either --data-json or --data-file, not both",400);let t=Oe(e.dataJson,e.dataFile,"data");if(t===null||t===void 0)return;if(typeof t!=="object"||Array.isArray(t))throw new A('Run data must be a JSON object such as {"sale_ends_at":"2026-11-29T23:59:00Z","discount_percent":20}',400);return Object.keys(t).length>0?t:void 0}function wv(e,t){let n=t??(Array.isArray(e.includedSubscriberIds)?e.includedSubscriberIds.length:0);if(e.type==="rules"&&Array.isArray(e.include)&&e.include.length===0&&n>0)return`${n.toLocaleString("en-US")} picked contact${n===1?"":"s"}`;switch(e.type){case"all":return"everyone";case"lists":return`lists ${(Array.isArray(e.listIds)?e.listIds:[]).join(", ")}`;case"segment":return`segment ${String(e.segmentId??"")}`;case"filtered":return"saved filter";case"rules":return"audience rules";default:return String(e.type??"audience")}}function xp(e){let t=e.status==="queued"?e.scheduledFor?`scheduled for ${X(e.scheduledFor)}`:"queued":`${e.enrolledCount}/${Math.max(e.estimatedCount,e.enrolledCount+e.skippedCount)} enrolled${e.skippedCount>0?`, ${e.skippedCount} skipped`:""}`;return`${e.id} [${e.status}] ${wv(e.audience,e.includedSubscriberCount)} · ${t} · started ${X(e.createdAt)}${e.error?` · error: ${e.error}`:""}`}var Sbe=2000,Dbe=1800000;async function Bbe(e){await new Promise((t)=>setTimeout(t,e))}function Cv(e){return`'${e.replaceAll("'","'\\''")}'`}async function I4(e,t){if(!await j())k(M()),process.exit(1);try{let n=$B(t),r=wbe(t),o=encodeURIComponent(e);if(t.apply!==!0){if(t.targetNodeId?.trim())console.log("Note: --target-node-id only applies with --apply; the estimate ignores it.");if(r&&!t.json)console.log("Note: --data-json/--data-file only apply with --apply; the estimate ignores them.");let f=await E("POST",`/api/v1/sequences/${o}/enroll-audience/estimate`,{audience:n},t.company);if(t.json){S({...f,dryRun:!0});return}console.log(`Audience: ${wv(n)}`),console.log(`Matching contacts: ${f.matchingCount}`),console.log(`Already in the sequence: ${f.alreadyEnrolledCount}`),console.log(`Would enroll: ${f.enrollableCount}`),console.log(""),console.log("Re-run with --apply to start enrolling in the background.");return}let a=t.targetNodeId?.trim(),c=t.scheduleAt?.trim();if(c&&Number.isNaN(Date.parse(c)))throw new A("--schedule-at must be an ISO 8601 date-time, e.g. 2026-11-15T09:00:00Z",400);let l=await E("POST",`/api/v1/sequences/${o}/enroll-audience`,{audience:n,...a?{targetNodeId:a}:{},...c?{scheduledFor:new Date(c).toISOString()}:{},...r?{data:r}:{}},t.company);if(t.keepEnrolling){try{await E("PUT",`/api/v1/sequences/${o}`,{audienceAutoEnroll:{audience:n,...c?{startsAt:new Date(c).toISOString()}:{}}},t.company)}catch(f){let h=f instanceof Error?f.message:String(f),b=`Enrollment ${l.audienceEnrollment.id} already started. Retry only keep-enrolling configuration with sequenzy sequences update ${Cv(e)} --auto-enroll-json ${Cv(JSON.stringify(n))}${c?` --auto-enroll-starts-at ${Cv(new Date(c).toISOString())}`:""}${t.company?` --company ${Cv(t.company)}`:""}.`;if(t.json)S({...l,partialSuccess:!0,autoEnrollError:h,recovery:b});else console.log(l.message),console.log(xp(l.audienceEnrollment)),console.log(b);throw f}if(!t.json){if(console.log("Auto-enroll on: people who join this audience later are enrolled until the last key date."),r)console.log("Run data applies to this enrollment only; auto-enrolled late joiners will not have {{enrollment.*}} values.")}}let p=l.audienceEnrollment;if(t.wait){let f=Date.now();while((p.status==="queued"||p.status==="running")&&Date.now()-f<Dbe)if(await Bbe(Sbe),p=(await E("GET",`/api/v1/sequences/${o}/audience-enrollments/${encodeURIComponent(p.id)}`,void 0,t.company)).audienceEnrollment,!t.json)console.log(xp(p))}if(t.json){S({...l,audienceEnrollment:p});return}if(!t.wait)console.log(l.message);if(console.log(xp(p)),p.data&&Object.keys(p.data).length>0)console.log(`Run data ({{enrollment.*}}): ${Object.keys(p.data).join(", ")}`);if(p.status==="queued"||p.status==="running")console.log(`Poll with: sequenzy sequences audience-enrollments ${e}`)}catch(n){k(n instanceof A?n:n),process.exit(1)}}async function C4(e,t){if(!await j())k(M()),process.exit(1);try{let n=t.limit?.trim();if(n!==void 0&&!/^\d+$/.test(n))throw new A("--limit must be a whole number",400);let r=n?`?limit=${n}`:"",o=await E("GET",`/api/v1/sequences/${encodeURIComponent(e)}/audience-enrollments${r}`,void 0,t.company);if(t.json){S(o);return}if(o.audienceEnrollments.length===0){console.log("No audience enrollments yet.");return}for(let a of o.audienceEnrollments)console.log(xp(a))}catch(n){k(n instanceof A?n:n),process.exit(1)}}async function w4(e,t,n){if(!await j())k(M()),process.exit(1);try{let r=await E("GET",`/api/v1/sequences/${encodeURIComponent(e)}/audience-enrollments/${encodeURIComponent(t)}`,void 0,n.company);if(n.json){S(r);return}let o=r.audienceEnrollment;if(console.log(xp(o)),console.log(`Target step: ${o.targetNodeId??"first step"}`),o.data&&Object.keys(o.data).length>0)console.log(`Run data ({{enrollment.*}}): ${Object.keys(o.data).join(", ")}`);if(console.log(`Scanned: ${o.processedCount} · Enrolled: ${o.enrolledCount} · Skipped: ${o.skippedCount}${o.estimatedCount>0?` · Estimated: ${o.estimatedCount}`:""}`),o.startedAt)console.log(`Started: ${X(o.startedAt)}`);if(o.completedAt)console.log(`Finished: ${X(o.completedAt)}`);if(o.cancelRequestedAt&&!o.completedAt)console.log("Cancellation requested; stopping after the current batch.")}catch(r){k(r instanceof A?r:r),process.exit(1)}}async function S4(e,t,n){if(!await j())k(M()),process.exit(1);try{let r=await E("POST",`/api/v1/sequences/${encodeURIComponent(e)}/audience-enrollments/${encodeURIComponent(t)}/cancel`,void 0,n.company);if(n.json){S(r);return}console.log(r.message),console.log(xp(r.audienceEnrollment))}catch(r){k(r instanceof A?r:r),process.exit(1)}}import{writeFile as _be}from"node:fs/promises";var xbe=["active","waiting","paused","completed","failed","cancelled"],D4=["enrolled_at_desc","enrolled_at_asc","wait_until_asc","wait_until_desc"],kbe=500,Rbe=["enrollmentId","subscriberId","email","firstName","lastName","subscriberStatus","status","currentNodeId","currentNodeType","currentNodeLabel","enrollmentKey","enrollmentStartedAt","waitUntil","lastUpdatedAt","failedReason","movedFromNodeId","movedAt","moveReason","stopConditionMatches","stopConditionMatchReason","enteredViaKind","enteredViaValue","enteredViaName","entryTriggerType","entryEventName","entryEventPropertyKeys","lastBranchSelectedPath","lastBranchFieldName","lastBranchComparedSummary","branchDecisionCount","branchDecisionsTruncated","pausedAt","pauseReason"];function _4(e){if(!e)return;return e.evaluations?.find((t)=>t.outcome==="pass")??e.evaluations?.find((t)=>t.outcome==="fail")??e.evaluations?.[0]}function B4(e){return[e.nodeId,e.decidedAt,e.splitMode,e.selectedPath,e.matchedBranchId??""].join("\x00")}function NB(e){if(e.splitMode==="random"){if(!e.matchedBranchId)return e.selectedPath==="else"?"took else":void 0;return e.selectedPath==="else"?`chose ${e.matchedBranchId}, then fell back to else`:`chose ${e.matchedBranchId}`}let t=_4(e);return t?.fieldName&&t.compared?.summary?`${t.fieldName} ${t.compared.summary}`:t?.reason}function Tbe(e,t,n){if(e?.find((o)=>!n.includes(o))!==void 0)throw new A(`${t} must be one of: ${n.join(", ")}`,400)}function x4(e){if(Tbe(e.status,"--status",xbe),e.sort!==void 0&&!D4.includes(e.sort))throw new A(`--sort must be one of: ${D4.join(", ")}`,400);let t=new URLSearchParams;if(e.status?.length)t.set("status",e.status.join(","));if(e.nodeId?.length)t.set("currentNodeId",e.nodeId.join(","));if(e.subscriberId?.length)t.set("subscriberId",e.subscriberId.join(","));if(e.email)t.set("email",e.email);if(e.sort)t.set("sort",e.sort);if(e.limit)t.set("limit",e.limit);if(e.offset)t.set("offset",e.offset);if(e.stopConditionMatch)t.set("stopConditionMatch","true");return t.size>0?`?${t.toString()}`:""}function Qbe(e){if(e.csv!==void 0&&e.json)throw new A("--csv cannot be combined with --json",400);if(e.all&&e.offset!==void 0)throw new A("--all cannot be combined with --offset",400)}async function $be(e,t){let n=t.limit??String(kbe),r=new Map,o,a=0,c=0;for(;;){let p=await E("GET",`/api/v1/sequences/${encodeURIComponent(e)}/enrollments${x4({...t,limit:n,offset:String(c)})}`,void 0,t.company);o??=p,a+=p.stopConditionMatchEvaluatedCount??0;for(let f of p.enrollments)if(!r.has(f.enrollmentId))r.set(f.enrollmentId,f);if(p.enrollments.length===0||!p.pagination.hasMore)break;c+=p.enrollments.length}let l=Array.from(r.values());return{...o??{success:!0,sequenceId:e,sequenceName:"",statuses:[],enrollments:[],pagination:{limit:Number(n),offset:0,count:0,total:0,hasMore:!1}},enrollments:l,stopConditionMatchEvaluatedCount:a,pagination:{limit:o?.pagination.limit??Number(n),offset:0,count:l.length,total:Math.max(o?.pagination.total??0,l.length),hasMore:!1}}}function Nbe(e){let t=[e.firstName,e.lastName].filter((n)=>Boolean(n)).join(" ");return t===""?"":` (${t})`}function k4(e){let t=e.currentNodeLabel??e.currentNodeType,n=e.currentNodeMissing?" [node deleted]":"";return t?`${t} <${e.currentNodeId}>${n}`:`${e.currentNodeId}${n}`}async function Obe(e,t){Qbe(t);let n=t.all?await $be(e,t):await E("GET",`/api/v1/sequences/${encodeURIComponent(e)}/enrollments${x4(t)}`,void 0,t.company);if(t.csv!==void 0){let a=vb(Rbe,n.enrollments.map((c)=>{let l=c.branchDecisions?.at(-1),p=_4(l);return{...c,enteredViaKind:c.enteredVia?.kind??"",enteredViaValue:c.enteredVia?.value??"",enteredViaName:c.enteredVia?.name??"",entryTriggerType:c.entryContext?.triggerType??"",entryEventName:c.entryContext?.eventName??"",entryEventPropertyKeys:c.entryContext?.eventPropertyKeys.join(";")??"",lastBranchSelectedPath:l?.selectedPath??"",lastBranchFieldName:p?.fieldName??"",lastBranchComparedSummary:p?.compared?.summary??"",branchDecisionCount:c.branchDecisionCount??0,branchDecisionsTruncated:c.branchDecisionsTruncated??!1}}));if(typeof t.csv==="string")await _be(t.csv,`${a}\r
|
|
317
|
-
`,"utf8"),console.log(`Exported ${n.enrollments.length} enrollments to ${t.csv}`);else console.log(a);return}if(t.json){S(n);return}let{pagination:r}=n;console.log(`Enrollments in ${n.sequenceName} (${r.count} of ${r.total}, statuses: ${n.statuses.join(", ")})`);let o=n.stopCondition;if(o&&o.type!=="none"){if(console.log(`Stop condition: ${o.type}${o.value?` = ${o.value}`:""}`),o.matchConfig)console.log(` match config: ${JSON.stringify(o.matchConfig)}`)}if(n.enrollments.length===0){console.log("No enrollments matched the filters.");return}for(let a of n.enrollments){console.log(""),console.log(`- ${a.email??a.subscriberId}${Nbe(a)} [${a.status}]`),console.log(` at ${k4(a)}`),console.log(` enrolled ${X(a.enrollmentStartedAt)}${a.waitUntil?`, resumes ${X(a.waitUntil)}`:""}`);let c=a.enteredVia?.description;if(c&&a.enteredVia?.kind!=="unknown")console.log(` entered via ${c}`);let l=a.entryContext;if(l?.eventName){let f=l.eventPropertyKeys.length>0?` keys ${l.eventPropertyKeys.join(", ")}`:"";console.log(` entry event ${l.eventName}${f}`)}else if(l?.triggerType)console.log(` entry trigger ${l.triggerType}`);let p=a.branchDecisions?.at(-1);if(p){let f=NB(p);console.log(` branch ${p.selectedPath}${f?`: ${f}`:""}`)}if(a.branchDecisionsTruncated)console.log(` branch history truncated: showing ${a.branchDecisions?.length??0} of ${a.branchDecisionCount??"unknown"}`);if(a.failedReason)console.log(` failed: ${a.failedReason}`);if(a.stopConditionMatches===!0)console.log(` stop condition matches now: ${a.stopConditionMatchReason??"condition met"}`),console.log(" -> worker re-checks before a future step; a step already in progress may still finish");if(a.status==="paused")console.log(` paused${a.pausedAt?` since ${X(a.pausedAt)}`:""}${a.pauseReason?` (${a.pauseReason})`:""}; resume with sequenzy sequences resume-subscribers`);if(a.movedAt)console.log(` released from ${a.movedFromNodeId??"an earlier step"} on ${X(a.movedAt)}${a.moveReason?` (${a.moveReason})`:""}`);console.log(` subscriberId ${a.subscriberId}`)}if(console.log(""),t.stopConditionMatch)console.log(`Stop-condition match checked for ${n.stopConditionMatchEvaluatedCount??0} enrollment(s). A waiting enrollment whose stop condition already matches keeps reporting "waiting" until its delay expires, then is re-checked before continuing. This is a current-state snapshot; a step already in progress may still finish.`);if(r.hasMore)console.log(`More results: sequenzy sequences enrollments ${e} --offset ${r.offset+r.count}`);if(!t.all&&t.csv===void 0)console.log(`Export every match: sequenzy sequences enrollments ${e} --all --csv enrollments.csv`);console.log(`Node-level counts: sequenzy stats --sequence ${e} # enrollmentCounts.byCurrentNode`)}async function R4(e,t){if(!await j())k(M()),process.exit(1);try{await Obe(e,t)}catch(n){k(n instanceof A?n:n),process.exit(1)}}async function T4(e,t,n){if(!await j())k(M()),process.exit(1);try{let r=await E("GET",`/api/v1/sequences/${encodeURIComponent(e)}/enrollments/${encodeURIComponent(t)}`,void 0,n.company);if(n.json){S(r);return}let o=r.enrollment;console.log(`Enrollment ${o.enrollmentId} in ${r.sequenceName} [${o.status}]`),console.log(` at ${k4(o)}`),console.log(` enrolled ${X(o.enrollmentStartedAt)}`);let a=o.enteredVia?.description;if(a)console.log(` entered via ${a}`);let c=o.entryContext;if(c?.eventName)console.log(` entry event ${c.eventName}${c.eventPropertyKeys.length>0?` keys ${c.eventPropertyKeys.join(", ")}`:""}`);if(console.log(` history from ${r.historySource}`),r.nodeHistoryTruncated)console.log(` node history truncated after ${r.nodeHistoryLimit} events`);if(o.branchDecisionsTruncated)console.log(` branch history truncated: showing ${o.branchDecisions?.length??0} of ${o.branchDecisionCount??"unknown"}`);if(r.nodeHistory.length===0)console.log(" no recorded node events");let l=new Set;for(let p of r.nodeHistory){let f=p.nodeLabel??p.nodeType??p.nodeId,h=p.branchDecision;if(h)l.add(B4(h));let b=h?NB(h):void 0,v=h?` branch ${h.selectedPath}${b?` (${b})`:""}`:"";console.log(` ${X(p.eventTime)} ${p.eventType} ${f}${v}`)}for(let p of o.branchDecisions??[]){if(l.has(B4(p)))continue;let f=NB(p);console.log(` ${X(p.decidedAt)} branch ${p.nodeId} ${p.selectedPath}${f?` (${f})`:""}`)}}catch(r){k(r instanceof A?r:r),process.exit(1)}}var Q4=["wait_until_asc","wait_until_desc","enrolled_at_asc","enrolled_at_desc"];function $4(e,t){if(e===void 0)return;let n=e.trim(),r=t==="--daily-limit"?0:1;if(!/^\d+$/.test(n))throw new A(`${t} must be a whole number`,400);let o=Number(n);if(!Number.isSafeInteger(o)||o<r)throw new A(`${t} must be at least ${r}`,400);return o}function N4(e){return Array.from(new Set((e??[]).map((t)=>t.trim()).filter((t)=>t.length>0)))}function Pbe(e){let t=e.fromNode?.trim();if(!t)throw new A("--from-node is required",400);if(e.sort!==void 0&&!Q4.includes(e.sort))throw new A(`--sort must be one of: ${Q4.join(", ")}`,400);let n=e.toNode?.trim(),r=N4(e.subscriberIds),o=N4(e.tag),a=$4(e.limit,"--limit"),c=$4(e.dailyLimit,"--daily-limit"),l=e.reason?.trim();return{fromNodeId:t,...n?{targetNodeId:n}:{},...a!==void 0&&{limit:a},...c!==void 0&&{dailyLimit:c},...e.sort!==void 0&&{sort:e.sort},...r.length>0&&{subscriberIds:r},...o.length>0&&{tags:o},...l?{reason:l}:{},dryRun:e.apply!==!0}}function qbe(e){if(console.log(e.message),console.log(""),console.log(`From step ${e.fromNodeId}`),console.log(`To step ${e.targetNodeId}`),console.log(`Matched ${e.matchedCount}, moved ${e.movedCount}, remaining ${e.remainingCount} (sorted by ${e.sort})`),e.skippedCount>0)console.log(`Skipped ${e.skippedCount} enrollment(s) that are active, mid-step, or awaiting double opt-in.`);if(e.dailyLimit!==null)console.log(`Daily limit ${e.dailyLimit}: ${e.movedInWindow} already moved in the last 24h, ${e.dailyRemaining} left.`);if(e.tagResult)console.log(`Tagged ${e.tagResult.updated} contact(s) with ${e.tagResult.tags.join(", ")} (${e.tagResult.unchanged} already tagged, ${e.tagResult.failed} failed).`);if(e.enqueueErrors.length>0)console.log(`${e.enqueueErrors.length} enrollment(s) could not be queued; the stuck-enrollment sweeper will retry them.`);if(e.enrollments.length>0){console.log(""),console.log(e.dryRun?"Would move:":"Moved:");for(let t of e.enrollments)console.log(`- ${t.subscriberEmail??t.subscriberId} [${t.status}]`);if(e.hasMore)console.log(`... and more (showing the first ${e.enrollments.length})`)}if(console.log(""),e.dryRun)console.log("Re-run with --apply to move them.");else if(e.remainingCount>0)console.log("Re-run the same command to release the next batch.")}async function O4(e,t){if(!await j())k(M()),process.exit(1);try{let n=Pbe(t),r=await E("POST",`/api/v1/sequences/${encodeURIComponent(e)}/enrollments/move`,n,t.company);if(t.json){S(r);return}qbe(r)}catch(n){k(n instanceof A?n:n),process.exit(1)}}var P4=500,Fbe={paused:"paused",already_paused:"already paused",in_progress:"step running now, retry shortly",resumed:"resumed",not_paused:"was not paused"};function q4(e){return Array.from(new Set((e??[]).flatMap((t)=>t.split(",")).map((t)=>t.trim()).filter((t)=>t.length>0)))}function Lbe(e,t){let n=q4(e.subscriberIds),r=q4(e.email);if(n.length===0&&r.length===0)throw new A("Provide --subscriber-ids, --email, or both",400);if(n.length+r.length>P4)throw new A(`A maximum of ${P4} subscriber IDs and emails combined can be targeted per command`,400);let o=e.reason?.trim();return{...n.length>0&&{subscriberIds:n},...r.length>0&&{emails:r},...t==="pause"&&o?{reason:o}:{}}}function Ube(e){if(console.log(e.message),e.enrollments.length>0){console.log("");for(let t of e.enrollments){let n=t.status==="paused"&&t.pausedAt?` since ${X(t.pausedAt)}`:t.waitUntil?`, next step ${X(t.waitUntil)}`:"";console.log(`- ${t.subscriberEmail??t.subscriberId}: ${Fbe[t.outcome]??t.outcome} [${t.status}${n}] on step ${t.currentNodeId}`)}}for(let t of e.notEnrolled)console.log(`- ${t.email??t.subscriberId}: not enrolled in this sequence`);for(let t of e.notFound.subscriberIds)console.log(`- ${t}: subscriber not found`);for(let t of e.notFound.emails)console.log(`- ${t}: subscriber not found`)}async function F4(e,t,n){if(!await j())k(M()),process.exit(1);try{let r=Lbe(n,e),o=await E("POST",`/api/v1/sequences/${encodeURIComponent(t)}/enrollments/${e}`,r,n.company);if(n.json){S(o);return}Ube(o)}catch(r){k(r),process.exit(1)}}function L4(e,t){return F4("pause",e,t)}function U4(e,t){return F4("resume",e,t)}var K4="Existing sender profile ID; carries its own address and name. To keep it with a different display name, set fromName inside each email step passed through --steps-json/--steps-file; omit sequence-level --from-email and --from-name.",Y4="Existing sender profile ID; carries its own address and name. To keep it with a different display name, set fromName inside each email step passed through --steps-json/--steps-file or --emails-json/--emails-file; omit sequence-level --from-email and --from-name.";function jbe(e){let t=[];if((e?.migratedRecipientCount??0)>0)t.push(`Recipients moved to the next step: ${e?.migratedRecipientCount}`);if((e?.completedRecipientCount??0)>0)t.push(`Recipients completed: ${e?.completedRecipientCount}`);return t}function zbe(e){let t=e.structuralStepNumber??e.stepNumber;return t!==null?`Step ${t}`:`Node ${e.nodeId}`}function Mbe(e){if(!e?.addedBranchNodeId)return[];let t=[`Branch node: ${e.addedBranchNodeId}`];for(let[n,r]of Object.entries(e.addedBranchPathNodeIds??{}))t.push(` Path ${n}: ${r.length>0?r.join(" -> "):"wired to an existing node"}`);return t}var Hbe=50,j4=10,z4=10,M4=500,Gbe=new Set(["unlimited","one_time","matching_field"]);function Jbe(e){if(!e.id)throw new A("Sequence ID is required",400);if(!e.nodeId?.trim())throw new A("--node is required",400);let t=e.to??[];if(t.length>z4)throw new A(`--to accepts no more than ${z4} email addresses`,400);let n=Array.from(new Set(t.map((o)=>o.trim().toLowerCase()).filter(Boolean)));if(n.length===0)throw new A("--to requires at least one email address",400);let r=n.find((o)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o));if(r)throw new A(`Invalid test recipient: ${r}`,400);return{path:`/api/v1/sequences/${encodeURIComponent(e.id)}/nodes/${encodeURIComponent(e.nodeId.trim())}/test`,body:{recipients:n}}}var Wbe={all:["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],everyday:["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],weekdays:["monday","tuesday","wednesday","thursday","friday"],"working-days":["monday","tuesday","wednesday","thursday","friday"],weekends:["saturday","sunday"]};function H4(e){if(e===void 0)return;if(!Gbe.has(e))throw new A("--enrollment-mode must be one of: unlimited, one_time, matching_field",400);return e}function Vbe(e){if(e===void 0)return;if(!zz(e))throw new A(`--list-scope must be one of: ${P0.join(", ")}`,400);return e}function G4(e,t){if(e===void 0&&t===void 0)return;let n=[],r=new Set;for(let o of[t,...e??[]]){let a=o?.trim();if(!a||r.has(a))continue;r.add(a),n.push(a)}if(n.length===0)throw new A("List and tag values must not be empty",400);return n}function Kbe(e){if(e===void 0)return;let t=[];for(let n of e.split(",")){let r=n.trim().toLowerCase();if(!r)continue;let o=Wbe[r];if(o){for(let a of o)if(!t.includes(a))t.push(a);continue}if(!t.includes(r))t.push(r)}if(t.length===0)throw new A("--sending-window-days must include at least one day",400);return t}function Ybe(e){let t=e.sendingWindowStart!==void 0||e.sendingWindowEnd!==void 0||e.sendingWindowTimezone!==void 0||e.sendingWindowDays!==void 0;if(e.clearSendingWindow&&t)throw new A("Use either --clear-sending-window or --sending-window-* options, not both",400);if(e.clearSendingWindow)return null;if(!t)return;let n=e.sendingWindowStart?.trim(),r=e.sendingWindowEnd?.trim(),o=e.sendingWindowTimezone?.trim();if(!n||!r||!o)throw new A("--sending-window-start, --sending-window-end, and --sending-window-timezone are required together",400);let a=Kbe(e.sendingWindowDays);return{enabled:!0,timezone:o,startTime:n,endTime:r,...a!==void 0&&{days:a}}}function Zbe(e){if(e.sendSpreadHours===void 0)return;let t=e.sendSpreadHours.trim(),n=Number(t);if(t===""||!Number.isFinite(n)||n<0)throw new A("--send-spread-hours must be a number of hours",400);return{spreadOverHours:n}}async function Xbe(e){if(e.sendSpreadHours===void 0||e.clearKeyDates===!0||(e.keyDate??[]).length>0||e.keyDatesJson!==void 0||e.keyDatesFile!==void 0)return e;let n=(await E("GET",`/api/v1/sequences/${e.id}`,void 0,e.company)).sequence?.keyDates;if(!n||n.dates.length===0)throw new A("This sequence has no key dates; add --key-date entries to set a spread",400);return{...e,keyDatesJson:JSON.stringify({timezone:n.timezone,dates:n.dates})}}function eve(e){let t=tve(e),n=Zbe(e);if(n===void 0)return t;if(t===null)throw new A("--send-spread-hours cannot be combined with --clear-key-dates",400);if(t===void 0)throw new A("--send-spread-hours needs key dates: add --key-date entries (or --key-dates-json)",400);return{...t,sendWindow:n}}function tve(e){let t=(e.keyDate??[]).map((c)=>c.trim()).filter((c)=>c.length>0),n=e.keyDatesJson!==void 0||e.keyDatesFile!==void 0,r=t.length>0||n||e.keyDatesTimezone!==void 0;if(e.clearKeyDates&&r)throw new A("Use either --clear-key-dates or --key-date/--key-dates-* options, not both",400);if(e.clearKeyDates)return null;if(!r)return;if(t.length>0&&n)throw new A("Use either --key-date entries or --key-dates-json/--key-dates-file, not both",400);if(n){let c=Oe(e.keyDatesJson,e.keyDatesFile,"key dates");if(c===void 0)throw new A("Key dates JSON is empty",400);let l=Array.isArray(c)?{dates:c}:c;if(!Array.isArray(l.dates))throw new A('Key dates JSON must be an array of { label, at } or an object with "dates"',400);let p=e.keyDatesTimezone?.trim()||l.timezone;return{...p?{timezone:p}:{},dates:l.dates,...l.sendWindow!==void 0&&{sendWindow:l.sendWindow}}}let o=e.keyDatesTimezone?.trim();if(!o)throw new A("--key-dates-timezone is required with --key-date, e.g. --key-dates-timezone America/New_York",400);let a=t.map((c)=>{let l=c.lastIndexOf("=");if(l<=0||l===c.length-1)throw new A(`--key-date must look like "Label=2026-11-27T00:00:00" (got "${c}")`,400);let p=c.slice(0,l).trim(),f=c.slice(l+1).trim(),h=/^([a-z0-9_]+):(.+)$/.exec(p);return h?{key:h[1],label:h[2].trim(),at:f}:{label:p,at:f}});return{timezone:o,dates:a}}function nve(e){let t=e.autoEnrollAll===!0||(e.autoEnrollListIds?.length??0)>0||e.autoEnrollSegmentId!==void 0||e.autoEnrollJson!==void 0;if(e.clearAutoEnroll&&t)throw new A("Use either --clear-auto-enroll or --auto-enroll-* options, not both",400);if(e.clearAutoEnroll)return null;if(!t){if(e.autoEnrollStartsAt!==void 0)throw new A("--auto-enroll-starts-at needs an audience: add --auto-enroll-all, --auto-enroll-list-ids, --auto-enroll-segment-id or --auto-enroll-json",400);return}let n=e.autoEnrollStartsAt?.trim();if(n&&Number.isNaN(Date.parse(n)))throw new A("--auto-enroll-starts-at must be an ISO 8601 date-time, e.g. 2026-11-15T09:00:00Z",400);return{...n?{startsAt:new Date(n).toISOString()}:{},audience:$B({...e.autoEnrollAll?{all:!0}:{},...e.autoEnrollListIds?{listIds:e.autoEnrollListIds}:{},...e.autoEnrollSegmentId?{segmentId:e.autoEnrollSegmentId}:{},...e.autoEnrollJson?{audienceJson:e.autoEnrollJson}:{}})}}function OB(e){if(!e)return"Off";let t=wv(e.audience);if(e.enabled){let n=e.startsAt&&Date.parse(e.startsAt)>Date.now()?` · starts ${X(e.startsAt)}`:"";return`On · ${t}${n} · new joiners are enrolled until the last key date`}return`Off (${e.endedReason==="countdown_ended"?"countdown ended":"switched off"}${e.endedAt?` ${X(e.endedAt)}`:""}) · was ${t}`}function PB(e){if(!e||e.dates.length===0)return"None";let t=e.timezone?` (${e.timezone})`:"",n=e.sendWindow?.spreadOverHours,r=n===void 0?"":n===0?" · sends at the exact moment":` · each email spread over ${n}h`;return e.dates.map((o)=>`${o.label}${o.key?` [${o.key}]`:""} = ${o.at}`).join("; ")+t+r}function rve(e){if(e.respectFrequencyCap&&e.ignoreFrequencyCap)throw new A("Use either --respect-frequency-cap or --ignore-frequency-cap, not both",400);if(e.respectFrequencyCap)return!0;if(e.ignoreFrequencyCap)return!1;return}function ove(e){if(e.activeSubscribersOnly&&e.includeSuppressedSubscribers)throw new A("Use either --active-subscribers-only or --include-suppressed-subscribers, not both",400);if(e.activeSubscribersOnly)return!0;if(e.includeSuppressedSubscribers)return!1;return}function Sv(e){return e?"Respected":"Ignored"}function Dv(e){if(!e)return"Not restricted";return`${e.startTime}-${e.endTime} ${e.timezone} (${(e.days??["every day"]).join(", ")})`}function ive(e){if(e.clearBccEmails&&e.bccEmails!==void 0)throw new A("Use either --clear-bcc-emails or --bcc-emails, not both",400);if(e.clearBccEmails)return null;if(e.bccEmails===void 0)return;let t=Array.from(new Set(e.bccEmails.split(",").map((n)=>n.trim()).filter((n)=>n.length>0)));return t.length>0?t:null}var sve={live:"running",enrollment_paused:"new enrollments paused, existing recipients continue",paused:"recipients frozen, nobody new enters",draft:"not running",archived:"not running"};function kp(e){let t=e.status??"Unknown",n=e.effectiveStatus===void 0?void 0:sve[e.effectiveStatus];if(n!==void 0)return`${t} (${n})`;return e.enrollmentPaused===!0?`${t} (new enrollments paused)`:t}function J4(e){if(e.effectiveStatusSummary!==void 0)console.log(`State: ${e.effectiveStatusSummary}`)}function ave(e){let t=[],n=e.sequenceName??e.sequenceId??"Sequence";if(t.push(`Sequence: ${n}${e.sequenceId?` [${e.sequenceId}]`:""}`),t.push(`Status: ${kp({status:e.status,enrollmentPaused:e.enrollmentPaused,effectiveStatus:e.effectiveStatus})}`),e.effectiveStatusSummary)t.push(`State: ${e.effectiveStatusSummary}`);t.push("Sends mail: no");let r=e.readiness;if(r){t.push(`Ready to activate: ${r.ready===!0?"yes":"no"}`);for(let c of r.errors??[])t.push(` Error: ${c}`);for(let c of r.warnings??[])t.push(` Warning: ${c}`)}let o=e.enrollment;if(o){if(t.push("Enrollment"),o.triggerType)t.push(` Trigger: ${o.triggerType}`);if(o.summary)t.push(` ${o.summary}`);if(o.note)t.push(` ${o.note}`);if(o.error)t.push(` Trigger error: ${o.error}`);if(o.autoEnrollOnActivateCount!==void 0)t.push(` Auto-enroll on activate: ${o.autoEnrollOnActivateCount}`);if(typeof o.currentlyMatchingCount==="number"){let c=o.currentlyMatchingEnrollsAutomatically?"enrolled on the first hourly check":"not enrolled automatically";t.push(` Currently matching: ${o.currentlyMatchingCount} (${c})`)}else if(o.currentlyMatchingAvailable===!1)t.push(" Currently matching: unavailable (evaluated by the hourly worker)");for(let c of o.currentlyMatchingSample??[]){let l=c.email??c.id??"unknown";t.push(c.name?` - ${c.name} <${l}>`:` - ${l}`)}}let a=e.path;if(a){let c=a.subscriber?.email??a.subscriber?.id??"subscriber";if(t.push(`Path for ${c}`),a.emailsOnPath!==void 0){let l=`${a.emailsOnPath} deliverable email${a.emailsOnPath===1?"":"s"}`;if(a.emailStepsOnPath!==void 0&&a.emailStepsOnPath!==a.emailsOnPath)t.push(` ${a.emailStepsOnPath} email step${a.emailStepsOnPath===1?"":"s"} on this path; ${l}`);else t.push(` ${l} on this path`)}for(let l of a.steps??[]){let p=l.label??l.nodeType??l.nodeId??"step",f=l.outcome;if(f){let h=f.assumed?" (assumed)":"",b=f.branchId?` [${f.branchId}]`:"";t.push(` ${p}: ${f.verdict??"unknown"}${b}${h} - ${f.reason??""}`)}else t.push(` ${p}`)}if(a.truncated)t.push(" Path truncated")}return t}function FB(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t!=="visual"&&t!=="plain")throw new A("--email-style must be 'visual' or 'plain'",400);return t}function W4(e){if(e===void 0)return;if(e!=="sequence_created_at"&&e!=="subscriber_created_at")throw new A("--inactivity-baseline must be 'sequence_created_at' or 'subscriber_created_at'",400);return e}function V4(e){let t=Vbe(e.listScope),n=G4(e.listIds,e.listId),r=G4(e.tagNames,e.tagName);if(t!==void 0&&n!==void 0)throw new A("Provide either --list-id/--list-ids or --list-scope, not both",400);if(t!==void 0&&e.trigger!==void 0&&e.trigger!=="contact_added")throw new A("--list-scope only applies to a contact_added trigger",400);if(e.pauseNewEnrollments&&e.resumeNewEnrollments)throw new A("Provide either --pause-new-enrollments or --resume-new-enrollments, not both",400);if(e.userCancellable&&e.notUserCancellable)throw new A("Provide either --user-cancellable or --not-user-cancellable, not both",400);if(e.clearLabels&&e.label!==void 0)throw new A("Provide either --label or --clear-labels, not both",400);if((e.branchJson!==void 0||e.branchFile!==void 0)&&(e.insertStepsJson!==void 0||e.insertStepsFile!==void 0))throw new A("Provide either --branch-json/--branch-file or --insert-steps-json/--insert-steps-file, not both",400);let o=[e.branchJson!==void 0||e.branchFile!==void 0,e.insertStepsJson!==void 0||e.insertStepsFile!==void 0,e.graphEditJson!==void 0||e.graphEditFile!==void 0].filter(Boolean).length;if(o>1)throw new A("Provide only one of --branch-*, --insert-steps-*, or --graph-edit-*",400);if((e.nodeUpdatesJson!==void 0||e.nodeUpdatesFile!==void 0)&&(e.stepsJson!==void 0||e.stepsFile!==void 0||e.emailsJson!==void 0||e.emailsFile!==void 0||e.smsStepsJson!==void 0||e.smsStepsFile!==void 0||e.subscriberUpdateStepsJson!==void 0||e.subscriberUpdateStepsFile!==void 0||o>0))throw new A("--node-updates-* cannot be combined with legacy step updates or structural graph changes",400);let a=Ybe(e),c=rve(e),l=ove(e),p=eve(e),f=nve(e),h=ive(e);return{...e.name!==void 0&&{name:e.name},...e.description!==void 0&&{description:e.description},...e.label!==void 0&&{labels:e.label},...e.clearLabels===!0&&{labels:[]},...e.userCancellable===!0&&{userCancellable:!0},...e.notUserCancellable===!0&&{userCancellable:!1},...e.trigger!==void 0&&{trigger:e.trigger},...e.goal!==void 0&&e.goal.trim().length>0&&{goal:e.goal.trim()},...ot(e.emailCount,"--email-count")!==void 0&&{emailCount:ot(e.emailCount,"--email-count")},...ot(e.durationDays,"--duration-days")!==void 0&&{durationDays:ot(e.durationDays,"--duration-days")},...FB(e.emailStyle)!==void 0&&{emailStyle:FB(e.emailStyle)},...e.pauseNewEnrollments===!0&&{enrollmentPaused:!0},...e.resumeNewEnrollments===!0&&{enrollmentPaused:!1},...e.confirmStructuralChange===!0&&{confirmStructuralChange:!0},...e.confirmLiveChange===!0&&{confirmLiveChange:!0},...f!==void 0&&{audienceAutoEnroll:f},...H4(e.enrollmentMode)!==void 0&&{enrollmentMode:H4(e.enrollmentMode)},...e.enrollmentFieldPath!==void 0&&{enrollmentFieldPath:e.enrollmentFieldPath},...a!==void 0&&{sendingWindow:a},...c!==void 0&&{frequencyCapEnabled:c},...l!==void 0&&{activeSubscribersOnly:l},...p!==void 0&&{keyDates:p},...h!==void 0&&{bccEmails:h},...n!==void 0&&{listId:n[0],listIds:n},...t!==void 0&&{listScope:t},...r!==void 0&&{tagName:r[0],tagNames:r},...e.segmentId!==void 0&&{segmentId:e.segmentId},...e.stopOnSegmentExit!==void 0&&{stopOnSegmentExit:e.stopOnSegmentExit},...e.eventName!==void 0&&{eventName:e.eventName},...e.integrationSlug!==void 0&&{integrationSlug:e.integrationSlug},...e.integrationEventKey!==void 0&&{integrationEventKey:e.integrationEventKey},...Oe(e.customIntegrationJson,e.customIntegrationFile,"customIntegration")!==void 0&&{customIntegration:Oe(e.customIntegrationJson,e.customIntegrationFile,"customIntegration")},...Oe(e.propertyFiltersJson,e.propertyFiltersFile,"propertyFilters")!==void 0&&{propertyFilters:Oe(e.propertyFiltersJson,e.propertyFiltersFile,"propertyFilters")},...ot(e.inactiveDays,"--inactive-days")!==void 0&&{inactiveDays:ot(e.inactiveDays,"--inactive-days")},...W4(e.inactivityBaseline)!==void 0&&{inactivityBaseline:W4(e.inactivityBaseline)},...ot(e.minCount,"--min-count")!==void 0&&{minCount:ot(e.minCount,"--min-count")},...ot(e.timeWindowDays,"--time-window-days")!==void 0&&{timeWindowDays:ot(e.timeWindowDays,"--time-window-days")},...Oe(e.stepsJson,e.stepsFile,"steps")!==void 0&&{steps:Oe(e.stepsJson,e.stepsFile,"steps")},...Oe(e.emailsJson,e.emailsFile,"emails")!==void 0&&{emails:Oe(e.emailsJson,e.emailsFile,"emails")},...Oe(e.smsStepsJson,e.smsStepsFile,"smsSteps")!==void 0&&{smsSteps:Oe(e.smsStepsJson,e.smsStepsFile,"smsSteps")},...Oe(e.subscriberUpdateStepsJson,e.subscriberUpdateStepsFile,"subscriberUpdateSteps")!==void 0&&{subscriberUpdateSteps:Oe(e.subscriberUpdateStepsJson,e.subscriberUpdateStepsFile,"subscriberUpdateSteps")},...Oe(e.branchJson,e.branchFile,"branch")!==void 0&&{branch:Oe(e.branchJson,e.branchFile,"branch")},...Oe(e.insertStepsJson,e.insertStepsFile,"insertSteps")!==void 0&&{insertSteps:Oe(e.insertStepsJson,e.insertStepsFile,"insertSteps")},...Oe(e.nodeUpdatesJson,e.nodeUpdatesFile,"nodeUpdates")!==void 0&&{nodeUpdates:Oe(e.nodeUpdatesJson,e.nodeUpdatesFile,"nodeUpdates")},...Oe(e.graphEditJson,e.graphEditFile,"graphEdit")!==void 0&&{graphEdit:Oe(e.graphEditJson,e.graphEditFile,"graphEdit")},...Oe(e.stopConditionJson,e.stopConditionFile,"stopCondition")!==void 0&&{stopCondition:Oe(e.stopConditionJson,e.stopConditionFile,"stopCondition")},...e.fromEmail!==void 0&&{fromEmail:e.fromEmail},...e.fromName!==void 0&&{fromName:e.fromName},...e.senderProfileId!==void 0&&{senderProfileId:e.senderProfileId},...e.replyTo!==void 0&&{replyTo:e.replyTo},...e.replyToName!==void 0&&{replyToName:e.replyToName},...e.replyProfileId!==void 0&&{replyProfileId:e.replyProfileId}}}function cve(e){return Array.from(new Set((e??"").split(",").map((t)=>t.trim()).filter((t)=>t.length>0)))}function lve(e){let t=(a)=>Array.from(new Set((a??[]).map((c)=>c.trim()).filter((c)=>c.length>0))),n=t(e.nodeIds),r=t(e.subscriberIds),o=e.cursor?.trim();return{...e.nodeIds!==void 0&&{nodeIds:n},...e.subscriberIds!==void 0&&{subscriberIds:r},...o&&{cursor:o},dryRun:e.apply!==!0}}function ug(e){if(/^[A-Za-z0-9_./:@+-]+$/.test(e))return e;return`'${e.replaceAll("'",`'"'"'`)}'`}function qB(e){let t=["sequenzy","sequences","realign-enrollments",ug(e.id)],n=(r,o)=>{let a=(o??[]).map((c)=>c.trim()).filter((c)=>c.length>0);if(a.length>0)t.push(r,...a.map(ug))};if(n("--node-ids",e.nodeIds),n("--subscriber-ids",e.subscriberIds),"jobId"in e&&e.jobId)t.push("--job-id",ug(e.jobId));else if("cursor"in e&&e.cursor){if(t.push("--cursor",ug(e.cursor)),e.apply)t.push("--apply")}if(e.company)t.push("--company",ug(e.company));return t.join(" ")}function uve(e){let t=e.subscriberId?.trim(),n=Array.from(new Set((e.subscriberIds??[]).map((c)=>c.trim()).filter((c)=>c.length>0))),r=cve(e.fieldValues),o=e.all===!0;if((t!==void 0&&t.length>0?1:0)+(n.length>0?1:0)+(r.length>0?1:0)+(o?1:0)!==1)throw new A("Provide exactly one target: --all, --subscriber-id, --subscriber-ids, or --field-values",400);return{...o&&{cancelAll:!0},...t!==void 0&&t.length>0&&{subscriberId:t},...n.length>0&&{subscriberIds:n},...e.fieldPath!==void 0&&e.fieldPath.trim().length>0&&{fieldPath:e.fieldPath.trim()},...r.length>0&&{fieldValues:r},dryRun:e.apply!==!0,...e.reason!==void 0&&e.reason.trim().length>0&&{reason:e.reason.trim()}}}function dve(e){let n=Array.isArray(e.email)&&e.email.length>0||e.emailsJson!==void 0||e.emailsFile!==void 0?op(e):[],r=Array.from(new Set((e.subscriberIds??[]).map((o)=>o.trim()).filter((o)=>o.length>0)));if(n.length===0&&r.length===0)throw new A("Provide at least one email address or subscriber ID",400);return{...n.length>0&&{emails:n},...r.length>0&&{subscriberIds:r},...e.targetNodeId!==void 0&&{targetNodeId:e.targetNodeId}}}function pve(e){let t=[],n=e.emails??[],r=e.subscriberIds??[],o=0,a=0;while(o<n.length||a<r.length){let c=n.slice(o,o+M4);o+=c.length;let l=M4-c.length,p=r.slice(a,a+l);a+=p.length,t.push({...c.length>0&&{emails:c},...p.length>0&&{subscriberIds:p},...e.targetNodeId!==void 0&&{targetNodeId:e.targetNodeId}})}return t}function mve(e){let t=e.goal?.trim(),n=!!t,r=!!e.stepsJson||!!e.stepsFile;if(n&&r)throw new A("Provide either --goal or --steps-json/--steps-file, not both",400);if(e.emailCount!==void 0&&!n)throw new A("--email-count requires --goal",400);if(e.durationDays!==void 0&&!n)throw new A("--duration-days requires --goal",400);if(e.emailStyle!==void 0&&!n)throw new A("--email-style requires --goal",400);FB(e.emailStyle);let o=ot(e.emailCount,"--email-count");if(o!==void 0&&o>j4)throw new A(`--email-count must be no more than ${j4}`,400);let a=ot(e.durationDays,"--duration-days");if(a!==void 0&&a<1)throw new A("--duration-days must be at least 1",400);return n?{mode:"goal",goal:t}:r?{mode:"steps"}:{mode:"blank"}}function fve(e){if(e.isActive&&e.notActive)throw new A("Provide either --active or --inactive, not both",400);return{...e.name!==void 0&&{name:e.name},...e.description!==void 0&&{description:e.description},...e.triggerType!==void 0&&{triggerType:e.triggerType},...e.triggerEventName!==void 0&&{triggerEventName:e.triggerEventName},...e.triggerTagName!==void 0&&{triggerTagName:e.triggerTagName},...e.attributePath!==void 0&&{attributePath:e.attributePath},...e.attributeCondition!==void 0&&{attributeCondition:e.attributeCondition},...e.attributeValue!==void 0&&{attributeValue:e.attributeValue},...e.attributePreviousValue!==void 0&&{attributePreviousValue:e.attributePreviousValue},...e.eventPropertyName!==void 0&&{eventPropertyName:e.eventPropertyName},...e.eventPropertyLabel!==void 0&&{eventPropertyLabel:e.eventPropertyLabel},...ot(e.attributionWindowHours,"--attribution-window-hours")!==void 0&&{attributionWindowHours:ot(e.attributionWindowHours,"--attribution-window-hours")},...e.isActive&&{isActive:!0},...e.notActive&&{isActive:!1}}}function gve(e){let t=Oe(e.fieldMappingJson,e.fieldMappingFile,"fieldMapping"),n=Oe(e.samplePayloadJson,e.samplePayloadFile,"samplePayload");if(e.clearFieldMapping&&t!==void 0)throw new A("Provide either --field-mapping-json/--field-mapping-file or --clear-field-mapping, not both",400);if(e.clearSamplePayload&&n!==void 0)throw new A("Provide either --sample-payload-json/--sample-payload-file or --clear-sample-payload, not both",400);if(t!==void 0&&(typeof t.email!=="string"||!t.email.trim()))throw new A("fieldMapping.email is required",400);return{...e.clearFieldMapping?{fieldMapping:null}:t!==void 0?{fieldMapping:t}:{},...e.clearSamplePayload?{samplePayload:null}:n!==void 0?{samplePayload:n}:{}}}async function Cn(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="list"){let c=new URLSearchParams;if(t.status)c.set("status",t.status);if(t.search)c.set("search",t.search);if(t.label?.length)c.set("labels",t.label.join(","));if(t.limit)c.set("limit",t.limit);if(t.offset)c.set("offset",t.offset);let l=c.size>0?`?${c.toString()}`:"",p=await E("GET",`/api/v1/sequences${l}`,void 0,t.company),f=await Gt(t.company),h=f!==void 0?ct({companyId:f}):void 0,b=p.sequences.map((C)=>f!==void 0?Ds(C,{sequenceId:C.id},"sequence",f):{...C,url:void 0});if(t.json){S({...p,sequences:b,...h!==void 0&&{appUrls:h.urls}});return}let v=p.pagination;console.log(v?`Sequences (${p.sequences.length} of ${v.total})`:`Sequences (${p.sequences.length})`);for(let C of b){if(console.log(`- ${C.name} [${C.id}]`),console.log(` Status: ${kp(C)}`),console.log(` Trigger: ${C.trigger??"Unknown"}`),console.log(` Sending window: ${Dv(C.sendingWindow)}`),C.frequencyCapEnabled!==void 0)console.log(` Frequency cap: ${Sv(C.frequencyCapEnabled)}`);console.log(` Created: ${X(C.createdAt)}`),Ce(" URL",C.url)}if(v?.hasMore)console.log(`More sequences available. Re-run with --offset ${v.offset+v.count} to fetch the next page.`);return}if(e==="create"){if(!t.name)throw new A("Sequence name is required",400);let c=mve(t),l=await E("POST","/api/v1/sequences",V4({...t,...c.goal!==void 0&&{goal:c.goal}}),t.company),p=await Gt(t.company),f=l.sequence?.id??l.sequenceId,h=p!==void 0&&f!==void 0?ct({companyId:p,sequenceId:f}):void 0;if(t.json){S({...l,...l.sequence!==void 0&&h?.urls.sequence!==void 0&&{sequence:{...l.sequence,url:h.urls.sequence}},...h!==void 0&&{appUrls:h.urls}});return}if(xn(l),console.log(`Created sequence: ${l.sequence?.name??t.name}`),console.log(`ID: ${l.sequence?.id??"Unknown"}`),Ce("URL",h?.urls.sequence),console.log(`Status: ${kp(l.sequence??{})}`),l.sequence?.emailCount!==void 0)console.log(`Emails: ${l.sequence.emailCount}`);if(l.sequence?.discountCount!==void 0)console.log(`Discount actions: ${l.sequence.discountCount}`);if("sendingWindow"in(l.sequence??{}))console.log(`Sending window: ${Dv(l.sequence?.sendingWindow)}`);if("frequencyCapEnabled"in(l.sequence??{}))console.log(`Frequency cap: ${Sv(l.sequence?.frequencyCapEnabled)}`);if("keyDates"in(l.sequence??{}))console.log(`Key dates: ${PB(l.sequence?.keyDates)}`);if("audienceAutoEnroll"in(l.sequence??{}))console.log(`Auto-enroll: ${OB(l.sequence?.audienceAutoEnroll)}`);if(c.mode==="goal")console.log("Mode: AI-generated");if(l.message)console.log(l.message);return}if(!t.id)throw new A("Sequence ID is required",400);if(e==="test"){let c=Jbe(t),l=await E("POST",c.path,c.body,t.company),p=await Gt(t.company),f=p!==void 0?ct({companyId:p,sequenceId:t.id}):void 0;if(t.json){S({...l,...f!==void 0&&{appUrls:f.urls}});return}console.log(l.message??`Queued ${l.results.length} sequence step test email${l.results.length===1?"":"s"}`);for(let h of l.results)console.log(`- ${h.recipientEmail}: email send ${h.emailSendId}`);Ce("URL",f?.urls.sequence);return}if(e==="goals"){let c=await E("GET",`/api/v1/sequences/${t.id}/goals`,void 0,t.company);if(t.json)return S(c);let l=Array.isArray(c.goals)?c.goals:[];console.log(`Sequence goals (${l.length})`);for(let p of l){if(typeof p!=="object"||p===null)continue;let f=p;console.log(`- ${String(f.name??"Unnamed goal")} [${String(f.id??"unknown")}]`)}return}if(e==="goal-create"||e==="goal-update"){if(e==="goal-create"&&!t.name)throw new A("Goal name is required",400);if(e==="goal-update"&&!t.goalId)throw new A("Goal ID is required",400);let c=await E(e==="goal-create"?"POST":"PATCH",`/api/v1/sequences/${t.id}/goals${t.goalId?`/${t.goalId}`:""}`,fve(t),t.company);if(t.json)return S(c);let l=c.goal;if(console.log(`${e==="goal-create"?"Created":"Updated"} sequence goal: ${String(l?.name??t.name??t.goalId)}`),l?.id)console.log(`ID: ${String(l.id)}`);return}if(e==="goal-delete"){if(!t.goalId)throw new A("Goal ID is required",400);let c=await E("DELETE",`/api/v1/sequences/${t.id}/goals/${t.goalId}`,void 0,t.company);if(t.json)return S(c);console.log(`Deleted sequence goal: ${t.goalId}`);return}if(e==="webhook-get"||e==="webhook-configure"||e==="webhook-rotate"){let c=e==="webhook-configure",l=e==="webhook-rotate",p=await E(l?"POST":c?"PUT":"GET",`/api/v1/sequences/${t.id}/inbound-webhook${l?"/rotate-secret":""}`,c?gve(t):void 0,t.company);if(t.json)return S(p);let f=p.webhook;if(console.log(`${l?"Rotated":c?"Configured":"Sequence"} inbound webhook: ${String(f?.status??"Unknown status")}`),f?.url)console.log(`URL: ${String(f.url)}`);return}if(e==="update"){if(t.name===void 0&&t.description===void 0&&t.label===void 0&&t.clearLabels!==!0&&t.userCancellable!==!0&&t.notUserCancellable!==!0&&t.trigger===void 0&&t.fromEmail===void 0&&t.fromName===void 0&&t.senderProfileId===void 0&&t.replyTo===void 0&&t.replyToName===void 0&&t.replyProfileId===void 0&&t.enrollmentMode===void 0&&t.enrollmentFieldPath===void 0&&t.pauseNewEnrollments!==!0&&t.resumeNewEnrollments!==!0&&t.sendingWindowStart===void 0&&t.sendingWindowEnd===void 0&&t.sendingWindowTimezone===void 0&&t.sendingWindowDays===void 0&&t.clearSendingWindow!==!0&&t.respectFrequencyCap!==!0&&t.ignoreFrequencyCap!==!0&&t.activeSubscribersOnly!==!0&&t.includeSuppressedSubscribers!==!0&&t.keyDate===void 0&&t.keyDatesJson===void 0&&t.keyDatesFile===void 0&&t.keyDatesTimezone===void 0&&t.clearKeyDates!==!0&&t.sendSpreadHours===void 0&&t.autoEnrollAll!==!0&&t.autoEnrollListIds===void 0&&t.autoEnrollSegmentId===void 0&&t.autoEnrollJson===void 0&&t.autoEnrollStartsAt===void 0&&t.clearAutoEnroll!==!0&&t.bccEmails===void 0&&t.clearBccEmails!==!0&&!t.stepsJson&&!t.stepsFile&&!t.emailsJson&&!t.emailsFile&&!t.smsStepsJson&&!t.smsStepsFile&&!t.subscriberUpdateStepsJson&&!t.subscriberUpdateStepsFile&&!t.branchJson&&!t.branchFile&&!t.insertStepsJson&&!t.insertStepsFile&&!t.nodeUpdatesJson&&!t.nodeUpdatesFile&&!t.graphEditJson&&!t.graphEditFile&&!t.stopConditionJson&&!t.stopConditionFile)throw new A("Provide at least one sequence metadata, identity, settings, step, nodeUpdates, or graphEdit option",400);let c=await E("PUT",`/api/v1/sequences/${t.id}`,V4(await Xbe(t)),t.company),l=await Gt(t.company),p=l!==void 0?ct({companyId:l,sequenceId:t.id}):void 0;if(t.json){S({...c,...c.sequence!==void 0&&p?.urls.sequence!==void 0&&{sequence:{...c.sequence,url:p.urls.sequence}},...p!==void 0&&{appUrls:p.urls}});return}xn(c),console.log(`Updated sequence: ${c.sequence?.name??t.id}`),console.log(`ID: ${c.sequence?.id??t.id}`),Ce("URL",p?.urls.sequence),console.log(`Status: ${kp(c.sequence??{})}`);for(let f of jbe(c.sequence))console.log(f);for(let f of Mbe(c.sequence))console.log(f);if("sendingWindow"in(c.sequence??{}))console.log(`Sending window: ${Dv(c.sequence?.sendingWindow)}`);if("frequencyCapEnabled"in(c.sequence??{}))console.log(`Frequency cap: ${Sv(c.sequence?.frequencyCapEnabled)}`);if("keyDates"in(c.sequence??{}))console.log(`Key dates: ${PB(c.sequence?.keyDates)}`);if("audienceAutoEnroll"in(c.sequence??{}))console.log(`Auto-enroll: ${OB(c.sequence?.audienceAutoEnroll)}`);if("bccEmails"in(c.sequence??{}))console.log(`BCC: ${c.sequence?.bccEmails?.join(", ")||"None"}`);return}if(e==="pause-enrollments"||e==="resume-enrollments"){let c=await E("POST",`/api/v1/sequences/${t.id}/${e}`,void 0,t.company),l=await Gt(t.company),p=l!==void 0?ct({companyId:l,sequenceId:t.id}):void 0;if(t.json){S({...c,...p!==void 0&&{appUrls:p.urls}});return}console.log(c.message??`Updated sequence ${t.id}`),J4(c),Ce("URL",p?.urls.sequence);return}if(e==="duplicate"){let c=await E("POST",`/api/v1/sequences/${t.id}/duplicate`,t.name===void 0?void 0:{name:t.name},t.company),l=c.sequence?.id??c.sequenceId,p=await Gt(t.company),f=p!==void 0&&l!==void 0?ct({companyId:p,sequenceId:l}):void 0;if(t.json){S({...c,...f!==void 0&&{appUrls:f.urls}});return}if(console.log(`Duplicated sequence: ${c.sequence?.name??l??t.id}`),l)console.log(`ID: ${l}`);console.log(`Status: ${kp(c.sequence??{})}`),Ce("URL",f?.urls.sequence);return}if(e==="archive"||e==="unarchive"){let c=await E("POST",`/api/v1/sequences/${t.id}/${e}`,void 0,t.company);if(t.json){S(c);return}console.log(`${e==="archive"?"Archived":"Restored"} sequence: ${c.sequence?.name??t.id}`);return}if(e==="test-run"||e==="test-run-get"){let c;if(e==="test-run"){if(!t.subscriber?.trim())throw new A("Pass --subscriber for a live sequence test",400);let p=Oe(t.eventProperties,void 0,"event-properties");if(p!==void 0&&(p===null||typeof p!=="object"||Array.isArray(p)))throw new A("--event-properties must be a JSON object",400);let f=t.speedMultiplier===void 0?120:Number(t.speedMultiplier);if(!Number.isInteger(f)||f<60||f>1e4)throw new A("--speed-multiplier must be an integer between 60 and 10000",400);c={subscriberId:t.subscriber.trim(),speedMultiplier:f,...p!==void 0?{customVariables:p}:{}}}else if(!t.runId)throw new A("Pass a test run ID",400);let l=await E(e==="test-run"?"POST":"GET",`/api/v1/sequences/${encodeURIComponent(t.id??"")}/test-runs${e==="test-run-get"?`/${encodeURIComponent(t.runId??"")}`:""}`,c,t.company);if(t.json)S(l);else{if(console.log(`Sequence test ${l.run.id}: ${l.run.status}`),l.run.errorMessage)console.log(l.run.errorMessage);if(e==="test-run")console.log(`Inspect: sequenzy sequences test-run-get ${t.id} ${l.run.id}${t.company?` --company ${t.company}`:""} --json`)}return}if(e==="simulate"){let c=t.subscriber?.trim(),l=t.simulateEmail?.trim();if(c&&l)throw new A("Pass --subscriber or --email, not both",400);let p=new URLSearchParams;if(c)p.set("subscriberId",c);if(l)p.set("email",l);if(t.limit)p.set("limit",t.limit);let f=p.size>0?`?${p.toString()}`:"",h=await E("GET",`/api/v1/sequences/${t.id}/simulate${f}`,void 0,t.company),b=await Gt(t.company),v=b!==void 0?ct({companyId:b,sequenceId:t.id}):void 0;if(t.json){S({...h,...v!==void 0&&{appUrls:v.urls}});return}for(let C of ave(h))console.log(C);Ce("URL",v?.urls.sequence);return}if(e==="enable"||e==="disable"){let c=await E("POST",`/api/v1/sequences/${t.id}/${e}`,void 0,t.company),l=await Gt(t.company),p=l!==void 0?ct({companyId:l,sequenceId:t.id}):void 0;if(t.json){S({...c,...p!==void 0&&{appUrls:p.urls}});return}xn(c),console.log(c.message??`${e}d sequence ${t.id}`),J4(c),Ce("URL",p?.urls.sequence);return}if(e==="enroll"){let c=dve(t),l=pve(c),p=0,f=0,h=[],b,v;for(let C of l){let R=await E("POST",`/api/v1/sequences/${t.id}/enroll`,C,t.company);p+=R.enrolled,f+=R.skipped,h.push(...R.notFound),b??=R.targetNodeId,v??=R.scheduledFor}if(t.json){S({success:!0,sequenceId:t.id,enrolled:p,skipped:f,notFound:h,...b!==void 0&&{targetNodeId:b},...v!==void 0&&{scheduledFor:v}});return}if(console.log(`Enrolled ${p} subscriber(s) in sequence: ${t.id}`),console.log(`Skipped (already enrolled, inactive, or unavailable): ${f}`),h.length>0){console.log(`Not found: ${h.length}`);for(let C of h.slice(0,10))console.log(`- ${C}`);if(h.length>10)console.log(`...and ${h.length-10} more`)}if(b!==void 0)console.log(`Target node: ${b}`);if(v!==void 0)console.log(`Scheduled for: ${X(v)}`);return}if(e==="realign-enrollments"){let c=await Gt(t.company),l=c!==void 0?ct({companyId:c,sequenceId:t.id}):void 0,p;if(t.jobId){let f=await E("GET",`/api/v1/sequences/${t.id}/enrollments/realign-sending-window/jobs/${encodeURIComponent(t.jobId)}`,void 0,t.company);if(t.json){S({...f,...l!==void 0&&{appUrls:l.urls}});return}if(!f.result){if(console.log(f.message??`Enrollment realignment is ${f.status}.`),f.status!=="failed")console.log(`Check again: ${qB({id:t.id,nodeIds:t.nodeIds,subscriberIds:t.subscriberIds,company:t.company,jobId:f.jobId})}`);Ce("URL",l?.urls.sequence);return}p=f.result}else{let f=lve(t),h=await E("POST",`/api/v1/sequences/${t.id}/enrollments/realign-sending-window`,f,t.company);if("status"in h){if(t.json){S({...h,...l!==void 0&&{appUrls:l.urls}});return}console.log(h.message??"Enrollment realignment queued."),console.log(`Job ID: ${h.jobId}`),console.log(`Check status: ${qB({id:t.id,nodeIds:t.nodeIds,subscriberIds:t.subscriberIds,company:t.company,jobId:h.jobId})}`),Ce("URL",l?.urls.sequence);return}p=h}if(t.json){S({...p,...l!==void 0&&{appUrls:l.urls}});return}if(console.log(p.message??"Sequence enrollment realignment complete"),p.sendingWindow){let f=p.sendingWindow;console.log(`Sending window: ${f.days.join(", ")} ${f.startTime}-${f.endTime} ${f.timezone}`)}else console.log("Sending window: none set on the sequence (per-step weekday gates only)");console.log(`Checked: ${p.scannedCount}`),console.log(`${p.dryRun?"Would realign":"Realigned"}: ${p.realignedCount}`),console.log(`Left as-is: ${p.unchangedCount}`);for(let[f,h]of Object.entries(p.unchangedReasons??{}))console.log(` ${f}: ${h}`);if(console.log(`Dry run: ${p.dryRun?"yes":"no"}`),p.requeueFailedCount>0)console.log(`Re-queue deferred to the sweeper: ${p.requeueFailedCount}`);if(p.changes.length>0){console.log(`Enrollments (first ${p.changes.length} of ${p.realignedCount}):`);for(let f of p.changes)console.log(`- ${f.subscriberEmail??f.subscriberId} | ${X(f.waitUntil)} -> ${X(f.newWaitUntil)} (${f.movedEarlierMinutes} min earlier)`)}if(p.dryRun&&p.realignedCount>0)console.log("Re-run with --apply to move these enrollments.");if(p.hasMore)console.log(p.nextCursor?`More enrollments remain. Continue with: ${qB({id:t.id,nodeIds:t.nodeIds,subscriberIds:t.subscriberIds,company:t.company,cursor:p.nextCursor,apply:!p.dryRun})}`:"More enrollments remain. Re-run the command to continue.");Ce("URL",l?.urls.sequence);return}if(e==="cancel-enrollments"){let c=uve(t),l=`/api/v1/sequences/${t.id}/enrollments/cancel`,p=await E("POST",l,c,t.company),f=p.matchedCount,h=p.cancelledCount,b=1;while(!p.dryRun&&(p.remainingCount??0)>0&&p.cancelledCount>0&&b<Hbe){if(!t.json)console.log(`Cancelled ${h} so far, ${p.remainingCount} remaining...`);p=await E("POST",l,c,t.company),h+=p.cancelledCount,b+=1}let v=p.remainingCount??0,C=b===1?p.message??"Sequence enrollment cancellation done":`Cancelled ${h} sequence enrollment${h===1?"":"s"} across ${b} requests.${v>0?` ${v} still match; re-run the same command to continue.`:""}`,R=await Gt(t.company),N=R!==void 0?ct({companyId:R,sequenceId:t.id}):void 0;if(t.json){S({...p,matchedCount:f,cancelledCount:h,message:C,requests:b,...N!==void 0&&{appUrls:N.urls}});return}if(console.log(C),console.log(`Matched: ${f}`),console.log(`Cancelled: ${h}`),console.log(`Remaining: ${v}`),console.log(`Dry run: ${p.dryRun?"yes":"no"}`),v>0&&!p.dryRun)console.log("Stopped before draining every enrollment. Re-run the same command to continue.");if((p.target?.notFoundSubscriberIds?.length??0)>0)console.log(`Subscriber IDs not found: ${p.target?.notFoundSubscriberIds?.join(", ")}`);if(p.hasMore)console.log("Only the first matching enrollments are shown.");if((p.enrollments?.length??0)>0){console.log("Enrollments:");for(let L of p.enrollments??[])console.log(`- ${L.tokenId} | ${L.subscriberEmail??L.subscriberId} [${L.status}]`)}Ce("URL",N?.urls.sequence);return}if(e==="delete"){let c=await E("DELETE",`/api/v1/sequences/${t.id}`,void 0,t.company);if(t.json){S(c);return}console.log(c.message??`Deleted sequence ${t.id}`);return}let n=await E("GET",`/api/v1/sequences/${t.id}`,void 0,t.company),r=await Gt(t.company),o=r!==void 0?ct({companyId:r,sequenceId:t.id}):void 0;if(t.json){S({...n,...o?.urls.sequence!==void 0&&{sequence:{...n.sequence,url:o.urls.sequence}},...o!==void 0&&{appUrls:o.urls}});return}let a=n.sequence;if(console.log(a.name),console.log(`ID: ${a.id}`),Ce("URL",o?.urls.sequence),console.log(`Status: ${kp(a)}`),console.log(`Trigger: ${a.trigger??"Unknown"}`),console.log(`Sending window: ${Dv(a.sendingWindow)}`),a.frequencyCapEnabled!==void 0)console.log(`Frequency cap: ${Sv(a.frequencyCapEnabled)}`);if(a.activeSubscribersOnly!==void 0)console.log(`Enrolls: ${a.activeSubscribersOnly?"active subscribers only":"all statuses (marketing emails skipped for unsubscribed and bounced)"}`);if(console.log(`Key dates: ${PB(a.keyDates)}`),a.audienceAutoEnroll)console.log(`Auto-enroll: ${OB(a.audienceAutoEnroll)}`);if(console.log(`BCC: ${a.bccEmails?.join(", ")||"None"}`),console.log(`Created: ${X(a.createdAt)}`),console.log(`Enrichment: ${a.enrichmentStatus} (${a.enrichedCount}/${a.emailCount})`),a.emails.length>0){console.log("Emails:");for(let c of a.emails){if(console.log(`- ${zbe(c)}`),console.log(` Email ID: ${c.emailId??"None"}`),console.log(` Name: ${c.name??"None"}`),console.log(` Subject: ${c.subject??"None"}`),console.log(` Preview: ${c.previewText??"None"}`),console.log(` Format: ${Cs(c.emailPreset)}`),console.log(` Theme: ${Jz(c.emailTheme)}`),c.attachments&&c.attachments.length>0)console.log(` Attachments: ${c.attachments.map((l)=>`${l.filename} (${l.path})`).join(", ")}`);if(console.log(` Blocks: ${c.blocks.length}`),c.abTest){console.log(` A/B test: ${c.abTest.id??"Unknown"}${c.abTest.status?` (${c.abTest.status})`:""}`);for(let l of c.abTest.variants??[])console.log(` Variant ${l.variantLabel}: ${l.subject??"None"}${l.isWinner?" (winner)":""}`),console.log(` Variant ID: ${l.variantId}`),console.log(` Blocks: ${l.blockCount??0}`);console.log(` ${Py}`)}}}}catch(n){k(n instanceof A?n:n),process.exit(1)}}function yl(e,t,n){if(e===void 0)return;let r=Number(e);if(!Number.isFinite(r)||r<=0)throw new A(`${t} must be a positive number`,400);if(r>n)throw new A(`${t} must be at most ${n}`,400);return r}function Ave(e){let t={};if(e.resetBrowseAbandonment){if(e.browseAbandonment!==void 0||e.browseDelayHours!==void 0||e.browseCooldownHours!==void 0)throw new A("--reset-browse-abandonment cannot be combined with other browse flags",400);t.browseAbandonment=null}else{let n={},r=ui(e.browseAbandonment,"--browse-abandonment");if(r!==void 0)n.enabled=r;let o=yl(e.browseDelayHours,"--browse-delay-hours",hz);if(o!==void 0)n.delayHours=o;let a=yl(e.browseCooldownHours,"--browse-cooldown-hours",yz);if(a!==void 0)n.cooldownHours=a;if(Object.keys(n).length>0)t.browseAbandonment=n}if(e.resetCartAbandonment){if(e.cartAbandonment!==void 0||e.cartDelayHours!==void 0||e.cartCooldownHours!==void 0||e.cartExpireAfterHours!==void 0)throw new A("--reset-cart-abandonment cannot be combined with other cart flags",400);t.cartAbandonment=null}else{let n={},r=ui(e.cartAbandonment,"--cart-abandonment");if(r!==void 0)n.enabled=r;let o=yl(e.cartDelayHours,"--cart-delay-hours",bz);if(o!==void 0)n.delayHours=o;let a=yl(e.cartCooldownHours,"--cart-cooldown-hours",vz);if(a!==void 0)n.cooldownHours=a;let c=yl(e.cartExpireAfterHours,"--cart-expire-after-hours",Ez);if(c!==void 0)n.expireAfterHours=c;if(Object.keys(n).length>0)t.cartAbandonment=n}if(e.resetPriceDrop){if(e.priceDrop!==void 0||e.priceDropMinPercent!==void 0||e.priceDropLookbackDays!==void 0||e.priceDropCooldownDays!==void 0)throw new A("--reset-price-drop cannot be combined with other price-drop flags",400);t.priceDrop=null}else{let n={},r=ui(e.priceDrop,"--price-drop");if(r!==void 0)n.enabled=r;let o=yl(e.priceDropMinPercent,"--price-drop-min-percent",Iz);if(o!==void 0)n.minPercent=o;let a=yl(e.priceDropLookbackDays,"--price-drop-lookback-days",Cz);if(a!==void 0)n.lookbackDays=a;let c=yl(e.priceDropCooldownDays,"--price-drop-cooldown-days",wz);if(c!==void 0)n.cooldownDays=c;if(Object.keys(n).length>0)t.priceDrop=n}if(Object.keys(t).length===0)throw new A("Provide at least one settings flag (see --help for the full list)",400);return t}function Z4(e){let{browseAbandonment:t,cartAbandonment:n,priceDrop:r}=e;if(console.log(`Shopify automation settings (${e.shopDomain})`),console.log(""),console.log(`Browse abandonment: ${t.enabled?"on":"off"}`),console.log(" Emails shoppers who view a product but don't buy, add to cart, or start checkout."),console.log(` Waits ${t.delayHours}h after the view - at most one email per subscriber per ${t.cooldownHours}h`),n)console.log(""),console.log(`Cart abandonment: ${n.enabled?"on":"off"}`),console.log(" Fires ecommerce.cart_abandoned with the full cart after the cart sits untouched with no checkout or order."),console.log(` Waits ${n.delayHours}h of inactivity - at most one per subscriber per ${n.cooldownHours}h`),console.log(` Drops a cart untouched for ${n.expireAfterHours}h instead of emailing about it`);console.log(""),console.log(`Price drop alerts: ${r.enabled?"on":"off"}`),console.log(` Emails recent viewers when a product's price falls by ${r.minPercent}% or more.`),console.log(` Audience: viewers from the last ${r.lookbackDays} days - at most one email per product per subscriber per ${r.cooldownDays} days`)}async function LB(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="get"){let o=await E("GET","/api/v1/shopify/automation-settings",void 0,t.company);if(t.json){S(o);return}Z4(o);return}let n=Ave(t),r=await E("PUT","/api/v1/shopify/automation-settings",n,t.company);if(t.json){S(r);return}if(r.message)console.log(r.message),console.log("");Z4(r)}catch(n){k(n instanceof A?n:n),process.exit(1)}}function hve(e){let{sms:t}=e;if(console.log(`SMS add-on: ${t.enabled?"enabled":"not enabled"}`),console.log(`Plan eligible: ${t.planEligible?"yes":"no"}`),console.log(`Credits balance: ${t.creditsBalance}`),console.log(`Brand prefix: ${t.brandPrefix??"(not set)"}`),t.numbers.length===0)console.log("Numbers: none");else{console.log("Numbers:");for(let n of t.numbers){let r=[n.label,n.brandPrefix?`prefix: ${n.brandPrefix}`:null,n.linkShorteningEnabled===!1?"links sent as written":null].filter(Boolean).join(", ");console.log(` ${n.e164} [${n.id}] (${n.status})${r?` - ${r}`:""}`)}}console.log(),console.log(e.message)}function yve(e){if(e.usage.length===0){console.log("No SMS sends recorded yet.");return}for(let t of e.usage)console.log(t.fromNumber),console.log(` Sends: ${t.totalSends} (delivered: ${t.delivered}, failed: ${t.failed}, test: ${t.testSends})`),console.log(` Credits charged: ${t.creditsCharged}`),console.log(` Last sent: ${t.lastSentAt??"never"}`)}function bve(e){return{to:Rn(e.phone??"","Phone number").trim(),text:Rn(e.text??"","--text").trim(),...e.imageUrl&&e.imageUrl.length>0?{imageUrls:e.imageUrl}:{},...e.fromNumber?.trim()?{fromNumberId:e.fromNumber.trim()}:{}}}function vve(e){return{label:e.label?.trim()||null}}function Eve(e){let t=e.trim().toLowerCase();if(t==="on")return!0;if(t==="off")return!1;throw Error('--link-shortening must be "on" or "off".')}function Ive(e){if(e.label===void 0&&e.brandPrefix===void 0&&e.linkShortening===void 0)throw Error("Provide --label, --brand-prefix, and/or --link-shortening.");return{...e.label!==void 0?{label:e.label.trim()||null}:{},...e.brandPrefix!==void 0?{brandPrefix:e.brandPrefix.trim()||null}:{},...e.linkShortening!==void 0?{linkShorteningEnabled:Eve(e.linkShortening)}:{}}}async function Tu(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="settings"){let n=await E("GET","/api/v1/sms/settings",void 0,t.company);if(t.json){S(n);return}hve(n);return}if(e==="send-test"){let n=await E("POST","/api/v1/sms/test",bve(t),t.company);if(t.json){S(n);return}console.log(n.message);return}if(e==="usage"){let n=await E("GET","/api/v1/sms/usage",void 0,t.company);if(t.json){S(n);return}yve(n);return}if(e==="release"){let n=Rn(t.numberId??"","SMS number ID").trim();if(!await mt(`Release SMS number ${n}? The number is handed back to the carrier and cannot be recovered.`,t)){console.log("Aborted.");return}let r=await E("DELETE",`/api/v1/sms/numbers/${encodeURIComponent(n)}`,void 0,t.company);if(t.json){S(r);return}console.log(r.message);return}if(e==="label"||e==="update"){let n=Rn(t.numberId??"","SMS number ID").trim(),r=await E("PATCH",`/api/v1/sms/numbers/${encodeURIComponent(n)}`,e==="label"?vve(t):Ive(t),t.company);if(t.json){S(r);return}console.log(r.message)}}catch(n){k(n instanceof A?n:n),process.exit(1)}}var Qu=yt(In(),1);var X4=["email","sequence","email_type","mailbox_provider","recipient_domain"],Cve={permanent_bounce:"permanent bounces",temporary_bounce:"temporary bounces",blocked:"blocked sends",complaint:"sends with spam complaints"};function wve(e){if(e.emails||e.clients||e.links)throw new A("--by cannot be combined with --emails, --clients or --links",400);if(e.campaign||e.sequence||e.transactional)throw new A("--by covers the account; narrow it with --source campaign:<id>, sequence:<id> or transactional:<id> instead",400);if(e.by&&!X4.includes(e.by))throw new A(`--by must be one of: ${X4.join(", ")}`,400);let t=new URLSearchParams;for(let[n,r]of[["by",e.by],["period",e.period],["start",e.start],["end",e.end],["emailType",e.emailType],["mailboxProvider",e.mailboxProvider],["recipientDomain",e.recipientDomain],["source",e.source],["outcome",e.outcome],["limit",e.limit]])if(r)t.set(n,r);if(e.includeBots)t.set("includeMachineEngagement","true");return`/api/v1/metrics/breakdown?${t.toString()}`}function Sve(e){if(!e)return"";switch(e.kind){case"source":return`--source ${e.source.type}:${e.source.id}`;case"email_type":return`--email-type ${e.emailType}`;case"mailbox_provider":return`--mailbox-provider ${e.mailboxProvider}`;case"recipient_domain":return`--recipient-domain ${e.recipientDomain}`}}function UB(e){return`${e.toFixed(1)}%`}function Dve(e){let t=e.period&&e.period!=="custom"?e.period:`${e.start??""} - ${e.end??""}`,n=e.outcome?`, only ${Cve[e.outcome]??e.outcome}`:"",r=[`Breakdown by ${e.by.replace("_"," ")} (${t}${n})`];if(e.rows.length===0)return r.push("No emails were sent with these filters in this period."),r;let o=e.rows.some((c)=>c.revenue!==null),a=Math.max(4,...e.rows.map((c)=>c.sent.toLocaleString().length));r.push("",` ${"Sent".padStart(a)} Open Click Bounce${o?" Revenue":""} Name`);for(let c of e.rows){let l=o?` ${(c.revenue===null?"-":`$${Math.round(c.revenue).toLocaleString()}`).padStart(10)}`:"",p=c.detail?` (${c.detail})`:"";r.push(` ${c.sent.toLocaleString().padStart(a)} ${UB(c.openRate).padStart(5)} ${UB(c.clickRate).padStart(5)} ${UB(c.bounceRate).padStart(6)}${l} ${c.label}${p}`);let f=Sve(c.filter);if(f)r.push(` ${"".padStart(a)} drill in: ${f}`)}return r}async function eW(e){let t=await E("GET",wve(e),void 0,e.company);if(e.json){S(t);return}for(let n of Dve(t))console.log(n)}function Bve(e){if(e.emails)throw new A("--clients cannot be combined with --emails",400);if(e.sequence||e.transactional)throw new A("--clients supports account-level stats and --campaign only",400);if(e.campaign&&(e.period||e.start||e.end||e.emailType))throw new A("--clients with --campaign covers the whole campaign; --period, --start, --end, and --email-type apply to account-level stats only",400);let t=new URLSearchParams;if(!e.campaign){for(let[o,a]of[["period",e.period],["start",e.start],["end",e.end],["emailType",e.emailType]])if(a)t.set(o,a)}if(e.mailboxProvider)t.set("mailboxProvider",e.mailboxProvider);if(e.includeBots)t.set("includeMachineEngagement","true");let n=t.toString(),r=e.campaign?`/api/v1/metrics/campaigns/${encodeURIComponent(e.campaign)}/clients`:"/api/v1/metrics/clients";return n?`${r}?${n}`:r}function _ve(e){return`${e.toFixed(e>0&&e<1?1:0)}%`}function xve(e){let n=[`Email clients (${e.campaignId?`campaign ${e.campaignId}`:e.period==="custom"&&e.start&&e.end?`${e.start} - ${e.end}`:e.period??"all time"})`];if(e.totalOpens===0)return n.push("No opens recorded yet."),n;let r=Math.max(...[...e.clients,...e.devices].map((o)=>o.label.length));for(let[o,a]of[["Clients",e.clients],["Devices",e.devices]]){n.push("",`${o}:`);for(let c of a)n.push(` ${c.label.padEnd(r)} ${_ve(c.share).padStart(4)} ${c.opens.toLocaleString()} ${c.opens===1?"open":"opens"}`)}return n.push("",`Based on ${e.totalOpens.toLocaleString()} unique ${e.totalOpens===1?"open":"opens"}; ${e.privacyProxyOpens.toLocaleString()} came through Gmail, Yahoo, or Apple Mail privacy proxies, which hide the device.`),n}async function tW(e){let t=await E("GET",Bve(e),void 0,e.company);if(e.json){S(t);return}for(let n of xve(t))console.log(n)}var nW=["sent","delivered","opened","clicked","openRate","clickRate","unsubscribed","conversions","revenue","step","name"],kve=["step","sort","order","page","limit"];function rW(e){if(e.emails)return;let t=kve.find((n)=>e[n]!==void 0&&!(n==="limit"&&(e.links||e.by)));if(t)throw new A(`--${t} requires --emails`,400)}function Rve(e){if(e.transactional)throw new A("--emails covers campaigns and sequence steps; --transactional is not supported",400);if(e.emailType!==void 0&&!["campaign","sequence"].includes(e.emailType))throw new A("--email-type must be 'campaign' or 'sequence' with --emails",400);if(e.sort!==void 0&&!nW.includes(e.sort))throw new A(`--sort must be one of: ${nW.join(", ")}`,400);if(e.order!==void 0&&!["asc","desc"].includes(e.order))throw new A("--order must be 'asc' or 'desc'",400);if(e.mailboxProvider)throw new A("--mailbox-provider applies to account-level stats and --campaign only",400);if(e.campaign&&(e.sequence||e.step))throw new A("--campaign cannot be combined with --sequence or --step when using --emails",400);let t=new URLSearchParams,n=[["emailType",e.emailType],["sequenceId",e.sequence],["campaignId",e.campaign],["step",e.step],["sort",e.sort],["order",e.order],["page",e.page],["limit",e.limit]];for(let[o,a]of n)if(a!==void 0&&a.trim()!=="")t.set(o,a.trim());if(e.start||e.end){if(e.start)t.set("start",e.start);if(e.end)t.set("end",e.end)}else if(e.period)t.set("period",e.period);if(e.includeBots)t.set("includeMachineEngagement","true");let r=t.toString();return r?`?${r}`:""}async function Tve(e){return E("GET",`/api/v1/metrics/emails${Rve(e)}`,void 0,e.company)}function Qve(e){let t=e.emailType==="sequence"?`${e.sequenceName??"Unknown sequence"}${e.step!==null?` · Step ${e.step}`:""}`:"Campaign",n=`${e.stats.opened.toLocaleString()} opened (${e.stats.openRate.toFixed(1)}%), ${e.stats.clicked.toLocaleString()} clicked (${e.stats.clickRate.toFixed(1)}%)`;return`${e.name} — ${e.stats.sent.toLocaleString()} sent, ${n} [${t}, ${e.emailId}]`}function $ve(e){let{totals:t,pagination:n}=e,r=e.period?e.period==="custom"?`${e.start??"?"} to ${e.end??"?"}`:e.period:"all time";if(console.log(`Per-email metrics (${r}${e.step!==void 0?`, step ${e.step}`:""})`),console.log(`Totals: ${t.emails.toLocaleString()} emails, ${t.sent.toLocaleString()} sent, ${t.delivered.toLocaleString()} delivered, ${t.opened.toLocaleString()} opened (${t.openRate.toFixed(1)}%), ${t.clicked.toLocaleString()} clicked (${t.clickRate.toFixed(1)}%)`),console.log(`Page: ${n.page}/${n.totalPages||1} (${n.total.toLocaleString()} matching emails)`),e.emails.length===0){console.log("No emails found.");return}console.log("");for(let o of e.emails)console.log(`- ${Qve(o)}`)}async function oW(e){let t=await Tve(e);if(e.json){S(t);return}$ve(t)}function Nve(e){if(e.emails||e.clients)throw new A("--links cannot be combined with --emails or --clients",400);if(e.campaign||e.sequence||e.transactional)throw new A("--links covers the whole account; for one campaign's links use 'sequenzy stats --campaign <id> --json' and read clickedLinks",400);let t=new URLSearchParams;for(let[r,o]of[["period",e.period],["start",e.start],["end",e.end],["emailType",e.emailType],["mailboxProvider",e.mailboxProvider],["limit",e.limit]])if(o)t.set(r,o);if(e.includeBots)t.set("includeMachineEngagement","true");let n=t.toString();return n?`/api/v1/metrics/links?${n}`:"/api/v1/metrics/links"}function Ove(e){return`${e.toFixed(e>0&&e<1?1:0)}%`}function Pve(e){let n=[`Link clicks (${e.period==="custom"&&e.start&&e.end?`${e.start} - ${e.end}`:e.period??"all time"})`];if(e.totalClicks===0)return n.push("No link clicks in this period."),n;let r=Math.max(...e.links.map((o)=>o.uniqueClicks.toLocaleString().length));n.push("");for(let o of e.links)n.push(` ${o.uniqueClicks.toLocaleString().padStart(r)} ${Ove(o.share).padStart(4)} ${o.clicks.toLocaleString()} ${o.clicks===1?"click":"clicks"} ${o.url}`);return n.push("",`${e.totalUniqueClicks.toLocaleString()} unique ${e.totalUniqueClicks===1?"click":"clicks"} (${e.totalClicks.toLocaleString()} total) across ${e.totalLinks.toLocaleString()} ${e.totalLinks===1?"link":"links"}${e.links.length<e.totalLinks?`; showing the top ${e.links.length}`:""}. Each subscriber counts once per link, and query strings are ignored, so UTM-tagged variants of a page count together.`),n}async function iW(e){let t=await E("GET",Nve(e),void 0,e.company);if(e.json){S(t);return}for(let n of Pve(t))console.log(n)}var W=yt(cg(),1);function qve(e,t){if(e===void 0||t===void 0)return null;return`${t.toLocaleString()} active (${e.toLocaleString()} total)`}function Fve(e){let t=e.recipients===1?"recipient":"recipients",n=e.clickers===1?"clicker":"clickers";return{impressions:`${e.impressions.toLocaleString()} (${e.recipients.toLocaleString()} ${t})`,clicks:`${e.clicks.toLocaleString()} (${e.clickers.toLocaleString()} ${n})`,orders:e.orders.toLocaleString(),revenue:(e.revenueByCurrency?.length??0)>0?(e.revenueByCurrency??[]).map(({currency:r,revenueCents:o})=>{let a=(o/100).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});return r==="UNKNOWN"?`${a} (currency unknown)`:`${r} ${a}`}).join(" + "):e.revenueCents>0?`${e.revenueCents.toLocaleString()} minor units (currency unavailable)`:"—",topProducts:e.topProducts.map((r)=>`${r.provider}:${r.providerProductId}: ${r.impressions.toLocaleString()} shown, ${r.clicks.toLocaleString()} clicked`)}}function Lve(e){let t=e.blocked??0;return[`Permanent: ${e.permanent.toLocaleString()}`,`Soft: ${Math.max(0,e.transient-t).toLocaleString()}`,`Blocked: ${t.toLocaleString()}`,`Undetermined: ${e.undetermined.toLocaleString()}`].join(" · ")}function Uve(e){let t=e.allowMultiple?e.totalResponses===1?"respondent · multiple answers":"respondents · multiple answers":e.totalResponses===1?"response":"responses";return{heading:`${e.question||"Poll"} (${e.totalResponses.toLocaleString()} ${t})`,details:[...e.nps?[`NPS: ${e.nps.score>0?"+":""}${e.nps.score} · Average: ${e.nps.average.toFixed(1)} · ${e.nps.promoters} promoters · ${e.nps.passives} passives · ${e.nps.detractors} detractors`]:[],...e.answers.map((n)=>`- ${n.answer}: ${n.responses.toLocaleString()} (${n.percentage}%)`)]}}function sW({polls:e,indent:t=0}){return W.jsxDEV(W.Fragment,{children:e.map((n)=>{let{heading:r,details:o}=Uve(n);return W.jsxDEV(Re,{flexDirection:"column",marginBottom:1,marginLeft:t,children:[W.jsxDEV(me,{children:r},void 0,!1,void 0,this),o.map((a)=>W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:a},void 0,!1,void 0,this)},a,!1,void 0,this))]},n.blockId,!0,void 0,this)})},void 0,!1,void 0,this)}function jve(e){let t=e.stats;return{subscriberCount:e.subscriberCount,activeSubscriberCount:e.activeSubscriberCount,sent:t.sent,delivered:t.delivered,opened:t.opened,clicked:t.clicked,replies:t.replies??0,unsubscribed:t.unsubscribed,openRate:t.openRate,clickRate:t.clickRate,replyRate:t.replyRate??0,complaints:t.complaints,complaintRate:t.complaintRate,conversions:t.conversions,revenueCents:t.revenueCents,enrollmentSkipped:e.enrollmentSkipped,enrollmentCounts:e.enrollmentCounts,pausedEnrollments:e.pausedEnrollments,steps:e.steps,clickedLinks:e.clickedLinks,bounceBreakdown:e.bounceBreakdown,engagementBreakdown:e.engagementBreakdown,polls:e.polls,commerceForecast:e.commerceForecast,recommendations:e.recommendations}}function jB(e,t){try{return new Intl.NumberFormat(void 0,{style:"currency",currency:t??"USD",maximumFractionDigits:0}).format(e/100)}catch{return`${t??"USD"} ${Math.round(e/100).toLocaleString()}`}}function Bv(e){let t=new URLSearchParams,n=Boolean(e.campaign||e.sequence||e.transactional);if(e.start||e.end){if(e.start)t.set("start",e.start);if(e.end)t.set("end",e.end)}else if(!n)t.set("period",e.period??"7d");else if(e.period)t.set("period",e.period);if(!n&&e.emailType)t.set("emailType",e.emailType);if(!n&&e.recipientDomain)t.set("recipientDomain",e.recipientDomain);if(!n&&e.source)t.set("source",e.source);if(!n&&e.outcome)t.set("outcome",e.outcome);if(e.mailboxProvider)t.set("mailboxProvider",e.mailboxProvider);if(e.includeBots)t.set("includeMachineEngagement","true");let r=t.toString();return r?`?${r}`:""}async function aW(e){let t=[e.campaign,e.sequence,e.transactional].filter((n)=>n!==void 0);if(t.length>1)throw new A("Use only one of --campaign, --sequence, or --transactional",400);if(e.emailType!==void 0&&!["campaign","transactional","sequence"].includes(e.emailType))throw new A("--email-type must be 'campaign', 'transactional', or 'sequence'",400);if(e.emailType&&t.length>0)throw new A("--email-type filters account-level stats and cannot be combined with --campaign, --sequence, or --transactional",400);if((e.recipientDomain||e.source||e.outcome)&&t.length>0)throw new A("--recipient-domain, --source and --outcome filter account-level stats and cannot be combined with --campaign, --sequence, or --transactional",400);if(e.mailboxProvider&&(e.sequence||e.transactional))throw new A("--mailbox-provider applies to account-level stats and --campaign only",400);if(e.campaign)return E("GET",`/api/v1/metrics/campaigns/${e.campaign}${Bv(e)}`,void 0,e.company);if(e.sequence)return E("GET",`/api/v1/metrics/sequences/${e.sequence}${Bv(e)}`,void 0,e.company);if(e.transactional)return E("GET",`/api/v1/metrics/transactional/${encodeURIComponent(e.transactional)}${Bv(e)}`,void 0,e.company);return E("GET",`/api/v1/metrics${Bv(e)}`,void 0,e.company)}function zve({options:e}){let[t,n]=Qu.useState(!0),[r,o]=Qu.useState(""),[a,c]=Qu.useState(null);if(Qu.useEffect(()=>{async function v(){try{let C=await aW(e);c(jve(C))}catch(C){o(gf(C instanceof A?C:C))}finally{n(!1)}}v()},[e]),Qu.useEffect(()=>{if(!t)setTimeout(()=>process.exit(r?1:0),100)},[t,r]),t)return W.jsxDEV(Re,{padding:1,children:[W.jsxDEV(me,{color:"cyan",children:W.jsxDEV(Ev,{type:"dots"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.jsxDEV(me,{children:" Loading stats..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(r)return W.jsxDEV(Re,{padding:1,children:W.jsxDEV(me,{color:"red",children:[" ",r]},void 0,!0,void 0,this)},void 0,!1,void 0,this);if(!a)return W.jsxDEV(Re,{padding:1,children:W.jsxDEV(me,{dimColor:!0,children:"No stats available"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let l=e.period??"7d",p=e.campaign?"Campaign Stats":e.sequence?"Sequence Stats":e.transactional?"Transactional Email Stats":`Stats (${e.emailType?`${e.emailType}, `:""}${l})`,f=e.sequence&&a.steps?a.steps.filter((v)=>(v.failedCount??0)>0):[],h=a.recommendations?Fve(a.recommendations):null,b=qve(a.subscriberCount,a.activeSubscriberCount);return W.jsxDEV(Re,{flexDirection:"column",padding:1,children:[W.jsxDEV(Re,{marginBottom:1,children:[W.jsxDEV(me,{bold:!0,color:"green",children:p},void 0,!1,void 0,this),e.mailboxProvider&&W.jsxDEV(me,{dimColor:!0,children:[" for ",e.mailboxProvider," recipients"]},void 0,!0,void 0,this),e.outcome&&W.jsxDEV(me,{dimColor:!0,children:[" ","only sends with ",e.outcome.replace("_"," ")]},void 0,!0,void 0,this),e.includeBots&&W.jsxDEV(me,{dimColor:!0,children:" including bot/scanner engagement"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{flexDirection:"column",children:[b&&W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Subscribers: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:b},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Sent: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.sent.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a.complaints!==void 0&&W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Complaints: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.complaints.toLocaleString()},void 0,!1,void 0,this),a.complaintRate!==void 0&&W.jsxDEV(me,{dimColor:!0,children:[" (",a.complaintRate.toFixed(2),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Delivered: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.delivered.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Opened: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.opened.toLocaleString()},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:[" (",a.openRate.toFixed(1),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Clicked: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.clicked.toLocaleString()},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:[" (",a.clickRate.toFixed(1),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Replies: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.replies.toLocaleString()},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:[" (",a.replyRate.toFixed(1),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Unsubscribed: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.unsubscribed.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a.conversions!==void 0&&W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Conversions: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.conversions.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a.revenueCents!==void 0&&W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Revenue: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:["$",(a.revenueCents/100).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(a.enrollmentSkipped?.count??0)>0&&W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Skipped: "},void 0,!1,void 0,this),W.jsxDEV(me,{color:"yellow",children:a.enrollmentSkipped?.count.toLocaleString()},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:[" ","(",Object.entries(a.enrollmentSkipped?.byReason??{}).map(([v,C])=>`${C} ${v}`).join(", ")||"couldn't be enrolled","; contacts that triggered the sequence but can't receive emails)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),e.sequence&&(a.steps?.length??0)>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:[W.jsxDEV(me,{bold:!0,children:"Steps"},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:" · sent per email step, in graph order"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(a.steps??[]).map((v)=>W.jsxDEV(Re,{marginLeft:2,children:[W.jsxDEV(me,{children:[`${v.step}. ${v.subject??v.nodeId}: `,v.stats.sent.toLocaleString()," sent"]},void 0,!0,void 0,this),W.jsxDEV(me,{dimColor:!0,children:` · ${v.stats.delivered.toLocaleString()} delivered · ${v.stats.opened.toLocaleString()} opened · ${v.stats.clicked.toLocaleString()} clicked · ${v.nodeId}`},void 0,!1,void 0,this)]},v.nodeId,!0,void 0,this))]},void 0,!0,void 0,this),e.sequence&&(a.steps??[]).some((v)=>(v.polls?.length??0)>0)&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:[W.jsxDEV(me,{bold:!0,children:"Poll & NPS Results"},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:" · per email step, all time"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(a.steps??[]).filter((v)=>(v.polls?.length??0)>0).map((v)=>W.jsxDEV(Re,{flexDirection:"column",marginLeft:2,children:[W.jsxDEV(me,{bold:!0,children:`${v.step}. ${v.subject??v.nodeId}`},void 0,!1,void 0,this),W.jsxDEV(sW,{polls:v.polls??[],indent:2},void 0,!1,void 0,this)]},v.nodeId,!0,void 0,this))]},void 0,!0,void 0,this),e.sequence&&a.enrollmentCounts&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:[W.jsxDEV(me,{bold:!0,children:"Current Enrollments"},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:[` · ${a.enrollmentCounts.total.toLocaleString()} total, ${a.enrollmentCounts.active.toLocaleString()} active, ${a.enrollmentCounts.waiting.toLocaleString()} waiting`,a.pausedEnrollments&&a.pausedEnrollments.total>0?` · ${a.pausedEnrollments.total.toLocaleString()} paused (not in total)`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),a.enrollmentCounts.byCurrentNode.map((v)=>W.jsxDEV(Re,{marginLeft:2,children:[W.jsxDEV(me,{children:["-"," ",v.currentNodeLabel??v.currentNodeType??v.currentNodeId,": ",v.total.toLocaleString()," (",v.active.toLocaleString()," ","active, ",v.waiting.toLocaleString()," waiting)"]},void 0,!0,void 0,this),v.currentNodeMissing&&W.jsxDEV(me,{color:"yellow",children:" · node missing from sequence graph"},void 0,!1,void 0,this)]},v.currentNodeId,!0,void 0,this))]},void 0,!0,void 0,this),!e.campaign&&!e.sequence&&!e.transactional&&!e.emailType&&a.commerceForecast&&a.commerceForecast.history.orderCount>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:[W.jsxDEV(me,{bold:!0,children:"Commerce Forecast"},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:` · ${a.commerceForecast.history.orderCount.toLocaleString()} paid orders`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a.commerceForecast.status==="ready"&&a.commerceForecast.forecast?W.jsxDEV(W.Fragment,{children:[W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Predicted AOV: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:jB(a.commerceForecast.forecast.predictedAverageOrderValueCents,a.commerceForecast.currency)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"12-month LTV: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:jB(a.commerceForecast.forecast.predictedCustomerValue365DaysCents,a.commerceForecast.currency)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"90-day revenue: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:jB(a.commerceForecast.forecast.expectedRevenue90DaysCents,a.commerceForecast.currency)},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:` (${a.commerceForecast.forecast.expectedOrders90Days.toLocaleString()} orders, ${a.commerceForecast.confidence} confidence)`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):W.jsxDEV(me,{dimColor:!0,children:a.commerceForecast.eligibility.reasons.map((v)=>v.message).join(" · ")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:W.jsxDEV(me,{bold:!0,children:"Product Recommendations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Impressions: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:h.impressions},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Clicks: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:h.clicks},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Orders: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:h.orders},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Revenue: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:h.revenue},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h.topProducts.length>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(me,{bold:!0,children:"Top Products"},void 0,!1,void 0,this),h.topProducts.map((v)=>W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["- ",v]},void 0,!0,void 0,this)},v,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),f.length>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:W.jsxDEV(me,{bold:!0,children:"Step Failures"},void 0,!1,void 0,this)},void 0,!1,void 0,this),f.map((v)=>W.jsxDEV(Re,{flexDirection:"column",marginBottom:1,children:[W.jsxDEV(me,{children:["Step ",v.step,": ",v.subject??v.nodeId," (",v.failedCount," failed",")"]},void 0,!0,void 0,this),(v.failedSubscribers??[]).map((C)=>W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["- ",C.email??C.subscriberId,":"," ",C.failedReason??"Reason unavailable"]},void 0,!0,void 0,this)},`${v.nodeId}-${C.subscriberId}`,!1,void 0,this)),(v.failedCount??0)>(v.failedSubscribers?.length??0)&&W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{dimColor:!0,children:["Showing first ",v.failedSubscribers?.length??0," of"," ",v.failedCount," failed subscribers"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},v.nodeId,!0,void 0,this))]},void 0,!0,void 0,this),a.clickedLinks&&a.clickedLinks.length>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:W.jsxDEV(me,{bold:!0,children:"Clicked Links"},void 0,!1,void 0,this)},void 0,!1,void 0,this),a.clickedLinks.map((v)=>W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["- ",v.url,": ",v.clicks.toLocaleString()," (",v.percentage.toFixed(1),"%)"]},void 0,!0,void 0,this)},v.url,!1,void 0,this))]},void 0,!0,void 0,this),a.bounceBreakdown&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(me,{bold:!0,children:"Bounce Breakdown"},void 0,!1,void 0,this),W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:Lve(a.bounceBreakdown)},void 0,!1,void 0,this)},void 0,!1,void 0,this),a.bounceBreakdown.subtypes.map((v)=>W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["- ",v.type," / ",v.subType??"Unknown",": ",v.count]},void 0,!0,void 0,this)},`${v.type}-${v.subType??"unknown"}`,!1,void 0,this))]},void 0,!0,void 0,this),a.engagementBreakdown&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(me,{bold:!0,children:"Human vs Machine Engagement"},void 0,!1,void 0,this),W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["Human: ",a.engagementBreakdown.human.opens," opens ·"," ",a.engagementBreakdown.human.clicks," clicks"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["Machine: ",a.engagementBreakdown.machine.opens," opens ·"," ",a.engagementBreakdown.machine.clicks," clicks"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a.polls&&a.polls.length>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:W.jsxDEV(me,{bold:!0,children:"Poll & NPS Results"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.jsxDEV(sW,{polls:a.polls},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Mve(e){return e.outcome&&(e.links||e.clients||e.emails)?new A("--outcome filters account stats and --by only, not --links, --clients or --emails",400):null}async function cW(e){try{rW(e)}catch(r){k(r),process.exitCode=1;return}if(!await j())k(M()),process.exit(1);if(e.by){try{await eW(e)}catch(r){k(r),process.exitCode=1}return}let t=Mve(e);if(t){k(t),process.exitCode=1;return}if(e.links){try{await iW(e)}catch(r){k(r),process.exitCode=1}return}if(e.clients){try{await tW(e)}catch(r){k(r),process.exitCode=1}return}if(e.emails){try{await oW(e)}catch(r){k(r),process.exitCode=1}return}if(e.json){try{S(await aW(e))}catch(r){k(r),process.exitCode=1}return}await ag(W.jsxDEV(zve,{options:e},void 0,!1,void 0,this)).waitUntilExit()}var lW=500;function _v(e){return Array.from(new Set((e??[]).map((t)=>t.trim()).filter((t)=>t.length>0)))}function Hve(e){return Array.isArray(e.email)&&e.email.length>0||e.emailsJson!==void 0||e.emailsFile!==void 0}function Gve(e,t){let n=_v(e.tag);if(n.length===0)throw new A("Provide at least one --tag",400);let r=Hve(e)?_v(op(e)):[],o=_v(e.externalId),a=_v(e.subscriberId);if(r.length+o.length+a.length===0)throw new A("Provide at least one target: --email, --emails-file, --emails-json, --external-id, or --subscriber-id",400);let c=[...r.map((p)=>({kind:"emails",value:p})),...o.map((p)=>({kind:"externalIds",value:p})),...a.map((p)=>({kind:"subscriberIds",value:p}))],l=[];for(let p=0;p<c.length;p+=lW){let f=c.slice(p,p+lW),h=f.filter((C)=>C.kind==="emails").map((C)=>C.value),b=f.filter((C)=>C.kind==="externalIds").map((C)=>C.value),v=f.filter((C)=>C.kind==="subscriberIds").map((C)=>C.value);l.push({tags:n,...h.length>0&&{emails:h},...b.length>0&&{externalIds:b},...v.length>0&&{subscriberIds:v},...t==="add"&&e.triggerAutomations===!0?{triggerAutomations:!0}:{}})}return l}function Jve(e){let t=e[0];if(!t)throw new A("No bulk tag responses to combine",500);return e.reduce((n,r)=>({success:n.success&&r.success,tags:r.tags,requested:n.requested+r.requested,matched:n.matched+r.matched,updated:n.updated+r.updated,unchanged:n.unchanged+r.unchanged,failed:n.failed+r.failed,notFound:{emails:[...n.notFound.emails,...r.notFound.emails],externalIds:[...n.notFound.externalIds,...r.notFound.externalIds],subscriberIds:[...n.notFound.subscriberIds,...r.notFound.subscriberIds]},failures:[...n.failures,...r.failures],triggeredAutomations:n.triggeredAutomations===!0||r.triggeredAutomations===!0}),{success:!0,tags:t.tags,requested:0,matched:0,updated:0,unchanged:0,failed:0,notFound:{emails:[],externalIds:[],subscriberIds:[]},failures:[],triggeredAutomations:!1})}function Wve(e,t){if(console.log(`${t==="add"?"Added":"Removed"} tags: ${e.tags.join(", ")}`),console.log(`Requested: ${e.requested}`),console.log(`Matched existing subscribers: ${e.matched}`),console.log(`Changed: ${e.updated}`),console.log(`Already in target state: ${e.unchanged}`),console.log(`Failed: ${e.failed}`),t==="add")console.log(`Tag automations: ${e.triggeredAutomations?"enabled":"skipped"}`);let n=[...e.notFound.emails,...e.notFound.externalIds,...e.notFound.subscriberIds];if(n.length>0){console.log(`Not found (not created): ${n.length}`);for(let r of n.slice(0,10))console.log(`- ${r}`);if(n.length>10)console.log(`...and ${n.length-10} more`)}for(let r of e.failures.slice(0,10))console.log(`- ${r.email??r.subscriberId}: ${r.error}`);if(e.failures.length>10)console.log(`...and ${e.failures.length-10} more failures`)}async function zB(e,t){if(!await j())k(M()),process.exit(1);try{let n=Gve(t,e),r=[];for(let a of n)r.push(await E("POST",`/api/v1/subscribers/bulk/tags/${e}`,a,t.company));let o=Jve(r);if(t.json){S({...o,requests:n.length});return}Wve(o,e)}catch(n){k(n instanceof A?n:n),process.exit(1)}}import{randomUUID as Vve}from"node:crypto";var MB="/api/v1/subscribers/operations";async function xv(e,t){if(e!=="start"&&e!=="list"&&!t.id)throw Error("Operation ID is required");let n=t.id?`${MB}/${encodeURIComponent(t.id)}`:MB;if(e==="list"){let a=await E("GET",MB,void 0,t.company);if(t.json)S(a);else for(let c of a.operations)uW(c);return}let r;if(e==="start"){if(t.kind!=="add_tags")throw Error("--kind must be add_tags");let a=t.audienceJson?JSON.parse(kn(t.audienceJson.startsWith("@")?void 0:t.audienceJson,t.audienceJson.startsWith("@")?t.audienceJson.slice(1):void 0,"audience-json")??"{}"):{},c=t.requestKey??Vve();rp(`Request key: ${c}. If the request is interrupted, retry with --request-key ${c}.`,{json:t.json,type:"recovery",requestKey:c}),r={kind:t.kind,requestKey:c,audience:a,...t.tag!==void 0&&{tags:t.tag},...t.triggerAutomations!==void 0&&{triggerAutomations:t.triggerAutomations}}}let o=await E(e==="get"?"GET":"POST",e==="cancel"?`${n}/cancel`:n,r,t.company);if(t.json)S(o);else uW(o.operation)}function uW(e){console.log(`${e.id} ${e.kind} ${e.status} ${e.processed}/${e.total} processed, ${e.failed} failed`);for(let t of e.failures)console.log(`${t.subscriberId}: ${t.error}`);if(e.error)console.log(e.error)}function HB(e,t){let n={...Df("--attrs-json",t),...e};return Object.keys(n).length>0?n:void 0}function Kve(e){let t=e.isArray?`${e.valueType} list`:e.valueType,n=e.mixedTypes?`${t}, mixed types`:t,r=e.sampleValue===null?"":` e.g. ${e.sampleValue}`;return`${e.key} (${n})${r}`}async function dW(e){let t=e.includeNested?"?includeNested=true":"",n=await E("GET",`/api/v1/subscribers/attributes${t}`,void 0,e.company);if(e.json){S(n);return}if(n.attributes.length===0){console.log("No custom attributes yet.");return}for(let o of n.attributes)console.log(Kve(o));let r=n.sampledContacts>0?`Types and examples come from ${n.sampledContacts} recent contacts.`:"Types and examples come from the account's attribute index.";console.log(`
|
|
317
|
+
`,"utf8"),console.log(`Exported ${n.enrollments.length} enrollments to ${t.csv}`);else console.log(a);return}if(t.json){S(n);return}let{pagination:r}=n;console.log(`Enrollments in ${n.sequenceName} (${r.count} of ${r.total}, statuses: ${n.statuses.join(", ")})`);let o=n.stopCondition;if(o&&o.type!=="none"){if(console.log(`Stop condition: ${o.type}${o.value?` = ${o.value}`:""}`),o.matchConfig)console.log(` match config: ${JSON.stringify(o.matchConfig)}`)}if(n.enrollments.length===0){console.log("No enrollments matched the filters.");return}for(let a of n.enrollments){console.log(""),console.log(`- ${a.email??a.subscriberId}${Nbe(a)} [${a.status}]`),console.log(` at ${k4(a)}`),console.log(` enrolled ${X(a.enrollmentStartedAt)}${a.waitUntil?`, resumes ${X(a.waitUntil)}`:""}`);let c=a.enteredVia?.description;if(c&&a.enteredVia?.kind!=="unknown")console.log(` entered via ${c}`);let l=a.entryContext;if(l?.eventName){let f=l.eventPropertyKeys.length>0?` keys ${l.eventPropertyKeys.join(", ")}`:"";console.log(` entry event ${l.eventName}${f}`)}else if(l?.triggerType)console.log(` entry trigger ${l.triggerType}`);let p=a.branchDecisions?.at(-1);if(p){let f=NB(p);console.log(` branch ${p.selectedPath}${f?`: ${f}`:""}`)}if(a.branchDecisionsTruncated)console.log(` branch history truncated: showing ${a.branchDecisions?.length??0} of ${a.branchDecisionCount??"unknown"}`);if(a.failedReason)console.log(` failed: ${a.failedReason}`);if(a.stopConditionMatches===!0)console.log(` stop condition matches now: ${a.stopConditionMatchReason??"condition met"}`),console.log(" -> worker re-checks before a future step; a step already in progress may still finish");if(a.status==="paused")console.log(` paused${a.pausedAt?` since ${X(a.pausedAt)}`:""}${a.pauseReason?` (${a.pauseReason})`:""}; resume with sequenzy sequences resume-subscribers`);if(a.movedAt)console.log(` released from ${a.movedFromNodeId??"an earlier step"} on ${X(a.movedAt)}${a.moveReason?` (${a.moveReason})`:""}`);console.log(` subscriberId ${a.subscriberId}`)}if(console.log(""),t.stopConditionMatch)console.log(`Stop-condition match checked for ${n.stopConditionMatchEvaluatedCount??0} enrollment(s). A waiting enrollment whose stop condition already matches keeps reporting "waiting" until its delay expires, then is re-checked before continuing. This is a current-state snapshot; a step already in progress may still finish.`);if(r.hasMore)console.log(`More results: sequenzy sequences enrollments ${e} --offset ${r.offset+r.count}`);if(!t.all&&t.csv===void 0)console.log(`Export every match: sequenzy sequences enrollments ${e} --all --csv enrollments.csv`);console.log(`Node-level counts: sequenzy stats --sequence ${e} # enrollmentCounts.byCurrentNode`)}async function R4(e,t){if(!await j())k(M()),process.exit(1);try{await Obe(e,t)}catch(n){k(n instanceof A?n:n),process.exit(1)}}async function T4(e,t,n){if(!await j())k(M()),process.exit(1);try{let r=await E("GET",`/api/v1/sequences/${encodeURIComponent(e)}/enrollments/${encodeURIComponent(t)}`,void 0,n.company);if(n.json){S(r);return}let o=r.enrollment;console.log(`Enrollment ${o.enrollmentId} in ${r.sequenceName} [${o.status}]`),console.log(` at ${k4(o)}`),console.log(` enrolled ${X(o.enrollmentStartedAt)}`);let a=o.enteredVia?.description;if(a)console.log(` entered via ${a}`);let c=o.entryContext;if(c?.eventName)console.log(` entry event ${c.eventName}${c.eventPropertyKeys.length>0?` keys ${c.eventPropertyKeys.join(", ")}`:""}`);if(console.log(` history from ${r.historySource}`),r.nodeHistoryTruncated)console.log(` node history truncated after ${r.nodeHistoryLimit} events`);if(o.branchDecisionsTruncated)console.log(` branch history truncated: showing ${o.branchDecisions?.length??0} of ${o.branchDecisionCount??"unknown"}`);if(r.nodeHistory.length===0)console.log(" no recorded node events");let l=new Set;for(let p of r.nodeHistory){let f=p.nodeLabel??p.nodeType??p.nodeId,h=p.branchDecision;if(h)l.add(B4(h));let b=h?NB(h):void 0,v=h?` branch ${h.selectedPath}${b?` (${b})`:""}`:"";console.log(` ${X(p.eventTime)} ${p.eventType} ${f}${v}`)}for(let p of o.branchDecisions??[]){if(l.has(B4(p)))continue;let f=NB(p);console.log(` ${X(p.decidedAt)} branch ${p.nodeId} ${p.selectedPath}${f?` (${f})`:""}`)}}catch(r){k(r instanceof A?r:r),process.exit(1)}}var Q4=["wait_until_asc","wait_until_desc","enrolled_at_asc","enrolled_at_desc"];function $4(e,t){if(e===void 0)return;let n=e.trim(),r=t==="--daily-limit"?0:1;if(!/^\d+$/.test(n))throw new A(`${t} must be a whole number`,400);let o=Number(n);if(!Number.isSafeInteger(o)||o<r)throw new A(`${t} must be at least ${r}`,400);return o}function N4(e){return Array.from(new Set((e??[]).map((t)=>t.trim()).filter((t)=>t.length>0)))}function Pbe(e){let t=e.fromNode?.trim();if(!t)throw new A("--from-node is required",400);if(e.sort!==void 0&&!Q4.includes(e.sort))throw new A(`--sort must be one of: ${Q4.join(", ")}`,400);let n=e.toNode?.trim(),r=N4(e.subscriberIds),o=N4(e.tag),a=$4(e.limit,"--limit"),c=$4(e.dailyLimit,"--daily-limit"),l=e.reason?.trim();return{fromNodeId:t,...n?{targetNodeId:n}:{},...a!==void 0&&{limit:a},...c!==void 0&&{dailyLimit:c},...e.sort!==void 0&&{sort:e.sort},...r.length>0&&{subscriberIds:r},...o.length>0&&{tags:o},...l?{reason:l}:{},dryRun:e.apply!==!0}}function qbe(e){if(console.log(e.message),console.log(""),console.log(`From step ${e.fromNodeId}`),console.log(`To step ${e.targetNodeId}`),console.log(`Matched ${e.matchedCount}, moved ${e.movedCount}, remaining ${e.remainingCount} (sorted by ${e.sort})`),e.skippedCount>0)console.log(`Skipped ${e.skippedCount} enrollment(s) that are active, mid-step, or awaiting double opt-in.`);if(e.dailyLimit!==null)console.log(`Daily limit ${e.dailyLimit}: ${e.movedInWindow} already moved in the last 24h, ${e.dailyRemaining} left.`);if(e.tagResult)console.log(`Tagged ${e.tagResult.updated} contact(s) with ${e.tagResult.tags.join(", ")} (${e.tagResult.unchanged} already tagged, ${e.tagResult.failed} failed).`);if(e.enqueueErrors.length>0)console.log(`${e.enqueueErrors.length} enrollment(s) could not be queued; the stuck-enrollment sweeper will retry them.`);if(e.enrollments.length>0){console.log(""),console.log(e.dryRun?"Would move:":"Moved:");for(let t of e.enrollments)console.log(`- ${t.subscriberEmail??t.subscriberId} [${t.status}]`);if(e.hasMore)console.log(`... and more (showing the first ${e.enrollments.length})`)}if(console.log(""),e.dryRun)console.log("Re-run with --apply to move them.");else if(e.remainingCount>0)console.log("Re-run the same command to release the next batch.")}async function O4(e,t){if(!await j())k(M()),process.exit(1);try{let n=Pbe(t),r=await E("POST",`/api/v1/sequences/${encodeURIComponent(e)}/enrollments/move`,n,t.company);if(t.json){S(r);return}qbe(r)}catch(n){k(n instanceof A?n:n),process.exit(1)}}var P4=500,Fbe={paused:"paused",already_paused:"already paused",in_progress:"step running now, retry shortly",resumed:"resumed",not_paused:"was not paused"};function q4(e){return Array.from(new Set((e??[]).flatMap((t)=>t.split(",")).map((t)=>t.trim()).filter((t)=>t.length>0)))}function Lbe(e,t){let n=q4(e.subscriberIds),r=q4(e.email);if(n.length===0&&r.length===0)throw new A("Provide --subscriber-ids, --email, or both",400);if(n.length+r.length>P4)throw new A(`A maximum of ${P4} subscriber IDs and emails combined can be targeted per command`,400);let o=e.reason?.trim();return{...n.length>0&&{subscriberIds:n},...r.length>0&&{emails:r},...t==="pause"&&o?{reason:o}:{}}}function Ube(e){if(console.log(e.message),e.enrollments.length>0){console.log("");for(let t of e.enrollments){let n=t.status==="paused"&&t.pausedAt?` since ${X(t.pausedAt)}`:t.waitUntil?`, next step ${X(t.waitUntil)}`:"";console.log(`- ${t.subscriberEmail??t.subscriberId}: ${Fbe[t.outcome]??t.outcome} [${t.status}${n}] on step ${t.currentNodeId}`)}}for(let t of e.notEnrolled)console.log(`- ${t.email??t.subscriberId}: not enrolled in this sequence`);for(let t of e.notFound.subscriberIds)console.log(`- ${t}: subscriber not found`);for(let t of e.notFound.emails)console.log(`- ${t}: subscriber not found`)}async function F4(e,t,n){if(!await j())k(M()),process.exit(1);try{let r=Lbe(n,e),o=await E("POST",`/api/v1/sequences/${encodeURIComponent(t)}/enrollments/${e}`,r,n.company);if(n.json){S(o);return}Ube(o)}catch(r){k(r),process.exit(1)}}function L4(e,t){return F4("pause",e,t)}function U4(e,t){return F4("resume",e,t)}var K4="Existing sender profile ID; carries its own address and name. To keep it with a different display name, set fromName inside each email step passed through --steps-json/--steps-file; omit sequence-level --from-email and --from-name.",Y4="Existing sender profile ID; carries its own address and name. To keep it with a different display name, set fromName inside each email step passed through --steps-json/--steps-file or --emails-json/--emails-file; omit sequence-level --from-email and --from-name.";function jbe(e){let t=[];if((e?.migratedRecipientCount??0)>0)t.push(`Recipients moved to the next step: ${e?.migratedRecipientCount}`);if((e?.completedRecipientCount??0)>0)t.push(`Recipients completed: ${e?.completedRecipientCount}`);return t}function zbe(e){let t=e.structuralStepNumber??e.stepNumber;return t!==null?`Step ${t}`:`Node ${e.nodeId}`}function Mbe(e){if(!e?.addedBranchNodeId)return[];let t=[`Branch node: ${e.addedBranchNodeId}`];for(let[n,r]of Object.entries(e.addedBranchPathNodeIds??{}))t.push(` Path ${n}: ${r.length>0?r.join(" -> "):"wired to an existing node"}`);return t}var Hbe=50,j4=10,z4=10,M4=500,Gbe=new Set(["unlimited","one_time","matching_field"]);function Jbe(e){if(!e.id)throw new A("Sequence ID is required",400);if(!e.nodeId?.trim())throw new A("--node is required",400);let t=e.to??[];if(t.length>z4)throw new A(`--to accepts no more than ${z4} email addresses`,400);let n=Array.from(new Set(t.map((o)=>o.trim().toLowerCase()).filter(Boolean)));if(n.length===0)throw new A("--to requires at least one email address",400);let r=n.find((o)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o));if(r)throw new A(`Invalid test recipient: ${r}`,400);return{path:`/api/v1/sequences/${encodeURIComponent(e.id)}/nodes/${encodeURIComponent(e.nodeId.trim())}/test`,body:{recipients:n}}}var Wbe={all:["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],everyday:["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],weekdays:["monday","tuesday","wednesday","thursday","friday"],"working-days":["monday","tuesday","wednesday","thursday","friday"],weekends:["saturday","sunday"]};function H4(e){if(e===void 0)return;if(!Gbe.has(e))throw new A("--enrollment-mode must be one of: unlimited, one_time, matching_field",400);return e}function Vbe(e){if(e===void 0)return;if(!zz(e))throw new A(`--list-scope must be one of: ${P0.join(", ")}`,400);return e}function G4(e,t){if(e===void 0&&t===void 0)return;let n=[],r=new Set;for(let o of[t,...e??[]]){let a=o?.trim();if(!a||r.has(a))continue;r.add(a),n.push(a)}if(n.length===0)throw new A("List and tag values must not be empty",400);return n}function Kbe(e){if(e===void 0)return;let t=[];for(let n of e.split(",")){let r=n.trim().toLowerCase();if(!r)continue;let o=Wbe[r];if(o){for(let a of o)if(!t.includes(a))t.push(a);continue}if(!t.includes(r))t.push(r)}if(t.length===0)throw new A("--sending-window-days must include at least one day",400);return t}function Ybe(e){let t=e.sendingWindowStart!==void 0||e.sendingWindowEnd!==void 0||e.sendingWindowTimezone!==void 0||e.sendingWindowDays!==void 0;if(e.clearSendingWindow&&t)throw new A("Use either --clear-sending-window or --sending-window-* options, not both",400);if(e.clearSendingWindow)return null;if(!t)return;let n=e.sendingWindowStart?.trim(),r=e.sendingWindowEnd?.trim(),o=e.sendingWindowTimezone?.trim();if(!n||!r||!o)throw new A("--sending-window-start, --sending-window-end, and --sending-window-timezone are required together",400);let a=Kbe(e.sendingWindowDays);return{enabled:!0,timezone:o,startTime:n,endTime:r,...a!==void 0&&{days:a}}}function Zbe(e){if(e.sendSpreadHours===void 0)return;let t=e.sendSpreadHours.trim(),n=Number(t);if(t===""||!Number.isFinite(n)||n<0)throw new A("--send-spread-hours must be a number of hours",400);return{spreadOverHours:n}}async function Xbe(e){if(e.sendSpreadHours===void 0||e.clearKeyDates===!0||(e.keyDate??[]).length>0||e.keyDatesJson!==void 0||e.keyDatesFile!==void 0)return e;let n=(await E("GET",`/api/v1/sequences/${e.id}`,void 0,e.company)).sequence?.keyDates;if(!n||n.dates.length===0)throw new A("This sequence has no key dates; add --key-date entries to set a spread",400);return{...e,keyDatesJson:JSON.stringify({timezone:n.timezone,dates:n.dates})}}function eve(e){let t=tve(e),n=Zbe(e);if(n===void 0)return t;if(t===null)throw new A("--send-spread-hours cannot be combined with --clear-key-dates",400);if(t===void 0)throw new A("--send-spread-hours needs key dates: add --key-date entries (or --key-dates-json)",400);return{...t,sendWindow:n}}function tve(e){let t=(e.keyDate??[]).map((c)=>c.trim()).filter((c)=>c.length>0),n=e.keyDatesJson!==void 0||e.keyDatesFile!==void 0,r=t.length>0||n||e.keyDatesTimezone!==void 0;if(e.clearKeyDates&&r)throw new A("Use either --clear-key-dates or --key-date/--key-dates-* options, not both",400);if(e.clearKeyDates)return null;if(!r)return;if(t.length>0&&n)throw new A("Use either --key-date entries or --key-dates-json/--key-dates-file, not both",400);if(n){let c=Oe(e.keyDatesJson,e.keyDatesFile,"key dates");if(c===void 0)throw new A("Key dates JSON is empty",400);let l=Array.isArray(c)?{dates:c}:c;if(!Array.isArray(l.dates))throw new A('Key dates JSON must be an array of { label, at } or an object with "dates"',400);let p=e.keyDatesTimezone?.trim()||l.timezone;return{...p?{timezone:p}:{},dates:l.dates,...l.sendWindow!==void 0&&{sendWindow:l.sendWindow}}}let o=e.keyDatesTimezone?.trim();if(!o)throw new A("--key-dates-timezone is required with --key-date, e.g. --key-dates-timezone America/New_York",400);let a=t.map((c)=>{let l=c.lastIndexOf("=");if(l<=0||l===c.length-1)throw new A(`--key-date must look like "Label=2026-11-27T00:00:00" (got "${c}")`,400);let p=c.slice(0,l).trim(),f=c.slice(l+1).trim(),h=/^([a-z0-9_]+):(.+)$/.exec(p);return h?{key:h[1],label:h[2].trim(),at:f}:{label:p,at:f}});return{timezone:o,dates:a}}function nve(e){let t=e.autoEnrollAll===!0||(e.autoEnrollListIds?.length??0)>0||e.autoEnrollSegmentId!==void 0||e.autoEnrollJson!==void 0;if(e.clearAutoEnroll&&t)throw new A("Use either --clear-auto-enroll or --auto-enroll-* options, not both",400);if(e.clearAutoEnroll)return null;if(!t){if(e.autoEnrollStartsAt!==void 0)throw new A("--auto-enroll-starts-at needs an audience: add --auto-enroll-all, --auto-enroll-list-ids, --auto-enroll-segment-id or --auto-enroll-json",400);return}let n=e.autoEnrollStartsAt?.trim();if(n&&Number.isNaN(Date.parse(n)))throw new A("--auto-enroll-starts-at must be an ISO 8601 date-time, e.g. 2026-11-15T09:00:00Z",400);return{...n?{startsAt:new Date(n).toISOString()}:{},audience:$B({...e.autoEnrollAll?{all:!0}:{},...e.autoEnrollListIds?{listIds:e.autoEnrollListIds}:{},...e.autoEnrollSegmentId?{segmentId:e.autoEnrollSegmentId}:{},...e.autoEnrollJson?{audienceJson:e.autoEnrollJson}:{}})}}function OB(e){if(!e)return"Off";let t=wv(e.audience);if(e.enabled){let n=e.startsAt&&Date.parse(e.startsAt)>Date.now()?` · starts ${X(e.startsAt)}`:"";return`On · ${t}${n} · new joiners are enrolled until the last key date`}return`Off (${e.endedReason==="countdown_ended"?"countdown ended":"switched off"}${e.endedAt?` ${X(e.endedAt)}`:""}) · was ${t}`}function PB(e){if(!e||e.dates.length===0)return"None";let t=e.timezone?` (${e.timezone})`:"",n=e.sendWindow?.spreadOverHours,r=n===void 0?"":n===0?" · sends at the exact moment":` · each email spread over ${n}h`;return e.dates.map((o)=>`${o.label}${o.key?` [${o.key}]`:""} = ${o.at}`).join("; ")+t+r}function rve(e){if(e.respectFrequencyCap&&e.ignoreFrequencyCap)throw new A("Use either --respect-frequency-cap or --ignore-frequency-cap, not both",400);if(e.respectFrequencyCap)return!0;if(e.ignoreFrequencyCap)return!1;return}function ove(e){if(e.activeSubscribersOnly&&e.includeSuppressedSubscribers)throw new A("Use either --active-subscribers-only or --include-suppressed-subscribers, not both",400);if(e.activeSubscribersOnly)return!0;if(e.includeSuppressedSubscribers)return!1;return}function Sv(e){return e?"Respected":"Ignored"}function Dv(e){if(!e)return"Not restricted";return`${e.startTime}-${e.endTime} ${e.timezone} (${(e.days??["every day"]).join(", ")})`}function ive(e){if(e.clearBccEmails&&e.bccEmails!==void 0)throw new A("Use either --clear-bcc-emails or --bcc-emails, not both",400);if(e.clearBccEmails)return null;if(e.bccEmails===void 0)return;let t=Array.from(new Set(e.bccEmails.split(",").map((n)=>n.trim()).filter((n)=>n.length>0)));return t.length>0?t:null}var sve={live:"running",enrollment_paused:"new enrollments paused, existing recipients continue",paused:"recipients frozen, nobody new enters",draft:"not running",archived:"not running"};function kp(e){let t=e.status??"Unknown",n=e.effectiveStatus===void 0?void 0:sve[e.effectiveStatus];if(n!==void 0)return`${t} (${n})`;return e.enrollmentPaused===!0?`${t} (new enrollments paused)`:t}function J4(e){if(e.effectiveStatusSummary!==void 0)console.log(`State: ${e.effectiveStatusSummary}`)}function ave(e){let t=[],n=e.sequenceName??e.sequenceId??"Sequence";if(t.push(`Sequence: ${n}${e.sequenceId?` [${e.sequenceId}]`:""}`),t.push(`Status: ${kp({status:e.status,enrollmentPaused:e.enrollmentPaused,effectiveStatus:e.effectiveStatus})}`),e.effectiveStatusSummary)t.push(`State: ${e.effectiveStatusSummary}`);t.push("Sends mail: no");let r=e.readiness;if(r){t.push(`Ready to activate: ${r.ready===!0?"yes":"no"}`);for(let c of r.errors??[])t.push(` Error: ${c}`);for(let c of r.warnings??[])t.push(` Warning: ${c}`)}let o=e.enrollment;if(o){if(t.push("Enrollment"),o.triggerType)t.push(` Trigger: ${o.triggerType}`);if(o.summary)t.push(` ${o.summary}`);if(o.note)t.push(` ${o.note}`);if(o.error)t.push(` Trigger error: ${o.error}`);if(o.autoEnrollOnActivateCount!==void 0)t.push(` Auto-enroll on activate: ${o.autoEnrollOnActivateCount}`);if(typeof o.currentlyMatchingCount==="number"){let c=o.currentlyMatchingEnrollsAutomatically?"enrolled on the first hourly check":"not enrolled automatically";t.push(` Currently matching: ${o.currentlyMatchingCount} (${c})`)}else if(o.currentlyMatchingAvailable===!1)t.push(" Currently matching: unavailable (evaluated by the hourly worker)");for(let c of o.currentlyMatchingSample??[]){let l=c.email??c.id??"unknown";t.push(c.name?` - ${c.name} <${l}>`:` - ${l}`)}}let a=e.path;if(a){let c=a.subscriber?.email??a.subscriber?.id??"subscriber";if(t.push(`Path for ${c}`),a.emailsOnPath!==void 0){let l=`${a.emailsOnPath} deliverable email${a.emailsOnPath===1?"":"s"}`;if(a.emailStepsOnPath!==void 0&&a.emailStepsOnPath!==a.emailsOnPath)t.push(` ${a.emailStepsOnPath} email step${a.emailStepsOnPath===1?"":"s"} on this path; ${l}`);else t.push(` ${l} on this path`)}for(let l of a.steps??[]){let p=l.label??l.nodeType??l.nodeId??"step",f=l.outcome;if(f){let h=f.assumed?" (assumed)":"",b=f.branchId?` [${f.branchId}]`:"";t.push(` ${p}: ${f.verdict??"unknown"}${b}${h} - ${f.reason??""}`)}else t.push(` ${p}`)}if(a.truncated)t.push(" Path truncated")}return t}function FB(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t!=="visual"&&t!=="plain")throw new A("--email-style must be 'visual' or 'plain'",400);return t}function W4(e){if(e===void 0)return;if(e!=="sequence_created_at"&&e!=="subscriber_created_at")throw new A("--inactivity-baseline must be 'sequence_created_at' or 'subscriber_created_at'",400);return e}function V4(e){let t=Vbe(e.listScope),n=G4(e.listIds,e.listId),r=G4(e.tagNames,e.tagName);if(t!==void 0&&n!==void 0)throw new A("Provide either --list-id/--list-ids or --list-scope, not both",400);if(t!==void 0&&e.trigger!==void 0&&e.trigger!=="contact_added")throw new A("--list-scope only applies to a contact_added trigger",400);if(e.pauseNewEnrollments&&e.resumeNewEnrollments)throw new A("Provide either --pause-new-enrollments or --resume-new-enrollments, not both",400);if(e.userCancellable&&e.notUserCancellable)throw new A("Provide either --user-cancellable or --not-user-cancellable, not both",400);if(e.clearLabels&&e.label!==void 0)throw new A("Provide either --label or --clear-labels, not both",400);if((e.branchJson!==void 0||e.branchFile!==void 0)&&(e.insertStepsJson!==void 0||e.insertStepsFile!==void 0))throw new A("Provide either --branch-json/--branch-file or --insert-steps-json/--insert-steps-file, not both",400);let o=[e.branchJson!==void 0||e.branchFile!==void 0,e.insertStepsJson!==void 0||e.insertStepsFile!==void 0,e.graphEditJson!==void 0||e.graphEditFile!==void 0].filter(Boolean).length;if(o>1)throw new A("Provide only one of --branch-*, --insert-steps-*, or --graph-edit-*",400);if((e.nodeUpdatesJson!==void 0||e.nodeUpdatesFile!==void 0)&&(e.stepsJson!==void 0||e.stepsFile!==void 0||e.emailsJson!==void 0||e.emailsFile!==void 0||e.smsStepsJson!==void 0||e.smsStepsFile!==void 0||e.subscriberUpdateStepsJson!==void 0||e.subscriberUpdateStepsFile!==void 0||o>0))throw new A("--node-updates-* cannot be combined with legacy step updates or structural graph changes",400);let a=Ybe(e),c=rve(e),l=ove(e),p=eve(e),f=nve(e),h=ive(e);return{...e.name!==void 0&&{name:e.name},...e.description!==void 0&&{description:e.description},...e.label!==void 0&&{labels:e.label},...e.clearLabels===!0&&{labels:[]},...e.userCancellable===!0&&{userCancellable:!0},...e.notUserCancellable===!0&&{userCancellable:!1},...e.trigger!==void 0&&{trigger:e.trigger},...e.goal!==void 0&&e.goal.trim().length>0&&{goal:e.goal.trim()},...ot(e.emailCount,"--email-count")!==void 0&&{emailCount:ot(e.emailCount,"--email-count")},...ot(e.durationDays,"--duration-days")!==void 0&&{durationDays:ot(e.durationDays,"--duration-days")},...FB(e.emailStyle)!==void 0&&{emailStyle:FB(e.emailStyle)},...e.pauseNewEnrollments===!0&&{enrollmentPaused:!0},...e.resumeNewEnrollments===!0&&{enrollmentPaused:!1},...e.confirmStructuralChange===!0&&{confirmStructuralChange:!0},...e.confirmLiveChange===!0&&{confirmLiveChange:!0},...f!==void 0&&{audienceAutoEnroll:f},...H4(e.enrollmentMode)!==void 0&&{enrollmentMode:H4(e.enrollmentMode)},...e.enrollmentFieldPath!==void 0&&{enrollmentFieldPath:e.enrollmentFieldPath},...a!==void 0&&{sendingWindow:a},...c!==void 0&&{frequencyCapEnabled:c},...l!==void 0&&{activeSubscribersOnly:l},...p!==void 0&&{keyDates:p},...h!==void 0&&{bccEmails:h},...n!==void 0&&{listId:n[0],listIds:n},...t!==void 0&&{listScope:t},...r!==void 0&&{tagName:r[0],tagNames:r},...e.segmentId!==void 0&&{segmentId:e.segmentId},...e.stopOnSegmentExit!==void 0&&{stopOnSegmentExit:e.stopOnSegmentExit},...e.eventName!==void 0&&{eventName:e.eventName},...e.integrationSlug!==void 0&&{integrationSlug:e.integrationSlug},...e.integrationEventKey!==void 0&&{integrationEventKey:e.integrationEventKey},...Oe(e.customIntegrationJson,e.customIntegrationFile,"customIntegration")!==void 0&&{customIntegration:Oe(e.customIntegrationJson,e.customIntegrationFile,"customIntegration")},...Oe(e.propertyFiltersJson,e.propertyFiltersFile,"propertyFilters")!==void 0&&{propertyFilters:Oe(e.propertyFiltersJson,e.propertyFiltersFile,"propertyFilters")},...ot(e.inactiveDays,"--inactive-days")!==void 0&&{inactiveDays:ot(e.inactiveDays,"--inactive-days")},...W4(e.inactivityBaseline)!==void 0&&{inactivityBaseline:W4(e.inactivityBaseline)},...ot(e.minCount,"--min-count")!==void 0&&{minCount:ot(e.minCount,"--min-count")},...ot(e.timeWindowDays,"--time-window-days")!==void 0&&{timeWindowDays:ot(e.timeWindowDays,"--time-window-days")},...Oe(e.stepsJson,e.stepsFile,"steps")!==void 0&&{steps:Oe(e.stepsJson,e.stepsFile,"steps")},...Oe(e.emailsJson,e.emailsFile,"emails")!==void 0&&{emails:Oe(e.emailsJson,e.emailsFile,"emails")},...Oe(e.smsStepsJson,e.smsStepsFile,"smsSteps")!==void 0&&{smsSteps:Oe(e.smsStepsJson,e.smsStepsFile,"smsSteps")},...Oe(e.subscriberUpdateStepsJson,e.subscriberUpdateStepsFile,"subscriberUpdateSteps")!==void 0&&{subscriberUpdateSteps:Oe(e.subscriberUpdateStepsJson,e.subscriberUpdateStepsFile,"subscriberUpdateSteps")},...Oe(e.branchJson,e.branchFile,"branch")!==void 0&&{branch:Oe(e.branchJson,e.branchFile,"branch")},...Oe(e.insertStepsJson,e.insertStepsFile,"insertSteps")!==void 0&&{insertSteps:Oe(e.insertStepsJson,e.insertStepsFile,"insertSteps")},...Oe(e.nodeUpdatesJson,e.nodeUpdatesFile,"nodeUpdates")!==void 0&&{nodeUpdates:Oe(e.nodeUpdatesJson,e.nodeUpdatesFile,"nodeUpdates")},...Oe(e.graphEditJson,e.graphEditFile,"graphEdit")!==void 0&&{graphEdit:Oe(e.graphEditJson,e.graphEditFile,"graphEdit")},...Oe(e.stopConditionJson,e.stopConditionFile,"stopCondition")!==void 0&&{stopCondition:Oe(e.stopConditionJson,e.stopConditionFile,"stopCondition")},...e.fromEmail!==void 0&&{fromEmail:e.fromEmail},...e.fromName!==void 0&&{fromName:e.fromName},...e.senderProfileId!==void 0&&{senderProfileId:e.senderProfileId},...e.replyTo!==void 0&&{replyTo:e.replyTo},...e.replyToName!==void 0&&{replyToName:e.replyToName},...e.replyProfileId!==void 0&&{replyProfileId:e.replyProfileId}}}function cve(e){return Array.from(new Set((e??"").split(",").map((t)=>t.trim()).filter((t)=>t.length>0)))}function lve(e){let t=(a)=>Array.from(new Set((a??[]).map((c)=>c.trim()).filter((c)=>c.length>0))),n=t(e.nodeIds),r=t(e.subscriberIds),o=e.cursor?.trim();return{...e.nodeIds!==void 0&&{nodeIds:n},...e.subscriberIds!==void 0&&{subscriberIds:r},...o&&{cursor:o},dryRun:e.apply!==!0}}function ug(e){if(/^[A-Za-z0-9_./:@+-]+$/.test(e))return e;return`'${e.replaceAll("'",`'"'"'`)}'`}function qB(e){let t=["sequenzy","sequences","realign-enrollments",ug(e.id)],n=(r,o)=>{let a=(o??[]).map((c)=>c.trim()).filter((c)=>c.length>0);if(a.length>0)t.push(r,...a.map(ug))};if(n("--node-ids",e.nodeIds),n("--subscriber-ids",e.subscriberIds),"jobId"in e&&e.jobId)t.push("--job-id",ug(e.jobId));else if("cursor"in e&&e.cursor){if(t.push("--cursor",ug(e.cursor)),e.apply)t.push("--apply")}if(e.company)t.push("--company",ug(e.company));return t.join(" ")}function uve(e){let t=e.subscriberId?.trim(),n=Array.from(new Set((e.subscriberIds??[]).map((c)=>c.trim()).filter((c)=>c.length>0))),r=cve(e.fieldValues),o=e.all===!0;if((t!==void 0&&t.length>0?1:0)+(n.length>0?1:0)+(r.length>0?1:0)+(o?1:0)!==1)throw new A("Provide exactly one target: --all, --subscriber-id, --subscriber-ids, or --field-values",400);return{...o&&{cancelAll:!0},...t!==void 0&&t.length>0&&{subscriberId:t},...n.length>0&&{subscriberIds:n},...e.fieldPath!==void 0&&e.fieldPath.trim().length>0&&{fieldPath:e.fieldPath.trim()},...r.length>0&&{fieldValues:r},dryRun:e.apply!==!0,...e.reason!==void 0&&e.reason.trim().length>0&&{reason:e.reason.trim()}}}function dve(e){let n=Array.isArray(e.email)&&e.email.length>0||e.emailsJson!==void 0||e.emailsFile!==void 0?op(e):[],r=Array.from(new Set((e.subscriberIds??[]).map((o)=>o.trim()).filter((o)=>o.length>0)));if(n.length===0&&r.length===0)throw new A("Provide at least one email address or subscriber ID",400);return{...n.length>0&&{emails:n},...r.length>0&&{subscriberIds:r},...e.targetNodeId!==void 0&&{targetNodeId:e.targetNodeId}}}function pve(e){let t=[],n=e.emails??[],r=e.subscriberIds??[],o=0,a=0;while(o<n.length||a<r.length){let c=n.slice(o,o+M4);o+=c.length;let l=M4-c.length,p=r.slice(a,a+l);a+=p.length,t.push({...c.length>0&&{emails:c},...p.length>0&&{subscriberIds:p},...e.targetNodeId!==void 0&&{targetNodeId:e.targetNodeId}})}return t}function mve(e){let t=e.goal?.trim(),n=!!t,r=!!e.stepsJson||!!e.stepsFile;if(n&&r)throw new A("Provide either --goal or --steps-json/--steps-file, not both",400);if(e.emailCount!==void 0&&!n)throw new A("--email-count requires --goal",400);if(e.durationDays!==void 0&&!n)throw new A("--duration-days requires --goal",400);if(e.emailStyle!==void 0&&!n)throw new A("--email-style requires --goal",400);FB(e.emailStyle);let o=ot(e.emailCount,"--email-count");if(o!==void 0&&o>j4)throw new A(`--email-count must be no more than ${j4}`,400);let a=ot(e.durationDays,"--duration-days");if(a!==void 0&&a<1)throw new A("--duration-days must be at least 1",400);return n?{mode:"goal",goal:t}:r?{mode:"steps"}:{mode:"blank"}}function fve(e){if(e.isActive&&e.notActive)throw new A("Provide either --active or --inactive, not both",400);return{...e.name!==void 0&&{name:e.name},...e.description!==void 0&&{description:e.description},...e.triggerType!==void 0&&{triggerType:e.triggerType},...e.triggerEventName!==void 0&&{triggerEventName:e.triggerEventName},...e.triggerTagName!==void 0&&{triggerTagName:e.triggerTagName},...e.attributePath!==void 0&&{attributePath:e.attributePath},...e.attributeCondition!==void 0&&{attributeCondition:e.attributeCondition},...e.attributeValue!==void 0&&{attributeValue:e.attributeValue},...e.attributePreviousValue!==void 0&&{attributePreviousValue:e.attributePreviousValue},...e.eventPropertyName!==void 0&&{eventPropertyName:e.eventPropertyName},...e.eventPropertyLabel!==void 0&&{eventPropertyLabel:e.eventPropertyLabel},...ot(e.attributionWindowHours,"--attribution-window-hours")!==void 0&&{attributionWindowHours:ot(e.attributionWindowHours,"--attribution-window-hours")},...e.isActive&&{isActive:!0},...e.notActive&&{isActive:!1}}}function gve(e){let t=Oe(e.fieldMappingJson,e.fieldMappingFile,"fieldMapping"),n=Oe(e.samplePayloadJson,e.samplePayloadFile,"samplePayload");if(e.clearFieldMapping&&t!==void 0)throw new A("Provide either --field-mapping-json/--field-mapping-file or --clear-field-mapping, not both",400);if(e.clearSamplePayload&&n!==void 0)throw new A("Provide either --sample-payload-json/--sample-payload-file or --clear-sample-payload, not both",400);if(t!==void 0&&(typeof t.email!=="string"||!t.email.trim()))throw new A("fieldMapping.email is required",400);return{...e.clearFieldMapping?{fieldMapping:null}:t!==void 0?{fieldMapping:t}:{},...e.clearSamplePayload?{samplePayload:null}:n!==void 0?{samplePayload:n}:{}}}async function Cn(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="list"){let c=new URLSearchParams;if(t.status)c.set("status",t.status);if(t.search)c.set("search",t.search);if(t.label?.length)c.set("labels",t.label.join(","));if(t.limit)c.set("limit",t.limit);if(t.offset)c.set("offset",t.offset);let l=c.size>0?`?${c.toString()}`:"",p=await E("GET",`/api/v1/sequences${l}`,void 0,t.company),f=await Gt(t.company),h=f!==void 0?ct({companyId:f}):void 0,b=p.sequences.map((C)=>f!==void 0?Ds(C,{sequenceId:C.id},"sequence",f):{...C,url:void 0});if(t.json){S({...p,sequences:b,...h!==void 0&&{appUrls:h.urls}});return}let v=p.pagination;console.log(v?`Sequences (${p.sequences.length} of ${v.total})`:`Sequences (${p.sequences.length})`);for(let C of b){if(console.log(`- ${C.name} [${C.id}]`),console.log(` Status: ${kp(C)}`),console.log(` Trigger: ${C.trigger??"Unknown"}`),C.emailCount!==void 0)console.log(` Emails: ${C.emailCount}`);if(console.log(` Sending window: ${Dv(C.sendingWindow)}`),C.frequencyCapEnabled!==void 0)console.log(` Frequency cap: ${Sv(C.frequencyCapEnabled)}`);console.log(` Created: ${X(C.createdAt)}`),Ce(" URL",C.url)}if(v?.hasMore)console.log(`More sequences available. Re-run with --offset ${v.offset+v.count} to fetch the next page.`);return}if(e==="create"){if(!t.name)throw new A("Sequence name is required",400);let c=mve(t),l=await E("POST","/api/v1/sequences",V4({...t,...c.goal!==void 0&&{goal:c.goal}}),t.company),p=await Gt(t.company),f=l.sequence?.id??l.sequenceId,h=p!==void 0&&f!==void 0?ct({companyId:p,sequenceId:f}):void 0;if(t.json){S({...l,...l.sequence!==void 0&&h?.urls.sequence!==void 0&&{sequence:{...l.sequence,url:h.urls.sequence}},...h!==void 0&&{appUrls:h.urls}});return}if(xn(l),console.log(`Created sequence: ${l.sequence?.name??t.name}`),console.log(`ID: ${l.sequence?.id??"Unknown"}`),Ce("URL",h?.urls.sequence),console.log(`Status: ${kp(l.sequence??{})}`),l.sequence?.emailCount!==void 0)console.log(`Emails: ${l.sequence.emailCount}`);if(l.sequence?.discountCount!==void 0)console.log(`Discount actions: ${l.sequence.discountCount}`);if("sendingWindow"in(l.sequence??{}))console.log(`Sending window: ${Dv(l.sequence?.sendingWindow)}`);if("frequencyCapEnabled"in(l.sequence??{}))console.log(`Frequency cap: ${Sv(l.sequence?.frequencyCapEnabled)}`);if("keyDates"in(l.sequence??{}))console.log(`Key dates: ${PB(l.sequence?.keyDates)}`);if("audienceAutoEnroll"in(l.sequence??{}))console.log(`Auto-enroll: ${OB(l.sequence?.audienceAutoEnroll)}`);if(c.mode==="goal")console.log("Mode: AI-generated");if(l.message)console.log(l.message);return}if(!t.id)throw new A("Sequence ID is required",400);if(e==="test"){let c=Jbe(t),l=await E("POST",c.path,c.body,t.company),p=await Gt(t.company),f=p!==void 0?ct({companyId:p,sequenceId:t.id}):void 0;if(t.json){S({...l,...f!==void 0&&{appUrls:f.urls}});return}console.log(l.message??`Queued ${l.results.length} sequence step test email${l.results.length===1?"":"s"}`);for(let h of l.results)console.log(`- ${h.recipientEmail}: email send ${h.emailSendId}`);Ce("URL",f?.urls.sequence);return}if(e==="goals"){let c=await E("GET",`/api/v1/sequences/${t.id}/goals`,void 0,t.company);if(t.json)return S(c);let l=Array.isArray(c.goals)?c.goals:[];console.log(`Sequence goals (${l.length})`);for(let p of l){if(typeof p!=="object"||p===null)continue;let f=p;console.log(`- ${String(f.name??"Unnamed goal")} [${String(f.id??"unknown")}]`)}return}if(e==="goal-create"||e==="goal-update"){if(e==="goal-create"&&!t.name)throw new A("Goal name is required",400);if(e==="goal-update"&&!t.goalId)throw new A("Goal ID is required",400);let c=await E(e==="goal-create"?"POST":"PATCH",`/api/v1/sequences/${t.id}/goals${t.goalId?`/${t.goalId}`:""}`,fve(t),t.company);if(t.json)return S(c);let l=c.goal;if(console.log(`${e==="goal-create"?"Created":"Updated"} sequence goal: ${String(l?.name??t.name??t.goalId)}`),l?.id)console.log(`ID: ${String(l.id)}`);return}if(e==="goal-delete"){if(!t.goalId)throw new A("Goal ID is required",400);let c=await E("DELETE",`/api/v1/sequences/${t.id}/goals/${t.goalId}`,void 0,t.company);if(t.json)return S(c);console.log(`Deleted sequence goal: ${t.goalId}`);return}if(e==="webhook-get"||e==="webhook-configure"||e==="webhook-rotate"){let c=e==="webhook-configure",l=e==="webhook-rotate",p=await E(l?"POST":c?"PUT":"GET",`/api/v1/sequences/${t.id}/inbound-webhook${l?"/rotate-secret":""}`,c?gve(t):void 0,t.company);if(t.json)return S(p);let f=p.webhook;if(console.log(`${l?"Rotated":c?"Configured":"Sequence"} inbound webhook: ${String(f?.status??"Unknown status")}`),f?.url)console.log(`URL: ${String(f.url)}`);return}if(e==="update"){if(t.name===void 0&&t.description===void 0&&t.label===void 0&&t.clearLabels!==!0&&t.userCancellable!==!0&&t.notUserCancellable!==!0&&t.trigger===void 0&&t.fromEmail===void 0&&t.fromName===void 0&&t.senderProfileId===void 0&&t.replyTo===void 0&&t.replyToName===void 0&&t.replyProfileId===void 0&&t.enrollmentMode===void 0&&t.enrollmentFieldPath===void 0&&t.pauseNewEnrollments!==!0&&t.resumeNewEnrollments!==!0&&t.sendingWindowStart===void 0&&t.sendingWindowEnd===void 0&&t.sendingWindowTimezone===void 0&&t.sendingWindowDays===void 0&&t.clearSendingWindow!==!0&&t.respectFrequencyCap!==!0&&t.ignoreFrequencyCap!==!0&&t.activeSubscribersOnly!==!0&&t.includeSuppressedSubscribers!==!0&&t.keyDate===void 0&&t.keyDatesJson===void 0&&t.keyDatesFile===void 0&&t.keyDatesTimezone===void 0&&t.clearKeyDates!==!0&&t.sendSpreadHours===void 0&&t.autoEnrollAll!==!0&&t.autoEnrollListIds===void 0&&t.autoEnrollSegmentId===void 0&&t.autoEnrollJson===void 0&&t.autoEnrollStartsAt===void 0&&t.clearAutoEnroll!==!0&&t.bccEmails===void 0&&t.clearBccEmails!==!0&&!t.stepsJson&&!t.stepsFile&&!t.emailsJson&&!t.emailsFile&&!t.smsStepsJson&&!t.smsStepsFile&&!t.subscriberUpdateStepsJson&&!t.subscriberUpdateStepsFile&&!t.branchJson&&!t.branchFile&&!t.insertStepsJson&&!t.insertStepsFile&&!t.nodeUpdatesJson&&!t.nodeUpdatesFile&&!t.graphEditJson&&!t.graphEditFile&&!t.stopConditionJson&&!t.stopConditionFile)throw new A("Provide at least one sequence metadata, identity, settings, step, nodeUpdates, or graphEdit option",400);let c=await E("PUT",`/api/v1/sequences/${t.id}`,V4(await Xbe(t)),t.company),l=await Gt(t.company),p=l!==void 0?ct({companyId:l,sequenceId:t.id}):void 0;if(t.json){S({...c,...c.sequence!==void 0&&p?.urls.sequence!==void 0&&{sequence:{...c.sequence,url:p.urls.sequence}},...p!==void 0&&{appUrls:p.urls}});return}xn(c),console.log(`Updated sequence: ${c.sequence?.name??t.id}`),console.log(`ID: ${c.sequence?.id??t.id}`),Ce("URL",p?.urls.sequence),console.log(`Status: ${kp(c.sequence??{})}`);for(let f of jbe(c.sequence))console.log(f);for(let f of Mbe(c.sequence))console.log(f);if("sendingWindow"in(c.sequence??{}))console.log(`Sending window: ${Dv(c.sequence?.sendingWindow)}`);if("frequencyCapEnabled"in(c.sequence??{}))console.log(`Frequency cap: ${Sv(c.sequence?.frequencyCapEnabled)}`);if("keyDates"in(c.sequence??{}))console.log(`Key dates: ${PB(c.sequence?.keyDates)}`);if("audienceAutoEnroll"in(c.sequence??{}))console.log(`Auto-enroll: ${OB(c.sequence?.audienceAutoEnroll)}`);if("bccEmails"in(c.sequence??{}))console.log(`BCC: ${c.sequence?.bccEmails?.join(", ")||"None"}`);return}if(e==="pause-enrollments"||e==="resume-enrollments"){let c=await E("POST",`/api/v1/sequences/${t.id}/${e}`,void 0,t.company),l=await Gt(t.company),p=l!==void 0?ct({companyId:l,sequenceId:t.id}):void 0;if(t.json){S({...c,...p!==void 0&&{appUrls:p.urls}});return}console.log(c.message??`Updated sequence ${t.id}`),J4(c),Ce("URL",p?.urls.sequence);return}if(e==="duplicate"){let c=await E("POST",`/api/v1/sequences/${t.id}/duplicate`,t.name===void 0?void 0:{name:t.name},t.company),l=c.sequence?.id??c.sequenceId,p=await Gt(t.company),f=p!==void 0&&l!==void 0?ct({companyId:p,sequenceId:l}):void 0;if(t.json){S({...c,...f!==void 0&&{appUrls:f.urls}});return}if(console.log(`Duplicated sequence: ${c.sequence?.name??l??t.id}`),l)console.log(`ID: ${l}`);console.log(`Status: ${kp(c.sequence??{})}`),Ce("URL",f?.urls.sequence);return}if(e==="archive"||e==="unarchive"){let c=await E("POST",`/api/v1/sequences/${t.id}/${e}`,void 0,t.company);if(t.json){S(c);return}console.log(`${e==="archive"?"Archived":"Restored"} sequence: ${c.sequence?.name??t.id}`);return}if(e==="test-run"||e==="test-run-get"){let c;if(e==="test-run"){if(!t.subscriber?.trim())throw new A("Pass --subscriber for a live sequence test",400);let p=Oe(t.eventProperties,void 0,"event-properties");if(p!==void 0&&(p===null||typeof p!=="object"||Array.isArray(p)))throw new A("--event-properties must be a JSON object",400);let f=t.speedMultiplier===void 0?120:Number(t.speedMultiplier);if(!Number.isInteger(f)||f<60||f>1e4)throw new A("--speed-multiplier must be an integer between 60 and 10000",400);c={subscriberId:t.subscriber.trim(),speedMultiplier:f,...p!==void 0?{customVariables:p}:{}}}else if(!t.runId)throw new A("Pass a test run ID",400);let l=await E(e==="test-run"?"POST":"GET",`/api/v1/sequences/${encodeURIComponent(t.id??"")}/test-runs${e==="test-run-get"?`/${encodeURIComponent(t.runId??"")}`:""}`,c,t.company);if(t.json)S(l);else{if(console.log(`Sequence test ${l.run.id}: ${l.run.status}`),l.run.errorMessage)console.log(l.run.errorMessage);if(e==="test-run")console.log(`Inspect: sequenzy sequences test-run-get ${t.id} ${l.run.id}${t.company?` --company ${t.company}`:""} --json`)}return}if(e==="simulate"){let c=t.subscriber?.trim(),l=t.simulateEmail?.trim();if(c&&l)throw new A("Pass --subscriber or --email, not both",400);let p=new URLSearchParams;if(c)p.set("subscriberId",c);if(l)p.set("email",l);if(t.limit)p.set("limit",t.limit);let f=p.size>0?`?${p.toString()}`:"",h=await E("GET",`/api/v1/sequences/${t.id}/simulate${f}`,void 0,t.company),b=await Gt(t.company),v=b!==void 0?ct({companyId:b,sequenceId:t.id}):void 0;if(t.json){S({...h,...v!==void 0&&{appUrls:v.urls}});return}for(let C of ave(h))console.log(C);Ce("URL",v?.urls.sequence);return}if(e==="enable"||e==="disable"){let c=await E("POST",`/api/v1/sequences/${t.id}/${e}`,void 0,t.company),l=await Gt(t.company),p=l!==void 0?ct({companyId:l,sequenceId:t.id}):void 0;if(t.json){S({...c,...p!==void 0&&{appUrls:p.urls}});return}xn(c),console.log(c.message??`${e}d sequence ${t.id}`),J4(c),Ce("URL",p?.urls.sequence);return}if(e==="enroll"){let c=dve(t),l=pve(c),p=0,f=0,h=[],b,v;for(let C of l){let R=await E("POST",`/api/v1/sequences/${t.id}/enroll`,C,t.company);p+=R.enrolled,f+=R.skipped,h.push(...R.notFound),b??=R.targetNodeId,v??=R.scheduledFor}if(t.json){S({success:!0,sequenceId:t.id,enrolled:p,skipped:f,notFound:h,...b!==void 0&&{targetNodeId:b},...v!==void 0&&{scheduledFor:v}});return}if(console.log(`Enrolled ${p} subscriber(s) in sequence: ${t.id}`),console.log(`Skipped (already enrolled, inactive, or unavailable): ${f}`),h.length>0){console.log(`Not found: ${h.length}`);for(let C of h.slice(0,10))console.log(`- ${C}`);if(h.length>10)console.log(`...and ${h.length-10} more`)}if(b!==void 0)console.log(`Target node: ${b}`);if(v!==void 0)console.log(`Scheduled for: ${X(v)}`);return}if(e==="realign-enrollments"){let c=await Gt(t.company),l=c!==void 0?ct({companyId:c,sequenceId:t.id}):void 0,p;if(t.jobId){let f=await E("GET",`/api/v1/sequences/${t.id}/enrollments/realign-sending-window/jobs/${encodeURIComponent(t.jobId)}`,void 0,t.company);if(t.json){S({...f,...l!==void 0&&{appUrls:l.urls}});return}if(!f.result){if(console.log(f.message??`Enrollment realignment is ${f.status}.`),f.status!=="failed")console.log(`Check again: ${qB({id:t.id,nodeIds:t.nodeIds,subscriberIds:t.subscriberIds,company:t.company,jobId:f.jobId})}`);Ce("URL",l?.urls.sequence);return}p=f.result}else{let f=lve(t),h=await E("POST",`/api/v1/sequences/${t.id}/enrollments/realign-sending-window`,f,t.company);if("status"in h){if(t.json){S({...h,...l!==void 0&&{appUrls:l.urls}});return}console.log(h.message??"Enrollment realignment queued."),console.log(`Job ID: ${h.jobId}`),console.log(`Check status: ${qB({id:t.id,nodeIds:t.nodeIds,subscriberIds:t.subscriberIds,company:t.company,jobId:h.jobId})}`),Ce("URL",l?.urls.sequence);return}p=h}if(t.json){S({...p,...l!==void 0&&{appUrls:l.urls}});return}if(console.log(p.message??"Sequence enrollment realignment complete"),p.sendingWindow){let f=p.sendingWindow;console.log(`Sending window: ${f.days.join(", ")} ${f.startTime}-${f.endTime} ${f.timezone}`)}else console.log("Sending window: none set on the sequence (per-step weekday gates only)");console.log(`Checked: ${p.scannedCount}`),console.log(`${p.dryRun?"Would realign":"Realigned"}: ${p.realignedCount}`),console.log(`Left as-is: ${p.unchangedCount}`);for(let[f,h]of Object.entries(p.unchangedReasons??{}))console.log(` ${f}: ${h}`);if(console.log(`Dry run: ${p.dryRun?"yes":"no"}`),p.requeueFailedCount>0)console.log(`Re-queue deferred to the sweeper: ${p.requeueFailedCount}`);if(p.changes.length>0){console.log(`Enrollments (first ${p.changes.length} of ${p.realignedCount}):`);for(let f of p.changes)console.log(`- ${f.subscriberEmail??f.subscriberId} | ${X(f.waitUntil)} -> ${X(f.newWaitUntil)} (${f.movedEarlierMinutes} min earlier)`)}if(p.dryRun&&p.realignedCount>0)console.log("Re-run with --apply to move these enrollments.");if(p.hasMore)console.log(p.nextCursor?`More enrollments remain. Continue with: ${qB({id:t.id,nodeIds:t.nodeIds,subscriberIds:t.subscriberIds,company:t.company,cursor:p.nextCursor,apply:!p.dryRun})}`:"More enrollments remain. Re-run the command to continue.");Ce("URL",l?.urls.sequence);return}if(e==="cancel-enrollments"){let c=uve(t),l=`/api/v1/sequences/${t.id}/enrollments/cancel`,p=await E("POST",l,c,t.company),f=p.matchedCount,h=p.cancelledCount,b=1;while(!p.dryRun&&(p.remainingCount??0)>0&&p.cancelledCount>0&&b<Hbe){if(!t.json)console.log(`Cancelled ${h} so far, ${p.remainingCount} remaining...`);p=await E("POST",l,c,t.company),h+=p.cancelledCount,b+=1}let v=p.remainingCount??0,C=b===1?p.message??"Sequence enrollment cancellation done":`Cancelled ${h} sequence enrollment${h===1?"":"s"} across ${b} requests.${v>0?` ${v} still match; re-run the same command to continue.`:""}`,R=await Gt(t.company),N=R!==void 0?ct({companyId:R,sequenceId:t.id}):void 0;if(t.json){S({...p,matchedCount:f,cancelledCount:h,message:C,requests:b,...N!==void 0&&{appUrls:N.urls}});return}if(console.log(C),console.log(`Matched: ${f}`),console.log(`Cancelled: ${h}`),console.log(`Remaining: ${v}`),console.log(`Dry run: ${p.dryRun?"yes":"no"}`),v>0&&!p.dryRun)console.log("Stopped before draining every enrollment. Re-run the same command to continue.");if((p.target?.notFoundSubscriberIds?.length??0)>0)console.log(`Subscriber IDs not found: ${p.target?.notFoundSubscriberIds?.join(", ")}`);if(p.hasMore)console.log("Only the first matching enrollments are shown.");if((p.enrollments?.length??0)>0){console.log("Enrollments:");for(let L of p.enrollments??[])console.log(`- ${L.tokenId} | ${L.subscriberEmail??L.subscriberId} [${L.status}]`)}Ce("URL",N?.urls.sequence);return}if(e==="delete"){let c=await E("DELETE",`/api/v1/sequences/${t.id}`,void 0,t.company);if(t.json){S(c);return}console.log(c.message??`Deleted sequence ${t.id}`);return}let n=await E("GET",`/api/v1/sequences/${t.id}`,void 0,t.company),r=await Gt(t.company),o=r!==void 0?ct({companyId:r,sequenceId:t.id}):void 0;if(t.json){S({...n,...o?.urls.sequence!==void 0&&{sequence:{...n.sequence,url:o.urls.sequence}},...o!==void 0&&{appUrls:o.urls}});return}let a=n.sequence;if(console.log(a.name),console.log(`ID: ${a.id}`),Ce("URL",o?.urls.sequence),console.log(`Status: ${kp(a)}`),console.log(`Trigger: ${a.trigger??"Unknown"}`),console.log(`Sending window: ${Dv(a.sendingWindow)}`),a.frequencyCapEnabled!==void 0)console.log(`Frequency cap: ${Sv(a.frequencyCapEnabled)}`);if(a.activeSubscribersOnly!==void 0)console.log(`Enrolls: ${a.activeSubscribersOnly?"active subscribers only":"all statuses (marketing emails skipped for unsubscribed and bounced)"}`);if(console.log(`Key dates: ${PB(a.keyDates)}`),a.audienceAutoEnroll)console.log(`Auto-enroll: ${OB(a.audienceAutoEnroll)}`);if(console.log(`BCC: ${a.bccEmails?.join(", ")||"None"}`),console.log(`Created: ${X(a.createdAt)}`),console.log(`Enrichment: ${a.enrichmentStatus} (${a.enrichedCount}/${a.emailCount})`),a.emails.length>0){console.log("Emails:");for(let c of a.emails){if(console.log(`- ${zbe(c)}`),console.log(` Email ID: ${c.emailId??"None"}`),console.log(` Name: ${c.name??"None"}`),console.log(` Subject: ${c.subject??"None"}`),console.log(` Preview: ${c.previewText??"None"}`),console.log(` Format: ${Cs(c.emailPreset)}`),console.log(` Theme: ${Jz(c.emailTheme)}`),c.attachments&&c.attachments.length>0)console.log(` Attachments: ${c.attachments.map((l)=>`${l.filename} (${l.path})`).join(", ")}`);if(console.log(` Blocks: ${c.blocks.length}`),c.abTest){console.log(` A/B test: ${c.abTest.id??"Unknown"}${c.abTest.status?` (${c.abTest.status})`:""}`);for(let l of c.abTest.variants??[])console.log(` Variant ${l.variantLabel}: ${l.subject??"None"}${l.isWinner?" (winner)":""}`),console.log(` Variant ID: ${l.variantId}`),console.log(` Blocks: ${l.blockCount??0}`);console.log(` ${Py}`)}}}}catch(n){k(n instanceof A?n:n),process.exit(1)}}function yl(e,t,n){if(e===void 0)return;let r=Number(e);if(!Number.isFinite(r)||r<=0)throw new A(`${t} must be a positive number`,400);if(r>n)throw new A(`${t} must be at most ${n}`,400);return r}function Ave(e){let t={};if(e.resetBrowseAbandonment){if(e.browseAbandonment!==void 0||e.browseDelayHours!==void 0||e.browseCooldownHours!==void 0)throw new A("--reset-browse-abandonment cannot be combined with other browse flags",400);t.browseAbandonment=null}else{let n={},r=ui(e.browseAbandonment,"--browse-abandonment");if(r!==void 0)n.enabled=r;let o=yl(e.browseDelayHours,"--browse-delay-hours",hz);if(o!==void 0)n.delayHours=o;let a=yl(e.browseCooldownHours,"--browse-cooldown-hours",yz);if(a!==void 0)n.cooldownHours=a;if(Object.keys(n).length>0)t.browseAbandonment=n}if(e.resetCartAbandonment){if(e.cartAbandonment!==void 0||e.cartDelayHours!==void 0||e.cartCooldownHours!==void 0||e.cartExpireAfterHours!==void 0)throw new A("--reset-cart-abandonment cannot be combined with other cart flags",400);t.cartAbandonment=null}else{let n={},r=ui(e.cartAbandonment,"--cart-abandonment");if(r!==void 0)n.enabled=r;let o=yl(e.cartDelayHours,"--cart-delay-hours",bz);if(o!==void 0)n.delayHours=o;let a=yl(e.cartCooldownHours,"--cart-cooldown-hours",vz);if(a!==void 0)n.cooldownHours=a;let c=yl(e.cartExpireAfterHours,"--cart-expire-after-hours",Ez);if(c!==void 0)n.expireAfterHours=c;if(Object.keys(n).length>0)t.cartAbandonment=n}if(e.resetPriceDrop){if(e.priceDrop!==void 0||e.priceDropMinPercent!==void 0||e.priceDropLookbackDays!==void 0||e.priceDropCooldownDays!==void 0)throw new A("--reset-price-drop cannot be combined with other price-drop flags",400);t.priceDrop=null}else{let n={},r=ui(e.priceDrop,"--price-drop");if(r!==void 0)n.enabled=r;let o=yl(e.priceDropMinPercent,"--price-drop-min-percent",Iz);if(o!==void 0)n.minPercent=o;let a=yl(e.priceDropLookbackDays,"--price-drop-lookback-days",Cz);if(a!==void 0)n.lookbackDays=a;let c=yl(e.priceDropCooldownDays,"--price-drop-cooldown-days",wz);if(c!==void 0)n.cooldownDays=c;if(Object.keys(n).length>0)t.priceDrop=n}if(Object.keys(t).length===0)throw new A("Provide at least one settings flag (see --help for the full list)",400);return t}function Z4(e){let{browseAbandonment:t,cartAbandonment:n,priceDrop:r}=e;if(console.log(`Shopify automation settings (${e.shopDomain})`),console.log(""),console.log(`Browse abandonment: ${t.enabled?"on":"off"}`),console.log(" Emails shoppers who view a product but don't buy, add to cart, or start checkout."),console.log(` Waits ${t.delayHours}h after the view - at most one email per subscriber per ${t.cooldownHours}h`),n)console.log(""),console.log(`Cart abandonment: ${n.enabled?"on":"off"}`),console.log(" Fires ecommerce.cart_abandoned with the full cart after the cart sits untouched with no checkout or order."),console.log(` Waits ${n.delayHours}h of inactivity - at most one per subscriber per ${n.cooldownHours}h`),console.log(` Drops a cart untouched for ${n.expireAfterHours}h instead of emailing about it`);console.log(""),console.log(`Price drop alerts: ${r.enabled?"on":"off"}`),console.log(` Emails recent viewers when a product's price falls by ${r.minPercent}% or more.`),console.log(` Audience: viewers from the last ${r.lookbackDays} days - at most one email per product per subscriber per ${r.cooldownDays} days`)}async function LB(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="get"){let o=await E("GET","/api/v1/shopify/automation-settings",void 0,t.company);if(t.json){S(o);return}Z4(o);return}let n=Ave(t),r=await E("PUT","/api/v1/shopify/automation-settings",n,t.company);if(t.json){S(r);return}if(r.message)console.log(r.message),console.log("");Z4(r)}catch(n){k(n instanceof A?n:n),process.exit(1)}}function hve(e){let{sms:t}=e;if(console.log(`SMS add-on: ${t.enabled?"enabled":"not enabled"}`),console.log(`Plan eligible: ${t.planEligible?"yes":"no"}`),console.log(`Credits balance: ${t.creditsBalance}`),console.log(`Brand prefix: ${t.brandPrefix??"(not set)"}`),t.numbers.length===0)console.log("Numbers: none");else{console.log("Numbers:");for(let n of t.numbers){let r=[n.label,n.brandPrefix?`prefix: ${n.brandPrefix}`:null,n.linkShorteningEnabled===!1?"links sent as written":null].filter(Boolean).join(", ");console.log(` ${n.e164} [${n.id}] (${n.status})${r?` - ${r}`:""}`)}}console.log(),console.log(e.message)}function yve(e){if(e.usage.length===0){console.log("No SMS sends recorded yet.");return}for(let t of e.usage)console.log(t.fromNumber),console.log(` Sends: ${t.totalSends} (delivered: ${t.delivered}, failed: ${t.failed}, test: ${t.testSends})`),console.log(` Credits charged: ${t.creditsCharged}`),console.log(` Last sent: ${t.lastSentAt??"never"}`)}function bve(e){return{to:Rn(e.phone??"","Phone number").trim(),text:Rn(e.text??"","--text").trim(),...e.imageUrl&&e.imageUrl.length>0?{imageUrls:e.imageUrl}:{},...e.fromNumber?.trim()?{fromNumberId:e.fromNumber.trim()}:{}}}function vve(e){return{label:e.label?.trim()||null}}function Eve(e){let t=e.trim().toLowerCase();if(t==="on")return!0;if(t==="off")return!1;throw Error('--link-shortening must be "on" or "off".')}function Ive(e){if(e.label===void 0&&e.brandPrefix===void 0&&e.linkShortening===void 0)throw Error("Provide --label, --brand-prefix, and/or --link-shortening.");return{...e.label!==void 0?{label:e.label.trim()||null}:{},...e.brandPrefix!==void 0?{brandPrefix:e.brandPrefix.trim()||null}:{},...e.linkShortening!==void 0?{linkShorteningEnabled:Eve(e.linkShortening)}:{}}}async function Tu(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="settings"){let n=await E("GET","/api/v1/sms/settings",void 0,t.company);if(t.json){S(n);return}hve(n);return}if(e==="send-test"){let n=await E("POST","/api/v1/sms/test",bve(t),t.company);if(t.json){S(n);return}console.log(n.message);return}if(e==="usage"){let n=await E("GET","/api/v1/sms/usage",void 0,t.company);if(t.json){S(n);return}yve(n);return}if(e==="release"){let n=Rn(t.numberId??"","SMS number ID").trim();if(!await mt(`Release SMS number ${n}? The number is handed back to the carrier and cannot be recovered.`,t)){console.log("Aborted.");return}let r=await E("DELETE",`/api/v1/sms/numbers/${encodeURIComponent(n)}`,void 0,t.company);if(t.json){S(r);return}console.log(r.message);return}if(e==="label"||e==="update"){let n=Rn(t.numberId??"","SMS number ID").trim(),r=await E("PATCH",`/api/v1/sms/numbers/${encodeURIComponent(n)}`,e==="label"?vve(t):Ive(t),t.company);if(t.json){S(r);return}console.log(r.message)}}catch(n){k(n instanceof A?n:n),process.exit(1)}}var Qu=yt(In(),1);var X4=["email","sequence","email_type","mailbox_provider","recipient_domain"],Cve={permanent_bounce:"permanent bounces",temporary_bounce:"temporary bounces",blocked:"blocked sends",complaint:"sends with spam complaints"};function wve(e){if(e.emails||e.clients||e.links)throw new A("--by cannot be combined with --emails, --clients or --links",400);if(e.campaign||e.sequence||e.transactional)throw new A("--by covers the account; narrow it with --source campaign:<id>, sequence:<id> or transactional:<id> instead",400);if(e.by&&!X4.includes(e.by))throw new A(`--by must be one of: ${X4.join(", ")}`,400);let t=new URLSearchParams;for(let[n,r]of[["by",e.by],["period",e.period],["start",e.start],["end",e.end],["emailType",e.emailType],["mailboxProvider",e.mailboxProvider],["recipientDomain",e.recipientDomain],["source",e.source],["outcome",e.outcome],["limit",e.limit]])if(r)t.set(n,r);if(e.includeBots)t.set("includeMachineEngagement","true");return`/api/v1/metrics/breakdown?${t.toString()}`}function Sve(e){if(!e)return"";switch(e.kind){case"source":return`--source ${e.source.type}:${e.source.id}`;case"email_type":return`--email-type ${e.emailType}`;case"mailbox_provider":return`--mailbox-provider ${e.mailboxProvider}`;case"recipient_domain":return`--recipient-domain ${e.recipientDomain}`}}function UB(e){return`${e.toFixed(1)}%`}function Dve(e){let t=e.period&&e.period!=="custom"?e.period:`${e.start??""} - ${e.end??""}`,n=e.outcome?`, only ${Cve[e.outcome]??e.outcome}`:"",r=[`Breakdown by ${e.by.replace("_"," ")} (${t}${n})`];if(e.rows.length===0)return r.push("No emails were sent with these filters in this period."),r;let o=e.rows.some((c)=>c.revenue!==null),a=Math.max(4,...e.rows.map((c)=>c.sent.toLocaleString().length));r.push("",` ${"Sent".padStart(a)} Open Click Bounce${o?" Revenue":""} Name`);for(let c of e.rows){let l=o?` ${(c.revenue===null?"-":`$${Math.round(c.revenue).toLocaleString()}`).padStart(10)}`:"",p=c.detail?` (${c.detail})`:"";r.push(` ${c.sent.toLocaleString().padStart(a)} ${UB(c.openRate).padStart(5)} ${UB(c.clickRate).padStart(5)} ${UB(c.bounceRate).padStart(6)}${l} ${c.label}${p}`);let f=Sve(c.filter);if(f)r.push(` ${"".padStart(a)} drill in: ${f}`)}return r}async function eW(e){let t=await E("GET",wve(e),void 0,e.company);if(e.json){S(t);return}for(let n of Dve(t))console.log(n)}function Bve(e){if(e.emails)throw new A("--clients cannot be combined with --emails",400);if(e.sequence||e.transactional)throw new A("--clients supports account-level stats and --campaign only",400);if(e.campaign&&(e.period||e.start||e.end||e.emailType))throw new A("--clients with --campaign covers the whole campaign; --period, --start, --end, and --email-type apply to account-level stats only",400);let t=new URLSearchParams;if(!e.campaign){for(let[o,a]of[["period",e.period],["start",e.start],["end",e.end],["emailType",e.emailType]])if(a)t.set(o,a)}if(e.mailboxProvider)t.set("mailboxProvider",e.mailboxProvider);if(e.includeBots)t.set("includeMachineEngagement","true");let n=t.toString(),r=e.campaign?`/api/v1/metrics/campaigns/${encodeURIComponent(e.campaign)}/clients`:"/api/v1/metrics/clients";return n?`${r}?${n}`:r}function _ve(e){return`${e.toFixed(e>0&&e<1?1:0)}%`}function xve(e){let n=[`Email clients (${e.campaignId?`campaign ${e.campaignId}`:e.period==="custom"&&e.start&&e.end?`${e.start} - ${e.end}`:e.period??"all time"})`];if(e.totalOpens===0)return n.push("No opens recorded yet."),n;let r=Math.max(...[...e.clients,...e.devices].map((o)=>o.label.length));for(let[o,a]of[["Clients",e.clients],["Devices",e.devices]]){n.push("",`${o}:`);for(let c of a)n.push(` ${c.label.padEnd(r)} ${_ve(c.share).padStart(4)} ${c.opens.toLocaleString()} ${c.opens===1?"open":"opens"}`)}return n.push("",`Based on ${e.totalOpens.toLocaleString()} unique ${e.totalOpens===1?"open":"opens"}; ${e.privacyProxyOpens.toLocaleString()} came through Gmail, Yahoo, or Apple Mail privacy proxies, which hide the device.`),n}async function tW(e){let t=await E("GET",Bve(e),void 0,e.company);if(e.json){S(t);return}for(let n of xve(t))console.log(n)}var nW=["sent","delivered","opened","clicked","openRate","clickRate","unsubscribed","conversions","revenue","step","name"],kve=["step","sort","order","page","limit"];function rW(e){if(e.emails)return;let t=kve.find((n)=>e[n]!==void 0&&!(n==="limit"&&(e.links||e.by)));if(t)throw new A(`--${t} requires --emails`,400)}function Rve(e){if(e.transactional)throw new A("--emails covers campaigns and sequence steps; --transactional is not supported",400);if(e.emailType!==void 0&&!["campaign","sequence"].includes(e.emailType))throw new A("--email-type must be 'campaign' or 'sequence' with --emails",400);if(e.sort!==void 0&&!nW.includes(e.sort))throw new A(`--sort must be one of: ${nW.join(", ")}`,400);if(e.order!==void 0&&!["asc","desc"].includes(e.order))throw new A("--order must be 'asc' or 'desc'",400);if(e.mailboxProvider)throw new A("--mailbox-provider applies to account-level stats and --campaign only",400);if(e.campaign&&(e.sequence||e.step))throw new A("--campaign cannot be combined with --sequence or --step when using --emails",400);let t=new URLSearchParams,n=[["emailType",e.emailType],["sequenceId",e.sequence],["campaignId",e.campaign],["step",e.step],["sort",e.sort],["order",e.order],["page",e.page],["limit",e.limit]];for(let[o,a]of n)if(a!==void 0&&a.trim()!=="")t.set(o,a.trim());if(e.start||e.end){if(e.start)t.set("start",e.start);if(e.end)t.set("end",e.end)}else if(e.period)t.set("period",e.period);if(e.includeBots)t.set("includeMachineEngagement","true");let r=t.toString();return r?`?${r}`:""}async function Tve(e){return E("GET",`/api/v1/metrics/emails${Rve(e)}`,void 0,e.company)}function Qve(e){let t=e.emailType==="sequence"?`${e.sequenceName??"Unknown sequence"}${e.step!==null?` · Step ${e.step}`:""}`:"Campaign",n=`${e.stats.opened.toLocaleString()} opened (${e.stats.openRate.toFixed(1)}%), ${e.stats.clicked.toLocaleString()} clicked (${e.stats.clickRate.toFixed(1)}%)`;return`${e.name} — ${e.stats.sent.toLocaleString()} sent, ${n} [${t}, ${e.emailId}]`}function $ve(e){let{totals:t,pagination:n}=e,r=e.period?e.period==="custom"?`${e.start??"?"} to ${e.end??"?"}`:e.period:"all time";if(console.log(`Per-email metrics (${r}${e.step!==void 0?`, step ${e.step}`:""})`),console.log(`Totals: ${t.emails.toLocaleString()} emails, ${t.sent.toLocaleString()} sent, ${t.delivered.toLocaleString()} delivered, ${t.opened.toLocaleString()} opened (${t.openRate.toFixed(1)}%), ${t.clicked.toLocaleString()} clicked (${t.clickRate.toFixed(1)}%)`),console.log(`Page: ${n.page}/${n.totalPages||1} (${n.total.toLocaleString()} matching emails)`),e.emails.length===0){console.log("No emails found.");return}console.log("");for(let o of e.emails)console.log(`- ${Qve(o)}`)}async function oW(e){let t=await Tve(e);if(e.json){S(t);return}$ve(t)}function Nve(e){if(e.emails||e.clients)throw new A("--links cannot be combined with --emails or --clients",400);if(e.campaign||e.sequence||e.transactional)throw new A("--links covers the whole account; for one campaign's links use 'sequenzy stats --campaign <id> --json' and read clickedLinks",400);let t=new URLSearchParams;for(let[r,o]of[["period",e.period],["start",e.start],["end",e.end],["emailType",e.emailType],["mailboxProvider",e.mailboxProvider],["limit",e.limit]])if(o)t.set(r,o);if(e.includeBots)t.set("includeMachineEngagement","true");let n=t.toString();return n?`/api/v1/metrics/links?${n}`:"/api/v1/metrics/links"}function Ove(e){return`${e.toFixed(e>0&&e<1?1:0)}%`}function Pve(e){let n=[`Link clicks (${e.period==="custom"&&e.start&&e.end?`${e.start} - ${e.end}`:e.period??"all time"})`];if(e.totalClicks===0)return n.push("No link clicks in this period."),n;let r=Math.max(...e.links.map((o)=>o.uniqueClicks.toLocaleString().length));n.push("");for(let o of e.links)n.push(` ${o.uniqueClicks.toLocaleString().padStart(r)} ${Ove(o.share).padStart(4)} ${o.clicks.toLocaleString()} ${o.clicks===1?"click":"clicks"} ${o.url}`);return n.push("",`${e.totalUniqueClicks.toLocaleString()} unique ${e.totalUniqueClicks===1?"click":"clicks"} (${e.totalClicks.toLocaleString()} total) across ${e.totalLinks.toLocaleString()} ${e.totalLinks===1?"link":"links"}${e.links.length<e.totalLinks?`; showing the top ${e.links.length}`:""}. Each subscriber counts once per link, and query strings are ignored, so UTM-tagged variants of a page count together.`),n}async function iW(e){let t=await E("GET",Nve(e),void 0,e.company);if(e.json){S(t);return}for(let n of Pve(t))console.log(n)}var W=yt(cg(),1);function qve(e,t){if(e===void 0||t===void 0)return null;return`${t.toLocaleString()} active (${e.toLocaleString()} total)`}function Fve(e){let t=e.recipients===1?"recipient":"recipients",n=e.clickers===1?"clicker":"clickers";return{impressions:`${e.impressions.toLocaleString()} (${e.recipients.toLocaleString()} ${t})`,clicks:`${e.clicks.toLocaleString()} (${e.clickers.toLocaleString()} ${n})`,orders:e.orders.toLocaleString(),revenue:(e.revenueByCurrency?.length??0)>0?(e.revenueByCurrency??[]).map(({currency:r,revenueCents:o})=>{let a=(o/100).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});return r==="UNKNOWN"?`${a} (currency unknown)`:`${r} ${a}`}).join(" + "):e.revenueCents>0?`${e.revenueCents.toLocaleString()} minor units (currency unavailable)`:"—",topProducts:e.topProducts.map((r)=>`${r.provider}:${r.providerProductId}: ${r.impressions.toLocaleString()} shown, ${r.clicks.toLocaleString()} clicked`)}}function Lve(e){let t=e.blocked??0;return[`Permanent: ${e.permanent.toLocaleString()}`,`Soft: ${Math.max(0,e.transient-t).toLocaleString()}`,`Blocked: ${t.toLocaleString()}`,`Undetermined: ${e.undetermined.toLocaleString()}`].join(" · ")}function Uve(e){let t=e.allowMultiple?e.totalResponses===1?"respondent · multiple answers":"respondents · multiple answers":e.totalResponses===1?"response":"responses";return{heading:`${e.question||"Poll"} (${e.totalResponses.toLocaleString()} ${t})`,details:[...e.nps?[`NPS: ${e.nps.score>0?"+":""}${e.nps.score} · Average: ${e.nps.average.toFixed(1)} · ${e.nps.promoters} promoters · ${e.nps.passives} passives · ${e.nps.detractors} detractors`]:[],...e.answers.map((n)=>`- ${n.answer}: ${n.responses.toLocaleString()} (${n.percentage}%)`)]}}function sW({polls:e,indent:t=0}){return W.jsxDEV(W.Fragment,{children:e.map((n)=>{let{heading:r,details:o}=Uve(n);return W.jsxDEV(Re,{flexDirection:"column",marginBottom:1,marginLeft:t,children:[W.jsxDEV(me,{children:r},void 0,!1,void 0,this),o.map((a)=>W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:a},void 0,!1,void 0,this)},a,!1,void 0,this))]},n.blockId,!0,void 0,this)})},void 0,!1,void 0,this)}function jve(e){let t=e.stats;return{subscriberCount:e.subscriberCount,activeSubscriberCount:e.activeSubscriberCount,sent:t.sent,delivered:t.delivered,opened:t.opened,clicked:t.clicked,replies:t.replies??0,unsubscribed:t.unsubscribed,openRate:t.openRate,clickRate:t.clickRate,replyRate:t.replyRate??0,complaints:t.complaints,complaintRate:t.complaintRate,conversions:t.conversions,revenueCents:t.revenueCents,enrollmentSkipped:e.enrollmentSkipped,enrollmentCounts:e.enrollmentCounts,pausedEnrollments:e.pausedEnrollments,steps:e.steps,clickedLinks:e.clickedLinks,bounceBreakdown:e.bounceBreakdown,engagementBreakdown:e.engagementBreakdown,polls:e.polls,commerceForecast:e.commerceForecast,recommendations:e.recommendations}}function jB(e,t){try{return new Intl.NumberFormat(void 0,{style:"currency",currency:t??"USD",maximumFractionDigits:0}).format(e/100)}catch{return`${t??"USD"} ${Math.round(e/100).toLocaleString()}`}}function Bv(e){let t=new URLSearchParams,n=Boolean(e.campaign||e.sequence||e.transactional);if(e.start||e.end){if(e.start)t.set("start",e.start);if(e.end)t.set("end",e.end)}else if(!n)t.set("period",e.period??"7d");else if(e.period)t.set("period",e.period);if(!n&&e.emailType)t.set("emailType",e.emailType);if(!n&&e.recipientDomain)t.set("recipientDomain",e.recipientDomain);if(!n&&e.source)t.set("source",e.source);if(!n&&e.outcome)t.set("outcome",e.outcome);if(e.mailboxProvider)t.set("mailboxProvider",e.mailboxProvider);if(e.includeBots)t.set("includeMachineEngagement","true");let r=t.toString();return r?`?${r}`:""}async function aW(e){let t=[e.campaign,e.sequence,e.transactional].filter((n)=>n!==void 0);if(t.length>1)throw new A("Use only one of --campaign, --sequence, or --transactional",400);if(e.emailType!==void 0&&!["campaign","transactional","sequence"].includes(e.emailType))throw new A("--email-type must be 'campaign', 'transactional', or 'sequence'",400);if(e.emailType&&t.length>0)throw new A("--email-type filters account-level stats and cannot be combined with --campaign, --sequence, or --transactional",400);if((e.recipientDomain||e.source||e.outcome)&&t.length>0)throw new A("--recipient-domain, --source and --outcome filter account-level stats and cannot be combined with --campaign, --sequence, or --transactional",400);if(e.mailboxProvider&&(e.sequence||e.transactional))throw new A("--mailbox-provider applies to account-level stats and --campaign only",400);if(e.campaign)return E("GET",`/api/v1/metrics/campaigns/${e.campaign}${Bv(e)}`,void 0,e.company);if(e.sequence)return E("GET",`/api/v1/metrics/sequences/${e.sequence}${Bv(e)}`,void 0,e.company);if(e.transactional)return E("GET",`/api/v1/metrics/transactional/${encodeURIComponent(e.transactional)}${Bv(e)}`,void 0,e.company);return E("GET",`/api/v1/metrics${Bv(e)}`,void 0,e.company)}function zve({options:e}){let[t,n]=Qu.useState(!0),[r,o]=Qu.useState(""),[a,c]=Qu.useState(null);if(Qu.useEffect(()=>{async function v(){try{let C=await aW(e);c(jve(C))}catch(C){o(gf(C instanceof A?C:C))}finally{n(!1)}}v()},[e]),Qu.useEffect(()=>{if(!t)setTimeout(()=>process.exit(r?1:0),100)},[t,r]),t)return W.jsxDEV(Re,{padding:1,children:[W.jsxDEV(me,{color:"cyan",children:W.jsxDEV(Ev,{type:"dots"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.jsxDEV(me,{children:" Loading stats..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(r)return W.jsxDEV(Re,{padding:1,children:W.jsxDEV(me,{color:"red",children:[" ",r]},void 0,!0,void 0,this)},void 0,!1,void 0,this);if(!a)return W.jsxDEV(Re,{padding:1,children:W.jsxDEV(me,{dimColor:!0,children:"No stats available"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let l=e.period??"7d",p=e.campaign?"Campaign Stats":e.sequence?"Sequence Stats":e.transactional?"Transactional Email Stats":`Stats (${e.emailType?`${e.emailType}, `:""}${l})`,f=e.sequence&&a.steps?a.steps.filter((v)=>(v.failedCount??0)>0):[],h=a.recommendations?Fve(a.recommendations):null,b=qve(a.subscriberCount,a.activeSubscriberCount);return W.jsxDEV(Re,{flexDirection:"column",padding:1,children:[W.jsxDEV(Re,{marginBottom:1,children:[W.jsxDEV(me,{bold:!0,color:"green",children:p},void 0,!1,void 0,this),e.mailboxProvider&&W.jsxDEV(me,{dimColor:!0,children:[" for ",e.mailboxProvider," recipients"]},void 0,!0,void 0,this),e.outcome&&W.jsxDEV(me,{dimColor:!0,children:[" ","only sends with ",e.outcome.replace("_"," ")]},void 0,!0,void 0,this),e.includeBots&&W.jsxDEV(me,{dimColor:!0,children:" including bot/scanner engagement"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{flexDirection:"column",children:[b&&W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Subscribers: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:b},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Sent: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.sent.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a.complaints!==void 0&&W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Complaints: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.complaints.toLocaleString()},void 0,!1,void 0,this),a.complaintRate!==void 0&&W.jsxDEV(me,{dimColor:!0,children:[" (",a.complaintRate.toFixed(2),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Delivered: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.delivered.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Opened: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.opened.toLocaleString()},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:[" (",a.openRate.toFixed(1),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Clicked: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.clicked.toLocaleString()},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:[" (",a.clickRate.toFixed(1),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Replies: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.replies.toLocaleString()},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:[" (",a.replyRate.toFixed(1),"%)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Unsubscribed: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.unsubscribed.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a.conversions!==void 0&&W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Conversions: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:a.conversions.toLocaleString()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a.revenueCents!==void 0&&W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Revenue: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:["$",(a.revenueCents/100).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(a.enrollmentSkipped?.count??0)>0&&W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Skipped: "},void 0,!1,void 0,this),W.jsxDEV(me,{color:"yellow",children:a.enrollmentSkipped?.count.toLocaleString()},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:[" ","(",Object.entries(a.enrollmentSkipped?.byReason??{}).map(([v,C])=>`${C} ${v}`).join(", ")||"couldn't be enrolled","; contacts that triggered the sequence but can't receive emails)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),e.sequence&&(a.steps?.length??0)>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:[W.jsxDEV(me,{bold:!0,children:"Steps"},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:" · sent per email step, in graph order"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(a.steps??[]).map((v)=>W.jsxDEV(Re,{marginLeft:2,children:[W.jsxDEV(me,{children:[`${v.step}. ${v.subject??v.nodeId}: `,v.stats.sent.toLocaleString()," sent"]},void 0,!0,void 0,this),W.jsxDEV(me,{dimColor:!0,children:` · ${v.stats.delivered.toLocaleString()} delivered · ${v.stats.opened.toLocaleString()} opened · ${v.stats.clicked.toLocaleString()} clicked · ${v.nodeId}`},void 0,!1,void 0,this)]},v.nodeId,!0,void 0,this))]},void 0,!0,void 0,this),e.sequence&&(a.steps??[]).some((v)=>(v.polls?.length??0)>0)&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:[W.jsxDEV(me,{bold:!0,children:"Poll & NPS Results"},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:" · per email step, all time"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(a.steps??[]).filter((v)=>(v.polls?.length??0)>0).map((v)=>W.jsxDEV(Re,{flexDirection:"column",marginLeft:2,children:[W.jsxDEV(me,{bold:!0,children:`${v.step}. ${v.subject??v.nodeId}`},void 0,!1,void 0,this),W.jsxDEV(sW,{polls:v.polls??[],indent:2},void 0,!1,void 0,this)]},v.nodeId,!0,void 0,this))]},void 0,!0,void 0,this),e.sequence&&a.enrollmentCounts&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:[W.jsxDEV(me,{bold:!0,children:"Current Enrollments"},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:[` · ${a.enrollmentCounts.total.toLocaleString()} total, ${a.enrollmentCounts.active.toLocaleString()} active, ${a.enrollmentCounts.waiting.toLocaleString()} waiting`,a.pausedEnrollments&&a.pausedEnrollments.total>0?` · ${a.pausedEnrollments.total.toLocaleString()} paused (not in total)`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),a.enrollmentCounts.byCurrentNode.map((v)=>W.jsxDEV(Re,{marginLeft:2,children:[W.jsxDEV(me,{children:["-"," ",v.currentNodeLabel??v.currentNodeType??v.currentNodeId,": ",v.total.toLocaleString()," (",v.active.toLocaleString()," ","active, ",v.waiting.toLocaleString()," waiting)"]},void 0,!0,void 0,this),v.currentNodeMissing&&W.jsxDEV(me,{color:"yellow",children:" · node missing from sequence graph"},void 0,!1,void 0,this)]},v.currentNodeId,!0,void 0,this))]},void 0,!0,void 0,this),!e.campaign&&!e.sequence&&!e.transactional&&!e.emailType&&a.commerceForecast&&a.commerceForecast.history.orderCount>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:[W.jsxDEV(me,{bold:!0,children:"Commerce Forecast"},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:` · ${a.commerceForecast.history.orderCount.toLocaleString()} paid orders`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a.commerceForecast.status==="ready"&&a.commerceForecast.forecast?W.jsxDEV(W.Fragment,{children:[W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Predicted AOV: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:jB(a.commerceForecast.forecast.predictedAverageOrderValueCents,a.commerceForecast.currency)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"12-month LTV: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:jB(a.commerceForecast.forecast.predictedCustomerValue365DaysCents,a.commerceForecast.currency)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"90-day revenue: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:jB(a.commerceForecast.forecast.expectedRevenue90DaysCents,a.commerceForecast.currency)},void 0,!1,void 0,this),W.jsxDEV(me,{dimColor:!0,children:` (${a.commerceForecast.forecast.expectedOrders90Days.toLocaleString()} orders, ${a.commerceForecast.confidence} confidence)`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):W.jsxDEV(me,{dimColor:!0,children:a.commerceForecast.eligibility.reasons.map((v)=>v.message).join(" · ")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:W.jsxDEV(me,{bold:!0,children:"Product Recommendations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Impressions: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:h.impressions},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Clicks: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:h.clicks},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Orders: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:h.orders},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W.jsxDEV(Re,{children:[W.jsxDEV(me,{dimColor:!0,children:"Revenue: "},void 0,!1,void 0,this),W.jsxDEV(me,{children:h.revenue},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h.topProducts.length>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(me,{bold:!0,children:"Top Products"},void 0,!1,void 0,this),h.topProducts.map((v)=>W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["- ",v]},void 0,!0,void 0,this)},v,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),f.length>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:W.jsxDEV(me,{bold:!0,children:"Step Failures"},void 0,!1,void 0,this)},void 0,!1,void 0,this),f.map((v)=>W.jsxDEV(Re,{flexDirection:"column",marginBottom:1,children:[W.jsxDEV(me,{children:["Step ",v.step,": ",v.subject??v.nodeId," (",v.failedCount," failed",")"]},void 0,!0,void 0,this),(v.failedSubscribers??[]).map((C)=>W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["- ",C.email??C.subscriberId,":"," ",C.failedReason??"Reason unavailable"]},void 0,!0,void 0,this)},`${v.nodeId}-${C.subscriberId}`,!1,void 0,this)),(v.failedCount??0)>(v.failedSubscribers?.length??0)&&W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{dimColor:!0,children:["Showing first ",v.failedSubscribers?.length??0," of"," ",v.failedCount," failed subscribers"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},v.nodeId,!0,void 0,this))]},void 0,!0,void 0,this),a.clickedLinks&&a.clickedLinks.length>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:W.jsxDEV(me,{bold:!0,children:"Clicked Links"},void 0,!1,void 0,this)},void 0,!1,void 0,this),a.clickedLinks.map((v)=>W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["- ",v.url,": ",v.clicks.toLocaleString()," (",v.percentage.toFixed(1),"%)"]},void 0,!0,void 0,this)},v.url,!1,void 0,this))]},void 0,!0,void 0,this),a.bounceBreakdown&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(me,{bold:!0,children:"Bounce Breakdown"},void 0,!1,void 0,this),W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:Lve(a.bounceBreakdown)},void 0,!1,void 0,this)},void 0,!1,void 0,this),a.bounceBreakdown.subtypes.map((v)=>W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["- ",v.type," / ",v.subType??"Unknown",": ",v.count]},void 0,!0,void 0,this)},`${v.type}-${v.subType??"unknown"}`,!1,void 0,this))]},void 0,!0,void 0,this),a.engagementBreakdown&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(me,{bold:!0,children:"Human vs Machine Engagement"},void 0,!1,void 0,this),W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["Human: ",a.engagementBreakdown.human.opens," opens ·"," ",a.engagementBreakdown.human.clicks," clicks"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),W.jsxDEV(Re,{marginLeft:2,children:W.jsxDEV(me,{children:["Machine: ",a.engagementBreakdown.machine.opens," opens ·"," ",a.engagementBreakdown.machine.clicks," clicks"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a.polls&&a.polls.length>0&&W.jsxDEV(Re,{flexDirection:"column",marginTop:1,children:[W.jsxDEV(Re,{marginBottom:1,children:W.jsxDEV(me,{bold:!0,children:"Poll & NPS Results"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.jsxDEV(sW,{polls:a.polls},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Mve(e){return e.outcome&&(e.links||e.clients||e.emails)?new A("--outcome filters account stats and --by only, not --links, --clients or --emails",400):null}async function cW(e){try{rW(e)}catch(r){k(r),process.exitCode=1;return}if(!await j())k(M()),process.exit(1);if(e.by){try{await eW(e)}catch(r){k(r),process.exitCode=1}return}let t=Mve(e);if(t){k(t),process.exitCode=1;return}if(e.links){try{await iW(e)}catch(r){k(r),process.exitCode=1}return}if(e.clients){try{await tW(e)}catch(r){k(r),process.exitCode=1}return}if(e.emails){try{await oW(e)}catch(r){k(r),process.exitCode=1}return}if(e.json){try{S(await aW(e))}catch(r){k(r),process.exitCode=1}return}await ag(W.jsxDEV(zve,{options:e},void 0,!1,void 0,this)).waitUntilExit()}var lW=500;function _v(e){return Array.from(new Set((e??[]).map((t)=>t.trim()).filter((t)=>t.length>0)))}function Hve(e){return Array.isArray(e.email)&&e.email.length>0||e.emailsJson!==void 0||e.emailsFile!==void 0}function Gve(e,t){let n=_v(e.tag);if(n.length===0)throw new A("Provide at least one --tag",400);let r=Hve(e)?_v(op(e)):[],o=_v(e.externalId),a=_v(e.subscriberId);if(r.length+o.length+a.length===0)throw new A("Provide at least one target: --email, --emails-file, --emails-json, --external-id, or --subscriber-id",400);let c=[...r.map((p)=>({kind:"emails",value:p})),...o.map((p)=>({kind:"externalIds",value:p})),...a.map((p)=>({kind:"subscriberIds",value:p}))],l=[];for(let p=0;p<c.length;p+=lW){let f=c.slice(p,p+lW),h=f.filter((C)=>C.kind==="emails").map((C)=>C.value),b=f.filter((C)=>C.kind==="externalIds").map((C)=>C.value),v=f.filter((C)=>C.kind==="subscriberIds").map((C)=>C.value);l.push({tags:n,...h.length>0&&{emails:h},...b.length>0&&{externalIds:b},...v.length>0&&{subscriberIds:v},...t==="add"&&e.triggerAutomations===!0?{triggerAutomations:!0}:{}})}return l}function Jve(e){let t=e[0];if(!t)throw new A("No bulk tag responses to combine",500);return e.reduce((n,r)=>({success:n.success&&r.success,tags:r.tags,requested:n.requested+r.requested,matched:n.matched+r.matched,updated:n.updated+r.updated,unchanged:n.unchanged+r.unchanged,failed:n.failed+r.failed,notFound:{emails:[...n.notFound.emails,...r.notFound.emails],externalIds:[...n.notFound.externalIds,...r.notFound.externalIds],subscriberIds:[...n.notFound.subscriberIds,...r.notFound.subscriberIds]},failures:[...n.failures,...r.failures],triggeredAutomations:n.triggeredAutomations===!0||r.triggeredAutomations===!0}),{success:!0,tags:t.tags,requested:0,matched:0,updated:0,unchanged:0,failed:0,notFound:{emails:[],externalIds:[],subscriberIds:[]},failures:[],triggeredAutomations:!1})}function Wve(e,t){if(console.log(`${t==="add"?"Added":"Removed"} tags: ${e.tags.join(", ")}`),console.log(`Requested: ${e.requested}`),console.log(`Matched existing subscribers: ${e.matched}`),console.log(`Changed: ${e.updated}`),console.log(`Already in target state: ${e.unchanged}`),console.log(`Failed: ${e.failed}`),t==="add")console.log(`Tag automations: ${e.triggeredAutomations?"enabled":"skipped"}`);let n=[...e.notFound.emails,...e.notFound.externalIds,...e.notFound.subscriberIds];if(n.length>0){console.log(`Not found (not created): ${n.length}`);for(let r of n.slice(0,10))console.log(`- ${r}`);if(n.length>10)console.log(`...and ${n.length-10} more`)}for(let r of e.failures.slice(0,10))console.log(`- ${r.email??r.subscriberId}: ${r.error}`);if(e.failures.length>10)console.log(`...and ${e.failures.length-10} more failures`)}async function zB(e,t){if(!await j())k(M()),process.exit(1);try{let n=Gve(t,e),r=[];for(let a of n)r.push(await E("POST",`/api/v1/subscribers/bulk/tags/${e}`,a,t.company));let o=Jve(r);if(t.json){S({...o,requests:n.length});return}Wve(o,e)}catch(n){k(n instanceof A?n:n),process.exit(1)}}import{randomUUID as Vve}from"node:crypto";var MB="/api/v1/subscribers/operations";async function xv(e,t){if(e!=="start"&&e!=="list"&&!t.id)throw Error("Operation ID is required");let n=t.id?`${MB}/${encodeURIComponent(t.id)}`:MB;if(e==="list"){let a=await E("GET",MB,void 0,t.company);if(t.json)S(a);else for(let c of a.operations)uW(c);return}let r;if(e==="start"){if(t.kind!=="add_tags")throw Error("--kind must be add_tags");let a=t.audienceJson?JSON.parse(kn(t.audienceJson.startsWith("@")?void 0:t.audienceJson,t.audienceJson.startsWith("@")?t.audienceJson.slice(1):void 0,"audience-json")??"{}"):{},c=t.requestKey??Vve();rp(`Request key: ${c}. If the request is interrupted, retry with --request-key ${c}.`,{json:t.json,type:"recovery",requestKey:c}),r={kind:t.kind,requestKey:c,audience:a,...t.tag!==void 0&&{tags:t.tag},...t.triggerAutomations!==void 0&&{triggerAutomations:t.triggerAutomations}}}let o=await E(e==="get"?"GET":"POST",e==="cancel"?`${n}/cancel`:n,r,t.company);if(t.json)S(o);else uW(o.operation)}function uW(e){console.log(`${e.id} ${e.kind} ${e.status} ${e.processed}/${e.total} processed, ${e.failed} failed`);for(let t of e.failures)console.log(`${t.subscriberId}: ${t.error}`);if(e.error)console.log(e.error)}function HB(e,t){let n={...Df("--attrs-json",t),...e};return Object.keys(n).length>0?n:void 0}function Kve(e){let t=e.isArray?`${e.valueType} list`:e.valueType,n=e.mixedTypes?`${t}, mixed types`:t,r=e.sampleValue===null?"":` e.g. ${e.sampleValue}`;return`${e.key} (${n})${r}`}async function dW(e){let t=e.includeNested?"?includeNested=true":"",n=await E("GET",`/api/v1/subscribers/attributes${t}`,void 0,e.company);if(e.json){S(n);return}if(n.attributes.length===0){console.log("No custom attributes yet.");return}for(let o of n.attributes)console.log(Kve(o));let r=n.sampledContacts>0?`Types and examples come from ${n.sampledContacts} recent contacts.`:"Types and examples come from the account's attribute index.";console.log(`
|
|
318
318
|
${r} Set typed values with --attrs-json, e.g. --attrs-json '{"zip":"02134","seats":5}'.`)}var pW=25;function kv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Yve(e){let t=e.trim();if(!t)throw new A("Events import file is empty",400);let n;try{n=JSON.parse(t)}catch(l){throw new A(`Invalid events import JSON: ${l instanceof Error?l.message:"Unknown error"}`,400)}let r=Array.isArray(n)?n:kv(n)&&Array.isArray(n.events)?n.events:null;if(!r||r.length===0)throw new A("Events import JSON must be a non-empty array or an object with an events array",400);if(r.length>pW)throw new A(`Events import accepts at most ${pW} events per request - split the file and send multiple requests`,400);let o=new Set(["email","externalId","name","properties","occurredAt","eventId"]),a=new Set,c=r.map((l,p)=>{if(!kv(l))throw new A(`Event ${p+1} must be an object`,400);if(!(typeof l.name==="string"&&l.name.trim()!==""))throw new A(`Event ${p+1} must include a name`,400);let h=typeof l.email==="string"&&l.email.trim()!=="",b=typeof l.externalId==="string"&&l.externalId.trim()!=="";if(!h&&!b)throw new A(`Event ${p+1} must include an email or an externalId`,400);if(!(typeof l.eventId==="string"&&l.eventId.trim()!==""))throw new A(`Event ${p+1} must include a non-empty eventId so retries are safe`,400);if(l.properties!==void 0&&l.properties!==null&&!kv(l.properties))throw new A(`Event ${p+1} properties must be an object`,400);for(let C of["email","externalId","occurredAt","eventId"]){let R=l[C];if(R!==void 0&&R!==null&&typeof R!=="string")throw new A(`Event ${p+1} ${C} must be a string`,400)}for(let C of Object.keys(l))if(!o.has(C))a.add(C);return{...h?{email:l.email}:{},...b?{externalId:l.externalId}:{},name:l.name,...kv(l.properties)?{properties:l.properties}:{},...typeof l.occurredAt==="string"&&l.occurredAt.trim()?{occurredAt:l.occurredAt}:{},eventId:l.eventId.trim()}});if(a.size>0)rp(`Ignoring unrecognized event field(s): ${[...a].sort().join(", ")}. Put row data inside "properties" to keep it.`,{warn:!0});return c}async function mW(e){if(e.eventsJson&&e.file)throw new A("Provide either the positional JSON file or --events-json, not both",400);let t=e.file?kn(void 0,e.file,"events import"):e.eventsJson;if(t===void 0)throw new A("Provide a JSON file or --events-json",400);let n=Yve(t),r=await E("POST","/api/v1/subscribers/events/imports",{events:n},e.company);if(!r.success)process.exitCode=1;if(e.json){S(r);return}console.log(`Events: ${r.total}`),console.log(`Recorded: ${r.recorded}`),console.log(`Duplicates: ${r.duplicates}`),console.log(`Failed: ${r.failed}`),console.log(`Side-effect failures: ${r.sideEffectFailed??0}`),console.log(`Subscribers: ${r.subscribers}`);for(let o of r.failures??[])console.log(` events[${o.index}]: ${o.error}`);for(let o of r.sideEffectFailures??[])console.log(` events[${o.index}] recorded, but ${o.stages.join(", ")} failed${o.error?`: ${o.error}`:""}`);if(!r.success)console.log("Some receipts or downstream stages still need recovery. Fix request-level row errors, then retry the same file: eventId prevents a second receipt and downstream work is re-attempted idempotently.")}import{basename as Zve}from"node:path";var Xve=new Set(["skip","merge","overwrite"]),eEe=new Set(["default","confirmed","double_opt_in"]);function fW(e){return Object.entries(e??{}).filter(([,n])=>n>0).sort(([,n],[,r])=>r-n).map(([n,r])=>`${n}=${r}`).join(", ")}function GB(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function tEe(e){let t=e.trim();if(/^(true|false)$/i.test(t))return t.toLowerCase()==="true";if(/^-?(?:\d+|\d*\.\d+)$/.test(t)){let n=Number(t);if(!/^-?0\d/.test(t)&&Number.isFinite(n)&&Math.abs(n)<=Number.MAX_SAFE_INTEGER)return n}return t}function gW(e){return e.trim().toLowerCase().replace(/[^a-z0-9]/g,"")}function JB(e,t){let n=new Set(t.map(gW)),r=e.findIndex((o)=>n.has(gW(o)));return r===-1?void 0:r}function rs(e,t){return t===void 0?"":e[t]?.trim()??""}function nEe(e){let t=Array.isArray(e)?e:GB(e)&&Array.isArray(e.subscribers)?e.subscribers:null;if(!t||t.length===0)throw new A("Subscriber import JSON must be a non-empty array or an object with a subscribers array",400);return t.map((n,r)=>{let o=GB(n)&&typeof n.email==="string"&&n.email.trim()!=="",a=GB(n)&&typeof n.phone==="string"&&n.phone.trim()!=="";if(!o&&!a)throw new A(`Subscriber import record ${r+1} must include an email or a phone number`,400);return n})}function rEe(e){let t=e.trim();if(!t)throw new A("Subscriber import file is empty",400);if(t.startsWith("[")||t.startsWith("{"))try{return{subscribers:nEe(JSON.parse(t))}}catch(le){if(le instanceof A)throw le;throw new A(`Invalid subscriber import JSON: ${le instanceof Error?le.message:"Unknown error"}`,400)}let{headers:n,data:r}=xz(e),o=fu(n,"email"),a=fu(n,"externalId"),c=fu(n,"firstName"),l=fu(n,"lastName"),p=fu(n,"fullName"),f=fu(n,"timezone"),h=JB(n,["phone","phone number","mobile"]),b=JB(n,["status","email status"])??Oz(n,r),v=Pz(n),C=JB(n,["tags","tag"]),R=new Set([o,a,c,l,p,f,h,b,v,C].filter((le)=>le!==void 0));if(o===void 0&&h===void 0)throw new A("CSV must include an email or phone column",400);let N=b!==void 0||v!==void 0,L=[],K=new Set,_e=r.map((le,Z)=>{let ee=rs(le,o);if(!ee&&!rs(le,h))throw new A(`CSV row ${Z+2} is missing an email and a phone number`,400);let tt=kz(rs(le,p)),Pe=rs(le,c)||tt.firstName,Ye=rs(le,l)||tt.lastName,Ee=rs(le,b),Ze=Qz({...b!==void 0&&{status:Ee},...v!==void 0&&{unsubscribeDate:rs(le,v)}});if(L.push(Ze),!Ze.recognized&&Ee)K.add(Ee);let Hn=$z(Ze.status),xt={};n.forEach((wt,en)=>{let Qt=rs(le,en);if(!R.has(en)&&wt.trim()&&Qt)xt[wt.trim()]=tEe(Qt)});let lt=rs(le,C).split(/[|;,]/).map((wt)=>wt.trim()).filter(Boolean),Jt=rs(le,a),we=rs(le,h),Xt=rs(le,f);return{...ee&&{email:ee},...Jt&&{externalId:Jt},...Pe&&{firstName:Pe},...Ye&&{lastName:Ye},...we&&{phone:we},...Xt&&{timezone:Xt},...Hn&&{status:Hn},...lt.length>0&&{tags:lt},...Object.keys(xt).length>0&&{customAttributes:xt}}});if(!N)return{subscribers:_e};return{subscribers:_e,statusSummary:Nz(L),unrecognizedStatusValues:[...K].slice(0,5)}}function oEe(e){return[`${e.active} active`,`${e.unsubscribed} unsubscribed`,`${e.bounced} bounced`,...e.unrecognized>0?[`${e.unrecognized} unknown imported as active`]:[]].join(", ")}function iEe(e){let t=e.duplicateStrategy??"skip";if(!Xve.has(t))throw new A("--duplicate-strategy must be one of: skip, merge, overwrite",400);let n=e.optInMode??"default";if(!eEe.has(n))throw new A("--opt-in-mode must be one of: default, confirmed, double_opt_in",400);if(e.defaultPhoneCountry!==void 0&&!/^[a-z]{2}$/i.test(e.defaultPhoneCountry))throw new A("--default-phone-country must be a two-letter code",400)}async function AW(e){if(iEe(e),e.recordsJson&&e.file)throw new A("Provide either the positional CSV/JSON file or --records-json, not both",400);let t=e.file?kn(void 0,e.file,"subscriber import"):e.recordsJson;if(t===void 0)throw new A("Provide a CSV/JSON file or --records-json",400);let{subscribers:n,statusSummary:r,unrecognizedStatusValues:o}=rEe(t),a=Array.isArray(e.list)?e.list:e.list?[e.list]:[],c=await E("POST","/api/v1/subscribers/imports",{subscribers:n,duplicateStrategy:e.duplicateStrategy??"skip",fileName:e.fileName??(e.file?Zve(e.file):"CLI import"),...a.length>0&&{listIds:a},enrollInSequences:e.enrollSequences===!0,...e.defaultPhoneCountry&&{defaultPhoneCountry:e.defaultPhoneCountry.toUpperCase()},...e.smsConsent!==void 0&&{smsConsent:e.smsConsent},...e.idempotencyKey!==void 0&&{idempotencyKey:e.idempotencyKey},optInMode:e.optInMode??"default"},e.company);if(e.json){S(r?{...c,statusSummary:r,...o?.length?{unrecognizedStatusValues:o}:{}}:c);return}if(r){if(console.log(`Statuses: ${oEe(r)}`),o?.length)console.log(` Unrecognized status values: ${o.join(", ")}`)}if(c.deduplicated){console.log(`Import already queued for this idempotency key: ${c.import.id}`),console.log(`Status: ${c.import.status}`),console.log(`Check progress: sequenzy subscribers import-status ${c.import.id}`);return}console.log(`Queued subscriber import: ${c.import.id}`),console.log(`Rows: ${c.import.totalRows}`),console.log(`Status: ${c.import.status}`),console.log(`Check progress: sequenzy subscribers import-status ${c.import.id}`)}async function hW(e){let t=e.importId?.trim();if(!t)throw new A("Provide an import ID",400);let n=await E("GET",`/api/v1/subscribers/imports/${encodeURIComponent(t)}`,void 0,e.company);if(e.json){S(n);return}let r=n.import;console.log(`Subscriber import: ${r.id}`),console.log(`Status: ${r.status}`),console.log(`Processed: ${r.processedCount} of ${r.totalRows}`),console.log(`Added: ${r.addedCount}`),console.log(`Updated: ${r.updatedCount}`),console.log(`Skipped: ${r.skippedCount}`);let o=fW(r.skippedReasons);if(o)console.log(` Skipped reasons: ${o}`);console.log(`Failed: ${r.failedCount}`);let a=fW(r.failedReasons);if(a)console.log(` Failed reasons: ${a}`);if(r.status==="completed"&&r.failedCount>0)console.log("Completed with row failures; inspect --json for reason counts.")}function sEe(e){if(typeof e!=="object"||e===null)return null;let t=e;if(t.historical!==!0)return null;return{duplicates:typeof t.duplicates==="number"?t.duplicates:0}}function aEe(e){if(typeof e!=="object"||e===null)return!1;return e.duplicate===!0}function cEe(e){if(typeof e!=="object"||e===null)return null;let t=e.accountIgnored;if(typeof t!=="object"||t===null)return null;let n=t.message;return typeof n==="string"?n:null}function lEe(e){if(typeof e!=="object"||e===null)return[];let t=e.sideEffectFailures;return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}function YB(e){if(!e)return[];return Array.isArray(e)?e:[e]}function vW(e){if(!e)return[];return Array.isArray(e)?e:[e]}function Rv(e){let t={};for(let n of e??[]){let[r,...o]=n.split("="),a=o.join("=");if(r&&a)t[r]=a}return Object.keys(t).length>0?t:void 0}function EW(e){let t=e.email?.trim()||void 0,n=e.externalId?.trim()||void 0;return{...t?{email:t}:{},...n?{externalId:n}:{}}}function $u(e){let t=EW(e);if(!t.email&&!t.externalId)throw Error("Provide an email or --external-id.");return t}function ZB(e,t){let n=new URLSearchParams;if(t?.includeBots)n.set("includeMachineEngagement","true");let r=n.toString(),o=r?`?${r}`:"";if(e.email)return`/api/v1/subscribers/${encodeURIComponent(e.email)}${o}`;return n.set("externalId",String(e.externalId)),`/api/v1/subscribers/external?${n.toString()}`}function IW(e){if(e.email)return`/api/v1/subscribers/${encodeURIComponent(e.email)}/notes`;let t=new URLSearchParams;return t.set("externalId",String(e.externalId)),`/api/v1/subscribers/external/notes?${t.toString()}`}var yW=["is","contains","gt","gte","lt","lte","is_not_empty"];function uEe(e){let t=e.attribute?.trim(),n=e.attributeValue,r=e.attributeOperator?.trim().toLowerCase();if(!t){if(n!==void 0||r)throw new A("--attribute-value and --attribute-operator require --attribute",400);return{}}if(r&&!yW.includes(r))throw new A(`--attribute-operator must be one of ${yW.join(", ")}. Create a segment for is_not, not_contains, or is_empty filters.`,400);let o=r||"is",a;if(n!==void 0)a=`${t}:${n}`;else if(t.includes(":"))a=t;else if(o==="is_not_empty")a=`${t}:`;else throw new A(`Provide --attribute-value (or --attribute "name:value") when --attribute-operator is ${o}. Only is_not_empty may omit a value.`,400);return{attribute:a,attributeOperator:o}}function dEe(e){let t=new URLSearchParams;if(e.segment)t.set("segmentId",e.segment);if(e.status?.trim())t.set("status",e.status.trim());if(e.unsubscribedAfter?.trim())t.set("unsubscribedAfter",e.unsubscribedAfter.trim());if(e.unsubscribedBefore?.trim())t.set("unsubscribedBefore",e.unsubscribedBefore.trim());if(e.attribute?.trim())t.set("attribute",e.attribute.trim());if(e.attributeOperator?.trim())t.set("attributeOperator",e.attributeOperator.trim());let n=YB(e.tag);if(n.length>0)t.set("tags",n.join(","));let r=vW(e.list);if(r.length>0&&r[0])t.set("list",r[0]);if(e.attribute){if(t.set("attribute",e.attribute),e.attributeOperator)t.set("attributeOperator",e.attributeOperator)}if(e.cursor)t.set("cursor",e.cursor);else t.set("page",String(e.page));return t.set("limit",String(e.pageSize)),t}var WB=1000,VB=1000,KB=WB*VB-1;function bW(e){if(e>KB)throw new A(`--offset must be ${KB} or less. Use --cursor to continue beyond that point.`,400);return e}function pEe(e){let t=ot(e.offset,"--offset"),n=ot(e.page,"--page");if(e.cursor?.trim()){if(t!==void 0||n!==void 0)throw new A("--cursor cannot be combined with --offset or --page. Keep following pagination.nextCursor instead.",400);return 0}if(t!==void 0&&n!==void 0)throw new A("Provide either --offset or --page, not both",400);if(t!==void 0&&t<0)throw new A("--offset must be zero or greater",400);if(n!==void 0){if(n<1)throw new A("--page must be 1 or greater",400);let r=CW(e.limit);if(r===void 0)throw new A("--page requires --limit so the page size is defined. Omit both to fetch every match.",400);return bW((n-1)*r)}return bW(t??0)}function CW(e){let t=ot(e,"--limit");if(t!==void 0&&t<1)throw new A("--limit must be 1 or greater",400);return t}async function mEe(e){let t=CW(e.limit),n=pEe(e),r=t===void 0?void 0:n+t,o=Math.min(WB,Math.max(1,r??WB)),a=uEe(e),c=[],l=1,p=e.cursor?.trim()||void 0,f,h=null,b=0,v=!1,C=!1;while(!0){let le=r===void 0?void 0:r-c.length,Z=p?Math.min(o,Math.max(1,le??o)):o,ee=dEe({segment:e.segment,tag:e.tag,list:e.list,status:e.status,unsubscribedAfter:e.unsubscribedAfter,unsubscribedBefore:e.unsubscribedBefore,attribute:a.attribute,attributeOperator:a.attributeOperator,page:l,pageSize:Z,cursor:p}),tt=await E("GET",`/api/v1/subscribers?${ee.toString()}`,void 0,e.company);if(b===0)h=tt.pagination?.total??null;b+=1,c.push(...tt.subscribers??[]);let Pe=(tt.subscribers??[]).length,Ye=tt.pagination?.nextCursor??void 0;f=Ye;let Ee=r!==void 0&&c.length>=r,Ze;if(Ye)Ze=!1;else if(tt.pagination?.hasMore!==void 0)Ze=!tt.pagination.hasMore;else if(tt.pagination?.totalPages!==void 0&&tt.pagination.totalPages!==null)Ze=l>=tt.pagination.totalPages;else Ze=Pe<Z;if(Ze||Pe===0&&!Ye){v=!0;break}if(Ee)break;if(b>=VB){C=!0;break}if(Ye)p=Ye;else if(p)break;else l+=1}let R=Boolean(e.cursor?.trim());if(C&&(c.length<n||c.length===n&&f===void 0))throw new A(`Could not reach offset ${n} within ${VB} requests because too few matches were returned per page. Start without --offset and follow pagination.nextCursor instead.`,400);if(h===null&&v&&!R)h=c.length;let N=c.slice(n,r),L=v?!1:h!==null?n+N.length<h:!v||c.length>n+N.length,K=f!==void 0&&c.length===n+N.length,_e=n+N.length;return{success:!0,subscribers:N,pagination:{page:t===void 0?1:Math.floor(n/t)+1,limit:t??o,offset:n,total:h,totalPages:h===null?null:Math.ceil(h/(t??o)),fetchedPages:b,hasMore:L,nextOffset:L&&!R&&_e<=KB?_e:null,nextCursor:L&&K?f??null:null},returned:N.length,truncated:L}}function wW(e){let t=[e.firstName,e.lastName].map((n)=>n?.trim()).filter((n)=>!!n);return t.length>0?t.join(" "):null}function fEe(e){let t=e.machine===!0?` [bot:${e.engagementQuality??"machine"}]`:"",n=`${X(e.eventTime)} ${e.eventType}${t}`;if(e.eventType==="custom"){let r=e.eventName??"unknown",o=e.properties&&Object.keys(e.properties).length>0?` ${JSON.stringify(e.properties)}`:"";return`${n} ${r}${o}`}if(e.eventType.startsWith("sms_")){let r=[e.smsErrorCode?`error:${e.smsErrorCode}`:null,e.clickedUrl,e.campaignId?`campaign:${e.campaignId}`:null].filter((o)=>Boolean(o));return r.length>0?`${n} ${r.join(" ")}`:n}if(e.clickedUrl)return`${n} ${e.clickedUrl}`;if(e.bounceType)return`${n} ${e.bounceType}`;if(e.campaignId)return`${n} campaign:${e.campaignId}`;return n}function gEe(e){if(e.subscribers.length===0){console.log("No subscribers found");return}console.log(`Subscribers (${e.returned})`);let{offset:t,total:n,nextOffset:r,nextCursor:o}=e.pagination,a=t>0?`Showing ${e.returned} matching subscribers starting at offset ${t}`:`Showing ${e.returned} matching subscribers`;if(e.truncated){let c=n===null?"":` of ${n}`,l=o?`--cursor ${o}`:`--offset ${r}`;console.log(`${a}${c}. Re-run with ${l} for the next page.`)}else console.log(`${a}. Fetched across ${e.pagination.fetchedPages} page(s).`);for(let c of e.subscribers){if(console.log(`- ${c.email} [${c.status}]`),c.externalId)console.log(` External ID: ${c.externalId}`);let l=wW(c);if(l)console.log(` Name: ${l}`);if(c.tags.length>0)console.log(` Tags: ${c.tags.join(", ")}`);if(c.emailProvider)console.log(` Email provider: ${c.emailProvider}`);if(console.log(` Created: ${X(c.createdAt)}`),c.unsubscribedAt)console.log(` Unsubscribed: ${X(c.unsubscribedAt)}`)}}function SW(e){if(console.log(`Notes (${e.length})`),e.length===0){console.log(" None");return}for(let t of e){let n=t.author?.name??t.author?.email??t.authorId??"Unknown";console.log(` - ${t.id} by ${n} at ${X(t.createdAt)}`);for(let r of t.body.split(`
|
|
319
319
|
`))console.log(` ${r}`)}}function AEe(e){if(console.log(`Subscriber: ${e.email}`),console.log(`Status: ${e.status}`),e.unsubscribedAt)console.log(`Unsubscribed: ${X(e.unsubscribedAt)}`);if(e.externalId)console.log(`External ID: ${e.externalId}`);let t=wW(e);if(t)console.log(`Name: ${t}`);if(e.timezone)console.log(`Timezone: ${e.timezone}`);if(console.log(`ID: ${e.id}`),console.log(`Created: ${X(e.createdAt)}`),console.log(`Updated: ${X(e.updatedAt)}`),console.log(`Email provider: ${e.emailProvider??"None"}`),console.log(`Tags: ${e.tags.length>0?e.tags.join(", "):"None"}`),SW(e.notes??[]),console.log("Lists:"),(e.lists?.length??0)===0)console.log(" None");else for(let n of e.lists??[])console.log(` - ${n.name}${n.unsubscribedAt?" [inactive]":" [active]"}`),console.log(` Joined: ${X(n.subscribedAt)}${n.unsubscribedAt?` | Unsubscribed: ${X(n.unsubscribedAt)}`:""}`);if(console.log("Sequence Enrollments:"),(e.sequenceEnrollments?.length??0)===0)console.log(" None");else for(let n of e.sequenceEnrollments??[])if(console.log(` - ${n.sequenceName} [${n.enrollmentStatus}]`),console.log(` Sequence ID: ${n.sequenceId} | Status: ${n.sequenceStatus}`),console.log(` Current node: ${n.currentNodeLabel??n.currentNodeType??"Unknown"}`),console.log(` Entered: ${X(n.enteredAt)} | Updated: ${X(n.updatedAt)}`),n.scheduledFor)console.log(` Scheduled: ${X(n.scheduledFor)}`);if(console.log("Email Stats:"),!e.emailStats)console.log(" None");else console.log(` Sent ${e.emailStats.sent}, delivered ${e.emailStats.delivered}, opened ${e.emailStats.opened}, clicked ${e.emailStats.clicked}, bounced ${e.emailStats.bounced}, unsubscribed ${e.emailStats.unsubscribed}, complained ${e.emailStats.complained}`);if(console.log("Recent Activity:"),(e.activity?.length??0)===0)console.log(" None");else for(let n of e.activity??[])console.log(` - ${fEe(n)}`);if(console.log("Custom Attributes:"),!e.customAttributes||Object.keys(e.customAttributes).length===0)console.log(" None");else console.log(JSON.stringify(e.customAttributes,null,2))}async function hEe(e){let t=await mEe(e);if(e.json){S(t);return}gEe(t)}async function yEe(e){if(e.enrollSequences&&e.skipSequences)throw Error("Provide either --enroll-sequences or --skip-sequences, not both.");let t=e.phone?.trim();if(e.phoneCountry!==void 0&&!t)throw Error("--phone-country only says how to read a national-format number. Pass it together with --phone.");let n=t?EW(e):$u(e),r=vW(e.list),o=await E("POST","/api/v1/subscribers",{...n,...t?{phone:t}:{},...e.phoneCountry!==void 0?{phoneCountry:e.phoneCountry}:{},...e.smsConsent?{smsConsent:!0}:{},firstName:e.firstName,lastName:e.lastName,...e.timezone!==void 0?{timezone:e.timezone.trim()||null}:{},tags:YB(e.tag),...e.noLists?{lists:[]}:r.length>0?{lists:r}:{},...e.enrollSequences?{enrollInSequences:!0}:e.skipSequences?{enrollInSequences:!1}:{},...e.createdAt!==void 0?{createdAt:e.createdAt}:{},customAttributes:HB(Rv(e.attr),e.attrsJson)},e.company);if(e.json){S(o);return}if(console.log(`Added subscriber: ${n.email??(n.externalId?`external:${n.externalId}`:`phone:${t}`)}`),e.createdAt!==void 0)console.log(e.enrollSequences?`Signup date recorded as ${e.createdAt}; matching sequence enrollment was enabled.`:`Signup date recorded as ${e.createdAt}; sequences were not enrolled.`)}async function bEe(e){let t=$u(e),n=YB(e.tag),r=HB(Rv(e.attr),e.attrsJson);if(!(e.status!==void 0||e.firstName!==void 0||e.lastName!==void 0||e.timezone!==void 0||e.phone!==void 0||e.smsConsent!==void 0||n.length>0||r!==void 0))throw Error("Provide at least one of --status, --first-name, --last-name, --timezone, --phone, --sms-consent/--no-sms-consent, --tag, --attr, or --attrs-json.");if(e.phoneCountry!==void 0&&e.phone===void 0)throw Error("--phone-country only says how to read a national-format number. Pass it together with --phone.");let a=await E("PATCH",ZB(t),{...e.status!==void 0&&{status:e.status},...e.firstName!==void 0&&{firstName:e.firstName},...e.lastName!==void 0&&{lastName:e.lastName},...e.timezone!==void 0&&{timezone:e.timezone.trim()||null},...e.phone!==void 0&&{phone:e.phone},...e.phoneCountry!==void 0&&{phoneCountry:e.phoneCountry},...e.smsConsent!==void 0&&{smsConsent:e.smsConsent},...n.length>0&&{tags:n},...r!==void 0&&{customAttributes:r},...e.merge&&r!==void 0?{customAttributesStrategy:"merge"}:{}},e.company);if(e.json){S(a);return}console.log(`Updated subscriber: ${t.email??`external:${t.externalId}`}`)}async function vEe(e){let t=$u(e),n=await E("GET",ZB(t,{includeBots:e.includeBots}),void 0,e.company);if(e.json){S(n);return}AEe(n.subscriber)}async function EEe(e){let t=$u(e),n=await E("GET",IW(t),void 0,e.company);if(e.json){S(n);return}SW(n.notes)}async function IEe(e){let t=$u(e),n=e.body?.trim();if(!n)throw Error("--body is required.");let r=await E("POST",IW(t),{body:n},e.company);if(e.json){S(r);return}console.log(`Added note: ${r.note.id}`)}async function CEe(e){let t=e.noteId?.trim();if(!t)throw Error("Provide a note ID.");let n=await E("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(t)}`,void 0,e.company);if(e.json){S(n);return}console.log(`Deleted note: ${t}`)}async function wEe(e){let t=$u(e),n=ZB(t),r=t.email??`external:${t.externalId}`;if(e.hard){let a=await E("DELETE",n,void 0,e.company);if(e.json){S(a);return}console.log(`Deleted subscriber: ${r}`);return}let o=await E("PATCH",n,{status:"unsubscribed"},e.company);if(e.json){S(o);return}console.log(`Unsubscribed: ${r}`)}async function SEe(e){let t=$u(e),n=e.name?.trim();if(!n)throw Error("--name is required.");if(e.account!==void 0&&e.organization!==void 0)throw Error("Provide either --account or --organization, not both.");let r=e.account??e.organization;if(r!==void 0&&e.accountJson!==void 0)throw Error(e.organization!==void 0?"Provide either --organization or --account-json, not both.":"Provide either --account or --account-json, not both.");let o=r;if(e.accountJson!==void 0){try{o=JSON.parse(e.accountJson)}catch{throw Error("--account-json must be a JSON object with externalId.")}if(typeof o!=="object"||o===null||Array.isArray(o)||!("externalId"in o)||typeof o.externalId!=="string"||!o.externalId.trim())throw Error("--account-json must be a JSON object with externalId.")}else if(typeof o==="string"&&!o.trim())throw Error("--account must be a non-empty account external ID.");let a=await E("POST","/api/v1/subscribers/events",{...t,event:n,...o!==void 0?{account:o}:{},properties:Rv(e.property),customAttributes:Rv(e.attr),...e.occurredAt!==void 0?{occurredAt:e.occurredAt}:{},...e.eventId!==void 0?{eventId:e.eventId}:{}},e.company);if(e.json){S(a);return}let c=t.email??`external:${t.externalId}`,l=cEe(a);if(l)console.warn(`Warning: ${l}`);let p=sEe(a);if(p){console.log(p.duplicates>0?`Already recorded: ${n} for ${c} (no duplicate written)`:`Recorded historical event: ${n} for ${c} (no sequences enrolled)`);return}if(aEe(a)){console.log(`Already recorded: ${n} for ${c} (no duplicate written)`);return}let f=lEe(a);if(f.length>0){console.log(`Event recorded with side-effect failures: ${f.join(", ")}`);return}console.log(`Triggered event: ${n} for ${c}`)}async function pi(e,t){if(!await j())k(M()),process.exit(1);try{switch(e){case"list":await hEe(t);return;case"add":await yEe(t);return;case"update":await bEe(t);return;case"attributes":await dW(t);return;case"get":await vEe(t);return;case"notes:list":await EEe(t);return;case"notes:add":await IEe(t);return;case"notes:delete":await CEe(t);return;case"import":await AW(t);return;case"import:get":await hW(t);return;case"events:import":await mW(t);return;case"event":await SEe(t);return;case"remove":await wEe(t);return}}catch(n){let r=n instanceof A?n:new A(n instanceof Error?n.message:"Unknown error",500);k(r),process.exit(1)}}function DEe(e){let t=new URLSearchParams;if(e.search)t.set("search",e.search);if(e.page)t.set("page",e.page);if(e.limit)t.set("limit",e.limit);if(e.sort)t.set("sort",e.sort);if(e.order)t.set("order",e.order);return`/api/v1/suppressions${t.size>0?`?${t}`:""}`}function BEe(e){if(e.suppressions.length===0)return["No suppressed recipients found."];let t=e.suppressions.map((r)=>{let o=r.reason==="complaint"?"complaint":r.scope==="global"?"global":"workspace",a=r.reason==="complaint"?"reported as spam":r.bounceSubType??r.bounceType??"bounced",c=r.delistable?"":" (protected)";return`${r.email} [${o}] ${a} ${X(r.suppressedAt)}${c}`}),n=e.sortBy?` Sorted by ${e.sortBy} ${e.sortOrder??"desc"}.`:"";if(t.push(`
|
|
320
320
|
Showing ${e.suppressions.length} of ${e.total} (page ${e.page}).${n}`),e.hasMore)t.push(`Use --page ${e.page+1} for more.`);return t}function _Ee(e,t){let n=new URLSearchParams;if(t)n.set("region",t);return`/api/v1/suppressions/${encodeURIComponent(e)}${n.size>0?`?${n}`:""}`}function xEe(e){return[`Recipient: ${e.email}`,`Suppressed: ${e.suppressed?"Yes":"No"}`,`Associated with company: ${e.knownRecipient?"Yes":"No"}`,`Local suppression: ${e.local.suppressed?`${e.local.suppressionType??e.local.reason??"unknown"} (${e.local.scope??"unknown scope"}, ${e.local.delistable?"removable":"protected"})`:"None"}`]}async function Tv(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="list"){let o=await E("GET",DEe(t),void 0,t.company);if(t.json){S(o);return}for(let a of BEe(o))console.log(a);return}if(!t.email)throw new A("Recipient email is required",400);let n=_Ee(t.email,t.region);if(e==="get"){let o=await E("GET",n,void 0,t.company);if(t.json){S(o);return}for(let a of xEe(o.suppression))console.log(a);return}if(!await mt(`Remove the workspace soft-bounce escalation for ${t.email}? Global, complaint, and unsubscribe protections will be kept.`,t)){console.log("Aborted.");return}let r=await E("DELETE",n,void 0,t.company);if(t.json){S(r);return}if(console.log(r.removed?`Removed workspace soft-bounce escalation for ${r.email}.`:`No removable workspace soft-bounce escalation found for ${r.email}.`),r.reactivatedSubscriberIds.length>0)console.log(`Reactivated subscribers: ${r.reactivatedSubscriberIds.length}`);if(r.remainingSuppression.suppressed)console.log("The recipient remains suppressed by a protected global, complaint, or unsubscribe source.")}catch(n){k(n instanceof A?n:n),process.exit(1)}}function kEe(e){if(e.reset){if(e.rulesJson!==void 0||e.rulesFile!==void 0)throw new A("--reset cannot be combined with --rules",400);return{syncRules:null}}let t=Oe(e.rulesJson,e.rulesFile,"rules");if(t===void 0)throw new A("Provide --rules-json, --rules-file, or --reset",400);if(!Array.isArray(t))throw new A("rules JSON must be an array of sync rules",400);return{syncRules:t}}function REe(e){let t=[],n=e.conditions;if(!n)return t;if(n.requiresTags?.length)t.push(` Requires tags: ${n.requiresTags.join(", ")}`);if(n.requiresNotTags?.length)t.push(` Excluded tags: ${n.requiresNotTags.join(", ")}`);let r=n.purchasedProduct;if(r){let o=[];if(r.tags?.length)o.push(`tags ${r.tags.join("|")}`);if(r.collectionIds?.length)o.push(`collections ${r.collectionIds.join("|")}`);if(r.productTypes?.length)o.push(`types ${r.productTypes.join("|")}`);if(r.vendors?.length)o.push(`vendors ${r.vendors.join("|")}`);if(o.length>0)t.push(` Product match: ${o.join("; ")}`)}return t}function DW(e){console.log(`Sync rules (${e.syncRules.length})${e.isDefault?" - platform defaults":""}`);for(let t of e.syncRules){let n=t.actions.addTags.length?`+${t.actions.addTags.join(", +")}`:"",r=t.actions.removeTags.length?`-${t.actions.removeTags.join(", -")}`:"",o=[n,r].filter(Boolean).join(" ")||"(no-op)";console.log(`- ${t.triggerEvent}: ${o}`);for(let a of REe(t))console.log(a)}}async function XB(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="get"){let o=await E("GET","/api/v1/sync-rules",void 0,t.company);if(t.json){S(o);return}DW(o);return}let n=kEe(t),r=await E("PUT","/api/v1/sync-rules",n,t.company);if(t.json){S(r);return}if(r.message)console.log(r.message);DW(r)}catch(n){k(n instanceof A?n:n),process.exit(1)}}function TEe(e){let t=e.isSystem?" [system]":"";console.log(`- ${e.name} [${e.id}]${t}`),console.log(` Color: ${e.color??"Default"}`)}function QEe(e){if(!e.name||e.name.trim()==="")throw new A("Tag name is required",400);return{name:e.name,...e.color!==void 0&&{color:e.color}}}async function Rp(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="list"){let r=await E("GET","/api/v1/tags",void 0,t.company);if(t.json){S(r);return}console.log(`Tags (${r.tags.length})`);for(let o of r.tags)TEe(o);return}if(e==="create"){let r=QEe(t),o=await E("POST","/api/v1/tags",r,t.company);if(t.json){S(o);return}if(console.log(`Created tag: ${o.tag?.name??r.name}`),o.tag)console.log(`ID: ${o.tag.id}`),console.log(`Color: ${o.tag.color??"Default"}`);return}if(!t.tagId)throw new A("Tag ID is required",400);if(e==="update"){if(!t.color||t.color.trim()==="")throw new A("--color is required",400);let r=await E("PATCH",`/api/v1/tags/${encodeURIComponent(t.tagId)}`,{color:t.color},t.company);if(t.json){S(r);return}if(console.log(`Updated tag: ${r.tag?.name??t.tagId}`),r.tag)console.log(`ID: ${r.tag.id}`),console.log(`Color: ${r.tag.color??"Default"}`);return}if(!await mt(`Delete tag ${t.tagId}? It will be removed from all subscribers.`,t)){console.log("Aborted.");return}let n=await E("DELETE",`/api/v1/tags/${encodeURIComponent(t.tagId)}`,void 0,t.company);if(t.json){S(n);return}console.log(`Deleted tag: ${t.tagId}`)}catch(n){k(n instanceof A?n:n),process.exit(1)}}var $Ee=new Set(["admin","marketer","viewer","restricted"]);function NEe(e){if(!e.email||e.email.trim()==="")throw new A("Email is required",400);if(!e.role||!$Ee.has(e.role))throw new A("--role must be admin, marketer, viewer, or restricted",400);return{email:e.email.trim(),role:e.role,...e.billingAccess===!0&&{canManageBilling:!0}}}function OEe(e){let t=e.user.name?`${e.user.name} <${e.user.email}>`:e.user.email;if(console.log(`- ${t} [${e.id}]`),console.log(` Kind: ${e.kind}`),console.log(` Role: ${e.role}`),console.log(` Status: ${e.status}`),console.log(` Billing access: ${e.canManageBilling?"yes":"no"}`),e.invitedAt)console.log(` Invited: ${X(e.invitedAt)}`);if(e.expiresAt)console.log(` Expires: ${X(e.expiresAt)}`);if(e.invitedBy)console.log(` Invited by: ${e.invitedBy.name??e.invitedBy.email}`)}async function Qv(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="list"){let r=await E("GET","/api/v1/team",void 0,t.company);if(t.json){S(r);return}console.log(`Team members (${r.members.length})`);for(let o of r.members)OEe(o);return}if(e==="invite"){let r=NEe(t),o=await E("POST","/api/v1/team/invitations",r,t.company);if(t.json){S(o);return}if(o.invitation){console.log(`Invitation sent to ${o.invitation.email}`),console.log(`ID: ${o.invitation.id}`),console.log(`Role: ${o.invitation.role}`),console.log(`Billing access: ${o.invitation.canManageBilling?"yes":"no"}`),console.log(`Status: ${o.invitation.status}`),console.log(`Expires: ${X(o.invitation.expiresAt)}`);return}console.log(`Added team member: ${o.member?.email??r.email}`),console.log(`Role: ${o.member?.role??r.role}`),console.log(`Billing access: ${o.member?.canManageBilling?"yes":"no"}`);return}if(!t.invitationId)throw new A("Invitation ID is required",400);if(!await mt(`Cancel invitation ${t.invitationId}?`,t)){console.log("Aborted.");return}let n=await E("DELETE",`/api/v1/team/invitations/${encodeURIComponent(t.invitationId)}`,void 0,t.company);if(t.json){S(n);return}console.log(`Cancelled invitation: ${t.invitationId}`)}catch(n){k(n instanceof A?n:n),process.exit(1)}}function BW(e){if(e.length===0)return"none";return e.map((t)=>`${t.locale}:${t.status}${t.editedAt?" (edited)":""}`).join(", ")}function $v(e){return e&&e.length>0?e.join(", "):"None"}function Nv(e){return e?"yes":"no"}function PEe(e,t){if(e.name===void 0&&e.subject===void 0&&e.previewText===void 0&&e.label===void 0&&e.template===void 0&&t.html===void 0&&t.blocks===void 0)throw new A("Provide at least one of: --name, --subject, --preview-text, --label, --template/--no-template, --html, --html-file, --blocks-json, --blocks-file",400);return{name:e.name,subject:e.subject,previewText:e.previewText,html:t.html,blocks:t.blocks,labels:e.label,...e.template!==void 0&&{isTemplate:e.template}}}function qEe(e,t){let n=e.subject?.trim();if(!n)throw new A("Localization subject is required",400);if(t.html===void 0&&t.blocks===void 0)throw new A("Provide localized content with --html, --html-file, --blocks-json, or --blocks-file",400);return{subject:n,previewText:e.previewText,html:t.html,blocks:t.blocks,...e.keepEdits===!0&&{keepEdits:!0}}}async function xa(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="list"){let c=new URLSearchParams;if(t.label)for(let C of t.label)c.append("label",C);if(t.templatesOnly)c.set("isTemplate","true");let l=ot(t.limit,"--limit");if(l!==void 0)c.set("limit",String(l));let p=ot(t.offset,"--offset");if(p!==void 0){if(p<0)throw new A("--offset must be zero or greater",400);c.set("offset",String(p))}let f=await E("GET",`/api/v1/templates${c.size>0?`?${c.toString()}`:""}`,void 0,t.company),h=ct({companyId:f.companyId}),b=f.templates.map((C)=>Ds(C,{emailId:C.id},"email",f.companyId));if(t.json){S({...f,templates:b,appUrls:h.urls});return}console.log(`Templates (${f.templates.length})`);let v=f.pagination;if(v?.hasMore){let C=v.offset+v.count;console.log(`Showing ${v.count} of ${v.total}. Re-run with --offset ${C} for the next page.`)}if(f.emailLocalizationConfig)console.log(`Primary locale: ${f.emailLocalizationConfig.primaryLocale}`);for(let C of b)console.log(`- ${C.name} [${C.id}]`),console.log(` Subject: ${C.subject}`),console.log(` Format: ${Cs(C.emailPreset)}`),console.log(` Labels: ${$v(C.labels)}`),console.log(` Reusable template: ${Nv(C.isTemplate)}`),Ce(" URL",C.url),console.log(` Localizations: ${BW(C.localizations)}`);return}let n=ws({html:t.html,htmlFile:t.htmlFile,blocksJson:t.blocksJson,blocksFile:t.blocksFile});if(e==="create"){if(!t.name)throw new A("Template name is required",400);let c=t.prompt?.trim()||void 0;if([c,n.html,n.blocks].filter((v)=>v!==void 0).length!==1)throw new A("Provide exactly one of --prompt, --html/--html-file, or --blocks-json/--blocks-file",400);if(!c&&(t.style!==void 0||t.tone!==void 0))throw new A("--style and --tone require --prompt",400);if(!t.subject&&!c)throw new A("Template subject is required unless --prompt is provided",400);let p=await E("POST","/api/v1/templates",{name:t.name,subject:t.subject,previewText:t.previewText,prompt:c,style:t.style,tone:t.tone,html:n.html,blocks:n.blocks,labels:t.label,...t.template!==void 0&&{isTemplate:t.template}},t.company),f=await Gt(t.company),h=p.template?.id??p.templateId,b=f!==void 0&&h!==void 0?ct({companyId:f,emailId:h}):void 0;if(t.json){S({...p,...p.template!==void 0&&b?.urls.email!==void 0&&{template:{...p.template,url:b.urls.email}},...b!==void 0&&{appUrls:b.urls}});return}xn(p),console.log(`Created template: ${p.template?.name??t.name}`),console.log(`ID: ${p.template?.id??"Unknown"}`),Ce("URL",b?.urls.email),console.log(`Labels: ${$v(p.template?.labels)}`),console.log(`Reusable template: ${Nv(p.template?.isTemplate)}`),console.log(`Subject: ${p.template?.subject??t.subject??"Unknown"}`);return}if(!t.id)throw new A("Template ID is required",400);if(e==="set-localization"){if(!t.locale)throw new A("Localization locale is required",400);let c=await E("PUT",`/api/v1/templates/${t.id}/localizations/${encodeURIComponent(t.locale)}`,qEe(t,n),t.company),l=await Gt(t.company),p=l!==void 0?ct({companyId:l,emailId:c.templateId}):void 0;if(t.json){S({...c,...p!==void 0&&{appUrls:p.urls}});return}xn(c),console.log(`Set ${c.localization.locale} localization for template ${c.templateId}`),console.log(`Status: ${c.localization.status}`),console.log(`Subject: ${c.localization.subject}`),Ce("URL",p?.urls.email);return}if(e==="sync-localizations"){let c=await E("POST",`/api/v1/templates/${t.id}/localizations/sync`,{...t.locales!==void 0&&{locales:t.locales},...t.skipEdited===!0&&{skipEdited:!0}},t.company),l=await Gt(t.company),p=l!==void 0?ct({companyId:l,emailId:c.templateId}):void 0;if(t.json){S({...c,...p!==void 0&&{appUrls:p.urls}});return}console.log(c.queuedLocales.length>0?`Queued ${c.queuedVariantCount} localization${c.queuedVariantCount===1?"":"s"}: ${c.queuedLocales.join(", ")}`:"Queued 0 localizations");let f=c.skippedLocales??[];if(f.length>0)console.log(`Kept ${f.length} edited localization${f.length===1?"":"s"}: ${f.join(", ")}`);Ce("URL",p?.urls.email);return}if(e==="update"){let c=await E("PUT",`/api/v1/templates/${t.id}`,PEe(t,n),t.company),l=await Gt(t.company),p=l!==void 0?ct({companyId:l,emailId:t.id}):void 0;if(t.json){S({...c,...c.template!==void 0&&p?.urls.email!==void 0&&{template:{...c.template,url:p.urls.email}},...p!==void 0&&{appUrls:p.urls}});return}xn(c),console.log(`Updated template: ${c.template?.name??t.id}`),console.log(`ID: ${c.template?.id??t.id}`),Ce("URL",p?.urls.email),console.log(`Labels: ${$v(c.template?.labels)}`),console.log(`Reusable template: ${Nv(c.template?.isTemplate)}`),console.log(`Subject: ${c.template?.subject??"Unchanged"}`);return}if(e==="delete"){let c=await E("DELETE",`/api/v1/templates/${t.id}`,void 0,t.company);if(t.json){S(c);return}console.log(c.message??`Deleted template: ${t.id}`);return}if(e==="share"){let c=await E("POST",`/api/v1/templates/${t.id}/share-link`,void 0,t.company);if(t.json){S(c);return}console.log(c.created?"Public link created.":"Public link already active."),Ce("Share URL",c.shareUrl),console.log("Anyone with the link sees an anonymized copy - no subscriber data, no tracking.");return}if(e==="unshare"){let c=await E("DELETE",`/api/v1/templates/${t.id}/share-link`,void 0,t.company);if(t.json){S(c);return}console.log(c.revoked?"Public link revoked. The old URL now returns 404.":"No public link to revoke.");return}let r=await E("GET",`/api/v1/templates/${t.id}`,void 0,t.company),o=ct({companyId:r.template.companyId,emailId:t.id});if(t.json){S({...r,template:{...r.template,url:o.urls.email},appUrls:o.urls});return}let a=r.template;if(console.log(a.name),console.log(`ID: ${a.id}`),console.log(`Company: ${a.companyId}`),Ce("URL",o.urls.email),a.shareUrl)Ce("Share URL",a.shareUrl);console.log(`Subject: ${a.subject}`),console.log(`Labels: ${$v(a.labels)}`),console.log(`Reusable template: ${Nv(a.isTemplate)}`),console.log(`Preview: ${a.previewText??"None"}`),console.log(`Blocks: ${a.blocks.length}`),console.log(`Format: ${Cs(a.emailPreset)}`),console.log(`Font: ${a.fontFamily??"Default"}`),console.log(`Created: ${X(a.createdAt)}`),console.log(`Updated: ${X(a.updatedAt)}`),console.log(`Localizations: ${BW(a.localizations)}`);for(let c of a.localizations){let l=c.lastError?` | error: ${c.lastError}`:"";console.log(`- ${c.locale} [${c.status}${c.editedAt?", edited":""}] blocks=${c.blocks.length}${l}`)}}catch(n){k(n instanceof A?n:n),process.exit(1)}}function FEe(e){if(!e){console.log("Tracking domain: none (links use the shared Sequenzy domain)");return}if(console.log(`Tracking domain: ${e.domain}`),console.log(` Status: ${e.status}`),console.log(` Links: ${e.active?e.domain:"shared Sequenzy domain until it verifies"}`),e.sslStatus)console.log(` SSL: ${e.sslStatus}`);if(e.error)console.log(` Error: ${e.error}`);if(!e.active)console.log(` DNS: ${e.cnameRecord.name} CNAME ${e.cnameRecord.value}`)}async function LEe(e,t){if(!await j())k(M()),process.exit(1);try{let n;if(e==="show")n=await E("GET","/api/v1/tracking-domain",void 0,t.company);else if(e==="set"){let r=t.domain?.trim();if(!r)throw new A("Provide a tracking domain, like links.acme.com",400);n=await E("PUT","/api/v1/tracking-domain",{domain:r},t.company)}else if(e==="verify")n=await E("POST","/api/v1/tracking-domain/verify",void 0,t.company);else{if(!await mt("Remove the tracking domain? Links and images in emails already sent through it will stop working.",t)){console.log("Cancelled.");return}n=await E("DELETE","/api/v1/tracking-domain",void 0,t.company)}if(t.json){S(n);return}if(e==="remove"){console.log(n.removed?"Tracking domain removed. Links use the shared Sequenzy domain.":"No tracking domain was set.");return}if(n.message)console.log(n.message),console.log("");FEe(n.trackingDomain)}catch(n){k(n),process.exit(1)}}function _W(e,t=LEe){let n=(l)=>l.optsWithGlobals(),r=e.command("domain").description("Show the company tracking domain used by every sending domain").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").allowExcessArguments(!1).action((l,p)=>t("show",n(p)));D(r,{notes:["Every sending domain uses the company tracking domain for tracked links and opens. It never blocks sending: until it verifies, or when it breaks or is removed, links use the shared Sequenzy domain."],examples:["sequenzy tracking domain","sequenzy tracking domain set links.example.com","sequenzy tracking domain verify"]});let o=r.command("set <hostname>").description("Set or change the company tracking domain").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,p,f)=>t("set",{...n(f),domain:l}));D(o,{notes:["Any subdomain you control works (it does not have to match a sending domain), for example links.example.com. Add the returned CNAME record.","Changing it keeps the previous hostname serving links in emails already sent, as long as its old CNAME stays in place."],examples:["sequenzy tracking domain set links.example.com"]});let a=r.command("verify").description("Check the company tracking domain's DNS and HTTPS now").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,p)=>t("verify",n(p)));D(a,{examples:["sequenzy tracking domain verify"]});let c=r.command("remove").description("Remove the company tracking domain").option("-y, --yes","Skip the confirmation prompt").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((l,p)=>t("remove",n(p)));return D(c,{notes:["Links and images in emails already sent through the tracking domain stop working. New emails use the shared Sequenzy domain."],examples:["sequenzy tracking domain remove --yes"]}),r}function e_(e,t,n){if(e!==void 0&&!n.includes(e))throw new A(`${t} must be one of: ${n.join(", ")}`,400)}function UEe(e){e_(e.status,"--status",["all","active","disabled"]),e_(e.sort,"--sort",["date","sends","opens","open-rate","clicks","ctr"]),e_(e.order,"--order",["asc","desc"]);let t=new URLSearchParams;for(let n of e.label??[])t.append("label",n);if(e.search?.trim())t.set("search",e.search.trim());if(e.status)t.set("status",e.status);if(e.sort)t.set("sort",e.sort);if(e.order)t.set("order",e.order);if(e.includeBots)t.set("includeMachineEngagement","true");return t.size>0?`?${t.toString()}`:""}function jEe(e,t){if(e.previewText!==void 0&&e.clearPreviewText===!0)throw new A("Use either --preview-text or --clear-preview-text, not both",400);if(e.label!==void 0&&e.clearLabels)throw new A("Use either --label or --clear-labels, not both",400);let n=e.clearPreviewText===!0?null:void 0;if(e.label===void 0&&!e.clearLabels&&e.name===void 0&&e.subject===void 0&&e.previewText===void 0&&n===void 0&&e.enabled===void 0&&t.html===void 0&&t.blocks===void 0)throw new A("Provide at least one of: --name, --subject, --preview-text, --clear-preview-text, --enabled/--no-enabled, --label, --clear-labels, --html, --html-file, --blocks-json, --blocks-file",400);return{...e.label!==void 0&&{labels:e.label},...e.clearLabels&&{labels:[]},...e.name!==void 0&&{name:e.name},...e.subject!==void 0&&{subject:e.subject},...e.previewText!==void 0&&{previewText:e.previewText},...n===null&&{previewText:null},...e.enabled!==void 0&&{enabled:e.enabled},...t.html!==void 0&&{html:t.html},...t.blocks!==void 0&&{blocks:t.blocks}}}async function Tp(e,t){if(!await j())k(M()),process.exit(1);try{if(e==="create"){if(!t.name)throw new A("Transactional name is required",400);let o=ws({html:t.html,htmlFile:t.htmlFile,blocksJson:t.blocksJson,blocksFile:t.blocksFile}),a=t.prompt?.trim()||void 0;if([a,o.html,o.blocks].filter((h)=>h!==void 0).length!==1)throw new A("Provide exactly one of --prompt, --html/--html-file, or --blocks-json/--blocks-file",400);if(!a&&!t.subject)throw new A("Transactional subject is required unless --prompt is provided",400);if(!a&&(t.style!==void 0||t.tone!==void 0))throw new A("--style and --tone require --prompt",400);let l=await E("POST","/api/v1/transactional",{name:t.name,...t.label!==void 0&&{labels:t.label},...t.slug!==void 0&&{slug:t.slug},...t.subject!==void 0&&{subject:t.subject},...t.previewText!==void 0&&{previewText:t.previewText},...a!==void 0&&{prompt:a},...t.style!==void 0&&{style:t.style},...t.tone!==void 0&&{tone:t.tone},...o.html!==void 0&&{html:o.html},...o.blocks!==void 0&&{blocks:o.blocks},...t.enabled!==void 0&&{enabled:t.enabled}},t.company),p=await Gt(t.company),f=p?ct({companyId:p,transactionalId:l.transactional.id}).urls.transactionalEmail:void 0;if(t.json){S({...l,transactional:{...l.transactional,url:f},...f&&{appUrls:{transactionalEmail:f}}});return}xn(l),console.log(`Created transactional template: ${l.transactional.name}`),console.log(`ID: ${l.transactional.id}`),console.log(`Slug: ${l.transactional.slug}`),console.log(`Enabled: ${l.transactional.enabled?"yes":"no"}`),console.log(`Labels: ${l.transactional.labels?.join(", ")||"None"}`),Ce("URL",f);return}if(e==="list"){let o=await E("GET",`/api/v1/transactional${UEe(t)}`,void 0,t.company),a=await Gt(t.company),c=o.transactional.map((p)=>Ds(p,{transactionalId:p.id},"transactionalEmail",a)),l=ct({companyId:a});if(t.json){S({...o,transactional:c,appUrls:l.urls});return}console.log(`Transactional templates (${o.transactional.length})`);for(let p of c)console.log(`- ${p.name} [${p.slug}] ${p.enabled?"enabled":"disabled"}${p.managedBy==="code"?" · managed in code":""}`),console.log(` Subject: ${p.subject??"Unknown"}`),console.log(` Labels: ${p.labels?.join(", ")||"None"}`),console.log(` Format: ${Cs(p.emailPreset)}`),console.log(` Sends: ${p.stats.sends} · Opens: ${p.stats.opens} (${p.stats.openRate.toFixed(2)}%) · Clicks: ${p.stats.clicks} (${p.stats.clickRate.toFixed(2)}%)`),Ce(" URL",p.url);return}if(!t.slug)throw new A("Transactional template slug is required",400);if(e==="update"){let o=ws({html:t.html,htmlFile:t.htmlFile,blocksJson:t.blocksJson,blocksFile:t.blocksFile}),a=await E("PATCH",`/api/v1/transactional/${encodeURIComponent(t.slug)}`,jEe(t,o),t.company),c=await Gt(t.company),l=c?ct({companyId:c,transactionalId:a.transactional.id}).urls.transactionalEmail:void 0;if(t.json){S({...a,transactional:{...a.transactional,url:l},...l&&{appUrls:{transactionalEmail:l}}});return}if(xn(a),console.log(`Updated transactional template: ${a.transactional.name}`),console.log(`ID: ${a.transactional.id}`),console.log(`Slug: ${a.transactional.slug}`),console.log(`Enabled: ${a.transactional.enabled?"yes":"no"}`),console.log(`Labels: ${a.transactional.labels?.join(", ")||"None"}`),a.transactional.subject)console.log(`Subject: ${a.transactional.subject}`);Ce("URL",l);return}if(e==="delete"){if(!await mt(`Delete transactional template ${t.slug}?`,t)){console.log("Aborted.");return}let o=await E("DELETE",`/api/v1/transactional/${encodeURIComponent(t.slug)}`,void 0,t.company);if(t.json){S(o);return}if(console.log(`Deleted transactional template: ${o.deleted?.name??t.slug}`),console.log(`Slug: ${o.deleted?.slug??t.slug}`),o.deleted?.emailDeleted)console.log("Code-managed content snapshot deleted with it");else if(o.deleted?.emailId)console.log(`Email content kept as a template: ${o.deleted.emailId}`);return}let n=await E("GET",`/api/v1/transactional/${encodeURIComponent(t.slug)}`,void 0,t.company);if(t.json){S(n);return}let r=n.transactional;if(console.log(r.name),console.log(`ID: ${r.id}`),console.log(`Slug: ${r.slug}`),console.log(`Enabled: ${r.enabled?"yes":"no"}`),r.managedBy==="code")console.log(`Managed in code: sends with --track-as ${r.slug}; content is a snapshot of a recent send`);if(r.subject)console.log(`Subject: ${r.subject}`);if(console.log(`Labels: ${r.labels?.join(", ")||"None"}`),console.log(`Format: ${Cs(r.emailPreset)}`),(r.variables?.length??0)>0)console.log(`Variables: ${r.variables?.join(", ")}`)}catch(n){k(n instanceof A?n:n),process.exit(1)}}import{readFileSync as zEe}from"node:fs";var xW=["snowflake","bigquery","redshift","postgres"],MEe=["subscribers","events"],kW=["every_15_minutes","hourly","daily","weekly","manual"],RW=["confirmed","double_opt_in"],bl="SEQUENZY_WAREHOUSE_PASSWORD";function ko(e){k(new A(e,400)),process.exit(1)}function dg(e,t){if(!e||e.trim().length===0)ko(`${t} is required.`);return e.trim()}function Qp(e,t,n){if(e===void 0)return;if(!t.includes(e))ko(`Invalid ${n} "${e}". Use one of: ${t.join(", ")}.`);return e}function pg(e,t){try{return zEe(e,"utf8")}catch{ko(`Could not read ${t} file "${e}".`)}}function Ov(e,t){let n;try{n=JSON.parse(e)}catch{ko(`${t} must be valid JSON.`)}if(!n||typeof n!=="object"||Array.isArray(n))ko(`${t} must be a JSON object.`);return n}function TW(e){let t=e.configJson?Ov(e.configJson,"--config-json"):{},n=[["account","account"],["username","username"],["warehouse","warehouse"],["database","database"],["schema","schema"],["role","role"],["projectId","projectId"],["location","location"],["host","host"],["sslMode","sslMode"]];for(let[r,o]of n){let a=e[r];if(typeof a==="string")t[o]=a}if(e.port!==void 0){let r=Number(e.port);if(!Number.isInteger(r))ko("--port must be a number.");t.port=r}return t}function QW(e,t="create"){let n=e.credentialsFile?Ov(pg(e.credentialsFile,"--credentials-file"),"--credentials-file"):{};if(e.privateKeyFile)n.privateKey=pg(e.privateKeyFile,"--private-key-file");if(e.privateKeyPassphrase)n.privateKeyPassphrase=e.privateKeyPassphrase;if(e.serviceAccountFile)n.serviceAccountJson=pg(e.serviceAccountFile,"--service-account-file");let r=t==="create"||e.passwordFromEnv?process.env[bl]:void 0;if(t==="update"&&e.passwordFromEnv&&!r)ko(`--password-from-env needs ${bl} to be set.`);let o=e.password??r;if(o)n.password=o;return Object.keys(n).length>0?n:void 0}function r_(e,t){if(e.query&&e.queryFile)ko("Use either --query or --query-file, not both.");let n=e.queryFile?pg(e.queryFile,"--query-file"):e.query;if(t&&!n?.trim())ko("--query or --query-file is required.");return n}function $W(e){if(e.mappingJson&&e.mappingFile)ko("Use either --mapping-json or --mapping-file, not both.");if(e.mappingFile)return Ov(pg(e.mappingFile,"--mapping-file"),"--mapping-file");return e.mappingJson?Ov(e.mappingJson,"--mapping-json"):void 0}function NW(e){if(e===void 0)return;return e.split(",").map((t)=>t.trim()).filter(Boolean)}function t_(e){let t=e.config.host??e.config.account??e.config.projectId??"";if(console.log(`- ${e.name} (${e.provider}) ${String(t)}`),console.log(` id: ${e.id} | status: ${e.status} | syncs: ${e.syncCount??0} | tested: ${e.lastTestedAt??"never"}`),e.lastError)console.log(` last error: ${e.lastError}`)}function OW(e){if(e.status==="running")return`running, ${e.rowsRead} rows read so far`;return`${e.status}: ${e.rowsRead} read, ${e.rowsSynced} synced, ${e.rowsUnchanged} unchanged, ${e.rowsSkipped} skipped, ${e.rowsFailed} failed`}function n_(e){let t=!e.isEnabled?"paused":e.status;if(console.log(`- ${e.name} (${e.kind})`),console.log(` id: ${e.id} | connection: ${e.connectionId} | ${e.frequency} | status: ${t}${e.cursorColumn?` | cursor: ${e.cursorColumn} >= ${e.cursorValue??"start"}`:""}`),console.log(` last success: ${e.lastSuccessAt??"never"} | next run: ${e.nextRunAt??"not scheduled"}`),e.latestRun)console.log(` latest run ${OW(e.latestRun)}`);if(e.lastError)console.log(` last error: ${e.lastError}`)}async function PW(){if(!await j())k(M()),process.exit(1)}function qW(e){return(t,n)=>{if(e.json){console.log(JSON.stringify(t,null,2));return}n()}}async function vl(e,t){await PW();let n=qW(t);try{if(e==="list"){let a=await E("GET","/api/v1/warehouse-connections",void 0,t.company);n(a,()=>{console.log(`Warehouse connections (${a.connections.length})`),a.connections.forEach(t_)});return}if(e==="create"){let a=Qp(t.provider,xW,"--provider");if(!a)ko(`--provider is required (${xW.join(", ")}).`);let c=QW(t);if(!c)ko(`Provide credentials: --private-key-file (Snowflake), --service-account-file (BigQuery), ${bl} or --password (Redshift/Postgres), or --credentials-file.`);let l=await E("POST","/api/v1/warehouse-connections",{name:dg(t.name,"--name"),provider:a,config:TW(t),credentials:c},t.company);n(l,()=>{console.log(`Connected ${l.connection.name} (${l.connection.id}).`),console.log("The test query succeeded. Create a sync with `sequenzy warehouse syncs create`.")});return}let r=encodeURIComponent(dg(t.id,"<id>"));if(e==="get"){let a=await E("GET",`/api/v1/warehouse-connections/${r}`,void 0,t.company);n(a,()=>t_(a.connection));return}if(e==="update"){let a=TW(t),c=QW(t,"update"),l={...t.name!==void 0?{name:t.name}:{},...Object.keys(a).length>0?{config:a}:{},...c?{credentials:c}:{}};if(Object.keys(l).length===0)ko("Nothing to update. Pass --name, connection settings or new credentials.");let p=await E("PATCH",`/api/v1/warehouse-connections/${r}`,l,t.company);n(p,()=>{console.log(`Updated ${p.connection.name}.`),t_(p.connection)});return}if(e==="delete"){if(!await mt(`Delete warehouse connection ${decodeURIComponent(r)}?`,t)){console.log("Cancelled.");return}let c=await E("DELETE",`/api/v1/warehouse-connections/${r}`,void 0,t.company);n(c,()=>console.log(`Deleted connection ${c.connectionId}.`));return}if(e==="test"){let a=await E("POST",`/api/v1/warehouse-connections/${r}/test`,void 0,t.company);n(a,()=>console.log(`Connection works (${a.connection.name}).`));return}let o=await E("POST",`/api/v1/warehouse-connections/${r}/preview`,{query:r_(t,!0)},t.company);n(o,()=>{console.log(`Columns: ${o.columns.map((a)=>`${a.name} (${a.type})`).join(", ")}`),console.log(`First ${o.rows.length} row(s):`);for(let a of o.rows)console.log(` ${JSON.stringify(a)}`)})}catch(r){k(r),process.exit(1)}}async function El(e,t){await PW();let n=qW(t);try{if(e==="list"){let c=t.connection?`?connectionId=${encodeURIComponent(t.connection)}`:"",l=await E("GET",`/api/v1/warehouse-syncs${c}`,void 0,t.company);n(l,()=>{console.log(`Warehouse syncs (${l.syncs.length})`),l.syncs.forEach(n_)});return}if(e==="create"){let c=$W(t);if(!c)ko("--mapping-json or --mapping-file is required.");let l=Qp(t.frequency,kW,"--frequency"),p=Qp(t.optInMode,RW,"--opt-in-mode"),f=NW(t.lists),h=await E("POST","/api/v1/warehouse-syncs",{connectionId:dg(t.connection,"--connection"),name:dg(t.name,"--name"),kind:Qp(t.kind,MEe,"--kind")??"subscribers",query:r_(t,!0),mapping:c,...t.cursorColumn?{cursorColumn:t.cursorColumn}:{},...l?{frequency:l}:{},...f?{listIds:f}:{},...p?{optInMode:p}:{},...t.triggerAutomations?{triggerAutomations:!0}:{}},t.company);n(h,()=>{console.log(`Created sync ${h.sync.name} (${h.sync.id}).`),console.log(`The first run is starting. Follow it with \`sequenzy warehouse syncs runs ${h.sync.id}\`.`)});return}let r=encodeURIComponent(dg(t.id,"<id>"));if(e==="get"){let c=await E("GET",`/api/v1/warehouse-syncs/${r}`,void 0,t.company);n(c,()=>n_(c.sync));return}if(e==="update"){let c={};if(t.name!==void 0)c.name=t.name;let l=r_(t,!1);if(l!==void 0)c.query=l;let p=$W(t);if(p)c.mapping=p;if(t.cursorColumn!==void 0)c.cursorColumn=t.cursorColumn===""?null:t.cursorColumn;let f=Qp(t.frequency,kW,"--frequency");if(f)c.frequency=f;let h=NW(t.lists);if(h)c.listIds=h;let b=Qp(t.optInMode,RW,"--opt-in-mode");if(b)c.optInMode=b;if(t.triggerAutomations!==void 0)c.triggerAutomations=t.triggerAutomations;if(t.enabled!==void 0){if(t.enabled!=="true"&&t.enabled!=="false")ko('--enabled must be "true" or "false".');c.isEnabled=t.enabled==="true"}if(Object.keys(c).length===0)ko("Nothing to update.");let v=await E("PATCH",`/api/v1/warehouse-syncs/${r}`,c,t.company);n(v,()=>{console.log(`Updated ${v.sync.name}.`),n_(v.sync)});return}if(e==="delete"){if(!await mt(`Delete warehouse sync ${decodeURIComponent(r)}? Imported contacts and events stay.`,t)){console.log("Cancelled.");return}let l=await E("DELETE",`/api/v1/warehouse-syncs/${r}`,void 0,t.company);n(l,()=>console.log(`Deleted sync ${l.syncId}.`));return}if(e==="run"){let c=await E("POST",`/api/v1/warehouse-syncs/${r}/run`,t.fullResync?{fullResync:!0}:{},t.company);n(c,()=>console.log(`${t.fullResync?"Full resync":"Run"} queued for ${c.sync.name}. Follow it with \`sequenzy warehouse syncs runs ${c.sync.id}\`.`));return}let o=t.limit?`?limit=${encodeURIComponent(t.limit)}`:"",a=await E("GET",`/api/v1/warehouse-syncs/${r}/runs${o}`,void 0,t.company);n(a,()=>{console.log(`Recent runs (${a.runs.length})`);for(let c of a.runs){let l=c.isFullResync?" (full resync)":c.isManual?" (manual)":"";console.log(`- ${c.startedAt}${l} ${OW(c)}`);for(let p of c.imports)console.log(` import ${p.status}: ${p.processedCount}/${p.totalRows}`);for(let p of c.errorSamples.slice(0,5))console.log(` row ${p.row}: ${p.reason}`);if(c.error)console.log(` error: ${c.error}`)}})}catch(r){k(r),process.exit(1)}}var HEe={requested:"Waiting to be added",collecting:"Collecting emails",available:"Watching",declined:"Not added"};function FW(e){return e.slice(0,16).replace("T"," ")}function LW(e){let t=e.status==="available"?`${e.emailCount} ${e.emailCount===1?"email":"emails"}${e.latestEmailAt?`, latest ${FW(e.latestEmailAt)} UTC`:""}`:null,n=e.status==="declined"?e.declineReason:e.note;return[`${e.brand?.name??e.domain} (${e.domain}) · ${HEe[e.status]}${t?` · ${t}`:""}`,n?` ${n}`:null,` ID: ${e.id}`].filter(Boolean).join(`
|