@sequenzy/cli 0.0.177 → 0.0.178
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(T,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} />`,Ts,bi,$s,bi),mc[bi+Ts]=!0}}if(T===n)Pr(dn);else No(dn);return dn}}var fr=_l;Khe.Fragment=n,Khe.jsxDEV=fr})()});var tw={};HZ(tw,{program:()=>zR,createCommand:()=>MR,createOption:()=>HR,createArgument:()=>GR,Command:()=>JR,Option:()=>VR,Argument:()=>KR,Help:()=>WR,CommanderError:()=>ZR,InvalidArgumentError:()=>YR,InvalidOptionArgumentError:()=>XR},{program:(GSe)=>zR=GSe,createCommand:(GSe)=>MR=GSe,createOption:(GSe)=>HR=GSe,createArgument:(GSe)=>GR=GSe,Command:(GSe)=>JR=GSe,Option:(GSe)=>VR=GSe,Argument:(GSe)=>KR=GSe,Help:(GSe)=>WR=GSe,CommanderError:(GSe)=>ZR=GSe,InvalidArgumentError:(GSe)=>YR=GSe,InvalidOptionArgumentError:(GSe)=>XR=GSe});var{Argument:LR}=ch(),{Command:ew}=qR(),{CommanderError:EY,InvalidArgumentError:UR}=qm(),{Help:IY}=WC(),{Option:jR}=ZC();var zR=new ew,MR=(e)=>new ew(e),HR=(e,t)=>new jR(e,t),GR=(e,t)=>new LR(e,t),JR=ew,VR=jR,KR=LR,WR=IY,ZR=EY,YR=UR,XR=UR;var{program:VSe,createCommand:KSe,createArgument:WSe,createOption:ZSe,CommanderError:eQ,InvalidArgumentError:YSe,InvalidOptionArgumentError:XSe,Command:tQ,Argument:e0e,Option:t0e,Help:n0e}=tw;var lh={name:"@sequenzy/cli",version:"0.0.177",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 Oae}from"node:util";import Vq from"node:process";import iu from"node:fs";import Kq from"node:path";import df from"node:crypto";import Pae from"node:assert";var Yl=(e)=>{let t=typeof e;return e!==null&&(t==="object"||t==="function")};var nw=new Set(["__proto__","prototype","constructor"]),wY=new Set("0123456789");function uh(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(nw.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(nw.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"&&!wY.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(nw.has(n))return[];t.push(n);break}case"index":throw Error("Index was not closed");case"start":{t.push("");break}}return t}function rw(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 nQ(e,t){if(rw(e,t))throw Error("Cannot use string index")}function rQ(e,t,n){if(!Yl(e)||typeof t!=="string")return n===void 0?e:n;let r=uh(t);if(r.length===0)return n;for(let o=0;o<r.length;o++){let a=r[o];if(rw(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 ow(e,t,n){if(!Yl(e)||typeof t!=="string")return e;let r=e,o=uh(t);for(let a=0;a<o.length;a++){let c=o[a];if(nQ(e,c),a===o.length-1)e[c]=n;else if(!Yl(e[c]))e[c]=typeof o[a+1]==="number"?[]:{};e=e[c]}return r}function oQ(e,t){if(!Yl(e)||typeof t!=="string")return!1;let n=uh(t);for(let r=0;r<n.length;r++){let o=n[r];if(nQ(e,o),r===n.length-1)return delete e[o],!0;if(e=e[o],!Yl(e))return!1}}function iQ(e,t){if(!Yl(e)||typeof t!=="string")return!1;let n=uh(t);if(n.length===0)return!1;for(let r of n){if(!Yl(e)||!(r in e)||rw(e,r))return!1;e=e[r]}return!0}import Zn from"node:path";import sQ from"node:os";import iw from"node:process";var Tc=sQ.homedir(),sw=sQ.tmpdir(),{env:Ed}=iw,SY=(e)=>{let t=Zn.join(Tc,"Library");return{data:Zn.join(t,"Application Support",e),config:Zn.join(t,"Preferences",e),cache:Zn.join(t,"Caches",e),log:Zn.join(t,"Logs",e),temp:Zn.join(sw,e)}},DY=(e)=>{let t=Ed.APPDATA||Zn.join(Tc,"AppData","Roaming"),n=Ed.LOCALAPPDATA||Zn.join(Tc,"AppData","Local");return{data:Zn.join(n,e,"Data"),config:Zn.join(t,e,"Config"),cache:Zn.join(n,e,"Cache"),log:Zn.join(n,e,"Log"),temp:Zn.join(sw,e)}},BY=(e)=>{let t=Zn.basename(Tc);return{data:Zn.join(Ed.XDG_DATA_HOME||Zn.join(Tc,".local","share"),e),config:Zn.join(Ed.XDG_CONFIG_HOME||Zn.join(Tc,".config"),e),cache:Zn.join(Ed.XDG_CACHE_HOME||Zn.join(Tc,".cache"),e),log:Zn.join(Ed.XDG_STATE_HOME||Zn.join(Tc,".local","state"),e),temp:Zn.join(sw,t,e)}};function aw(e,{suffix:t="nodejs"}={}){if(typeof e!=="string")throw TypeError(`Expected a string, got ${typeof e}`);if(t)e+=`-${t}`;if(iw.platform==="darwin")return SY(e);if(iw.platform==="win32")return DY(e);return BY(e)}import NY from"node:path";import nn from"node:fs";import{promisify as wo}from"node:util";var xY=(e,t)=>{let{onError:n}=t;return function(...o){return e.apply(void 0,o).catch(n)}},ra=xY;var _Y=(e,t)=>{let{onError:n}=t;return function(...o){try{return e.apply(void 0,o)}catch(a){return n(a)}}},bs=_Y;var aQ=250;var kY=(e,t)=>{let{isRetriable:n}=t;return function(o){let{timeout:a}=o,c=o.interval??aQ,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 y=Math.round(c*Math.random());if(y>0)return new Promise((C)=>setTimeout(C,y)).then(()=>p.apply(void 0,f));else return p.apply(void 0,f)})}}},oa=kY;var RY=(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=RY;import lQ from"node:process";var Lm={isChangeErrorOk:(e)=>{if(!Lm.isNodeError(e))return!1;let{code:t}=e;if(t==="ENOSYS")return!0;if(!cQ&&(t==="EINVAL"||t==="EPERM"))return!0;return!1},isNodeError:(e)=>e instanceof Error,isRetriableError:(e)=>{if(!Lm.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(!Lm.isNodeError(e))throw e;if(Lm.isChangeErrorOk(e))return;throw e}},cw=Lm;var Um={onError:cw.onChangeError},ri={onError:()=>{return}},cQ=lQ.getuid?!lQ.getuid():!1,Ao={isRetriable:cw.isRetriableError};var QY={attempt:{chmod:ra(wo(nn.chmod),Um),chown:ra(wo(nn.chown),Um),close:ra(wo(nn.close),ri),fsync:ra(wo(nn.fsync),ri),mkdir:ra(wo(nn.mkdir),ri),realpath:ra(wo(nn.realpath),ri),stat:ra(wo(nn.stat),ri),unlink:ra(wo(nn.unlink),ri),chmodSync:bs(nn.chmodSync,Um),chownSync:bs(nn.chownSync,Um),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(wo(nn.close),Ao),fsync:oa(wo(nn.fsync),Ao),open:oa(wo(nn.open),Ao),readFile:oa(wo(nn.readFile),Ao),rename:oa(wo(nn.rename),Ao),stat:oa(wo(nn.stat),Ao),write:oa(wo(nn.write),Ao),writeFile:oa(wo(nn.writeFile),Ao),closeSync:ia(nn.closeSync,Ao),fsyncSync:ia(nn.fsyncSync,Ao),openSync:ia(nn.openSync,Ao),readFileSync:ia(nn.readFileSync,Ao),renameSync:ia(nn.renameSync,Ao),statSync:ia(nn.statSync,Ao),writeSync:ia(nn.writeSync,Ao),writeFileSync:ia(nn.writeFileSync,Ao)}},Xr=QY;import Xl from"node:process";var uQ="utf8",lw=438,dQ=511;var pQ={},mQ=Xl.geteuid?Xl.geteuid():-1,fQ=Xl.getegid?Xl.getegid():-1;var gQ=1000,AQ=!!Xl.getuid,T0e=Xl.getuid?!Xl.getuid():!1,uw=128;var hQ=(e)=>e instanceof Error&&("code"in e);var dw=(e)=>typeof e==="string",dh=(e)=>e===void 0;import $Y from"node:path";import Id from"node:process";import yQ from"node:process";var bQ=yQ.platform==="linux",ph=yQ.platform==="win32";var pw=["SIGHUP","SIGINT","SIGTERM"];if(!ph)pw.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(bQ)pw.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var vQ=pw;class EQ{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(ph&&(e!=="SIGINT"&&e!=="SIGTERM"&&e!=="SIGKILL"))Id.kill(Id.pid,"SIGTERM");else Id.kill(Id.pid,e)},this.hook=()=>{Id.once("exit",()=>this.exit());for(let e of vQ)try{Id.once(e,()=>this.exit(e))}catch{}},this.register=(e)=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}}var IQ=new EQ;var TY=IQ.register,CQ=TY;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=$Y.basename(e);if(t.length<=uw)return e;let n=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(t);if(!n)return e;let r=t.length-uw;return`${e.slice(0,-t.length)}${n[1]}${n[2].slice(0,-r)}${n[3]}`}};CQ(Bi.purgeSyncAll);var jm=Bi;function mw(e,t,n=pQ){if(dw(n))return mw(e,t,{encoding:n});let o={timeout:n.timeout??gQ},a=null,c=null,l=null;try{let p=Xr.attempt.realpathSync(e),f=!!p;e=p||e,[c,a]=jm.get(e,n.tmpCreate||jm.create,n.tmpPurge!==!1);let h=AQ&&dh(n.chown),y=dh(n.mode);if(f&&(h||y)){let v=Xr.attempt.statSync(e);if(v){if(n={...n},h)n.chown={uid:v.uid,gid:v.gid};if(y)n.mode=v.mode}}if(!f){let v=NY.dirname(e);Xr.attempt.mkdirSync(v,{mode:dQ,recursive:!0})}if(l=Xr.retry.openSync(o)(c,"w",n.mode||lw),n.tmpCreated)n.tmpCreated(c);if(dw(t))Xr.retry.writeSync(o)(l,t,0,n.encoding||uQ);else if(!dh(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!==mQ||n.chown.gid!==fQ))Xr.attempt.chownSync(c,n.chown.uid,n.chown.gid);if(n.mode&&n.mode!==lw)Xr.attempt.chmodSync(c,n.mode);try{Xr.retry.renameSync(o)(c,e)}catch(v){if(!hQ(v))throw v;if(v.code!=="ENAMETOOLONG")throw v;Xr.retry.renameSync(o)(c,jm.truncate(e))}a(),c=null}finally{if(l)Xr.attempt.closeSync(l);if(c)jm.purge(c)}}var Zq=yt($P(),1),Yq=yt(nF(),1);var _oe=(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(!koe(o,a)&&r)return;Object.defineProperty(e,n,a)},koe=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)},Roe=(e,t)=>{let n=Object.getPrototypeOf(t);if(n===Object.getPrototypeOf(e))return;Object.setPrototypeOf(e,n)},Qoe=(e,t)=>`/* Wrapped ${e}*/
|
|
194
|
+
<%s key={someKey} {...props} />`,Ts,bi,$s,bi),mc[bi+Ts]=!0}}if(T===n)Pr(dn);else No(dn);return dn}}var fr=_l;Khe.Fragment=n,Khe.jsxDEV=fr})()});var tw={};HZ(tw,{program:()=>zR,createCommand:()=>MR,createOption:()=>HR,createArgument:()=>GR,Command:()=>JR,Option:()=>VR,Argument:()=>KR,Help:()=>WR,CommanderError:()=>ZR,InvalidArgumentError:()=>YR,InvalidOptionArgumentError:()=>XR},{program:(GSe)=>zR=GSe,createCommand:(GSe)=>MR=GSe,createOption:(GSe)=>HR=GSe,createArgument:(GSe)=>GR=GSe,Command:(GSe)=>JR=GSe,Option:(GSe)=>VR=GSe,Argument:(GSe)=>KR=GSe,Help:(GSe)=>WR=GSe,CommanderError:(GSe)=>ZR=GSe,InvalidArgumentError:(GSe)=>YR=GSe,InvalidOptionArgumentError:(GSe)=>XR=GSe});var{Argument:LR}=ch(),{Command:ew}=qR(),{CommanderError:EY,InvalidArgumentError:UR}=qm(),{Help:IY}=WC(),{Option:jR}=ZC();var zR=new ew,MR=(e)=>new ew(e),HR=(e,t)=>new jR(e,t),GR=(e,t)=>new LR(e,t),JR=ew,VR=jR,KR=LR,WR=IY,ZR=EY,YR=UR,XR=UR;var{program:VSe,createCommand:KSe,createArgument:WSe,createOption:ZSe,CommanderError:eQ,InvalidArgumentError:YSe,InvalidOptionArgumentError:XSe,Command:tQ,Argument:e0e,Option:t0e,Help:n0e}=tw;var lh={name:"@sequenzy/cli",version:"0.0.178",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 Oae}from"node:util";import Vq from"node:process";import iu from"node:fs";import Kq from"node:path";import df from"node:crypto";import Pae from"node:assert";var Yl=(e)=>{let t=typeof e;return e!==null&&(t==="object"||t==="function")};var nw=new Set(["__proto__","prototype","constructor"]),wY=new Set("0123456789");function uh(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(nw.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(nw.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"&&!wY.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(nw.has(n))return[];t.push(n);break}case"index":throw Error("Index was not closed");case"start":{t.push("");break}}return t}function rw(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 nQ(e,t){if(rw(e,t))throw Error("Cannot use string index")}function rQ(e,t,n){if(!Yl(e)||typeof t!=="string")return n===void 0?e:n;let r=uh(t);if(r.length===0)return n;for(let o=0;o<r.length;o++){let a=r[o];if(rw(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 ow(e,t,n){if(!Yl(e)||typeof t!=="string")return e;let r=e,o=uh(t);for(let a=0;a<o.length;a++){let c=o[a];if(nQ(e,c),a===o.length-1)e[c]=n;else if(!Yl(e[c]))e[c]=typeof o[a+1]==="number"?[]:{};e=e[c]}return r}function oQ(e,t){if(!Yl(e)||typeof t!=="string")return!1;let n=uh(t);for(let r=0;r<n.length;r++){let o=n[r];if(nQ(e,o),r===n.length-1)return delete e[o],!0;if(e=e[o],!Yl(e))return!1}}function iQ(e,t){if(!Yl(e)||typeof t!=="string")return!1;let n=uh(t);if(n.length===0)return!1;for(let r of n){if(!Yl(e)||!(r in e)||rw(e,r))return!1;e=e[r]}return!0}import Zn from"node:path";import sQ from"node:os";import iw from"node:process";var Tc=sQ.homedir(),sw=sQ.tmpdir(),{env:Ed}=iw,SY=(e)=>{let t=Zn.join(Tc,"Library");return{data:Zn.join(t,"Application Support",e),config:Zn.join(t,"Preferences",e),cache:Zn.join(t,"Caches",e),log:Zn.join(t,"Logs",e),temp:Zn.join(sw,e)}},DY=(e)=>{let t=Ed.APPDATA||Zn.join(Tc,"AppData","Roaming"),n=Ed.LOCALAPPDATA||Zn.join(Tc,"AppData","Local");return{data:Zn.join(n,e,"Data"),config:Zn.join(t,e,"Config"),cache:Zn.join(n,e,"Cache"),log:Zn.join(n,e,"Log"),temp:Zn.join(sw,e)}},BY=(e)=>{let t=Zn.basename(Tc);return{data:Zn.join(Ed.XDG_DATA_HOME||Zn.join(Tc,".local","share"),e),config:Zn.join(Ed.XDG_CONFIG_HOME||Zn.join(Tc,".config"),e),cache:Zn.join(Ed.XDG_CACHE_HOME||Zn.join(Tc,".cache"),e),log:Zn.join(Ed.XDG_STATE_HOME||Zn.join(Tc,".local","state"),e),temp:Zn.join(sw,t,e)}};function aw(e,{suffix:t="nodejs"}={}){if(typeof e!=="string")throw TypeError(`Expected a string, got ${typeof e}`);if(t)e+=`-${t}`;if(iw.platform==="darwin")return SY(e);if(iw.platform==="win32")return DY(e);return BY(e)}import NY from"node:path";import nn from"node:fs";import{promisify as wo}from"node:util";var xY=(e,t)=>{let{onError:n}=t;return function(...o){return e.apply(void 0,o).catch(n)}},ra=xY;var _Y=(e,t)=>{let{onError:n}=t;return function(...o){try{return e.apply(void 0,o)}catch(a){return n(a)}}},bs=_Y;var aQ=250;var kY=(e,t)=>{let{isRetriable:n}=t;return function(o){let{timeout:a}=o,c=o.interval??aQ,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 y=Math.round(c*Math.random());if(y>0)return new Promise((C)=>setTimeout(C,y)).then(()=>p.apply(void 0,f));else return p.apply(void 0,f)})}}},oa=kY;var RY=(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=RY;import lQ from"node:process";var Lm={isChangeErrorOk:(e)=>{if(!Lm.isNodeError(e))return!1;let{code:t}=e;if(t==="ENOSYS")return!0;if(!cQ&&(t==="EINVAL"||t==="EPERM"))return!0;return!1},isNodeError:(e)=>e instanceof Error,isRetriableError:(e)=>{if(!Lm.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(!Lm.isNodeError(e))throw e;if(Lm.isChangeErrorOk(e))return;throw e}},cw=Lm;var Um={onError:cw.onChangeError},ri={onError:()=>{return}},cQ=lQ.getuid?!lQ.getuid():!1,Ao={isRetriable:cw.isRetriableError};var QY={attempt:{chmod:ra(wo(nn.chmod),Um),chown:ra(wo(nn.chown),Um),close:ra(wo(nn.close),ri),fsync:ra(wo(nn.fsync),ri),mkdir:ra(wo(nn.mkdir),ri),realpath:ra(wo(nn.realpath),ri),stat:ra(wo(nn.stat),ri),unlink:ra(wo(nn.unlink),ri),chmodSync:bs(nn.chmodSync,Um),chownSync:bs(nn.chownSync,Um),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(wo(nn.close),Ao),fsync:oa(wo(nn.fsync),Ao),open:oa(wo(nn.open),Ao),readFile:oa(wo(nn.readFile),Ao),rename:oa(wo(nn.rename),Ao),stat:oa(wo(nn.stat),Ao),write:oa(wo(nn.write),Ao),writeFile:oa(wo(nn.writeFile),Ao),closeSync:ia(nn.closeSync,Ao),fsyncSync:ia(nn.fsyncSync,Ao),openSync:ia(nn.openSync,Ao),readFileSync:ia(nn.readFileSync,Ao),renameSync:ia(nn.renameSync,Ao),statSync:ia(nn.statSync,Ao),writeSync:ia(nn.writeSync,Ao),writeFileSync:ia(nn.writeFileSync,Ao)}},Xr=QY;import Xl from"node:process";var uQ="utf8",lw=438,dQ=511;var pQ={},mQ=Xl.geteuid?Xl.geteuid():-1,fQ=Xl.getegid?Xl.getegid():-1;var gQ=1000,AQ=!!Xl.getuid,T0e=Xl.getuid?!Xl.getuid():!1,uw=128;var hQ=(e)=>e instanceof Error&&("code"in e);var dw=(e)=>typeof e==="string",dh=(e)=>e===void 0;import $Y from"node:path";import Id from"node:process";import yQ from"node:process";var bQ=yQ.platform==="linux",ph=yQ.platform==="win32";var pw=["SIGHUP","SIGINT","SIGTERM"];if(!ph)pw.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(bQ)pw.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var vQ=pw;class EQ{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(ph&&(e!=="SIGINT"&&e!=="SIGTERM"&&e!=="SIGKILL"))Id.kill(Id.pid,"SIGTERM");else Id.kill(Id.pid,e)},this.hook=()=>{Id.once("exit",()=>this.exit());for(let e of vQ)try{Id.once(e,()=>this.exit(e))}catch{}},this.register=(e)=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}}var IQ=new EQ;var TY=IQ.register,CQ=TY;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=$Y.basename(e);if(t.length<=uw)return e;let n=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(t);if(!n)return e;let r=t.length-uw;return`${e.slice(0,-t.length)}${n[1]}${n[2].slice(0,-r)}${n[3]}`}};CQ(Bi.purgeSyncAll);var jm=Bi;function mw(e,t,n=pQ){if(dw(n))return mw(e,t,{encoding:n});let o={timeout:n.timeout??gQ},a=null,c=null,l=null;try{let p=Xr.attempt.realpathSync(e),f=!!p;e=p||e,[c,a]=jm.get(e,n.tmpCreate||jm.create,n.tmpPurge!==!1);let h=AQ&&dh(n.chown),y=dh(n.mode);if(f&&(h||y)){let v=Xr.attempt.statSync(e);if(v){if(n={...n},h)n.chown={uid:v.uid,gid:v.gid};if(y)n.mode=v.mode}}if(!f){let v=NY.dirname(e);Xr.attempt.mkdirSync(v,{mode:dQ,recursive:!0})}if(l=Xr.retry.openSync(o)(c,"w",n.mode||lw),n.tmpCreated)n.tmpCreated(c);if(dw(t))Xr.retry.writeSync(o)(l,t,0,n.encoding||uQ);else if(!dh(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!==mQ||n.chown.gid!==fQ))Xr.attempt.chownSync(c,n.chown.uid,n.chown.gid);if(n.mode&&n.mode!==lw)Xr.attempt.chmodSync(c,n.mode);try{Xr.retry.renameSync(o)(c,e)}catch(v){if(!hQ(v))throw v;if(v.code!=="ENAMETOOLONG")throw v;Xr.retry.renameSync(o)(c,jm.truncate(e))}a(),c=null}finally{if(l)Xr.attempt.closeSync(l);if(c)jm.purge(c)}}var Zq=yt($P(),1),Yq=yt(nF(),1);var _oe=(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(!koe(o,a)&&r)return;Object.defineProperty(e,n,a)},koe=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)},Roe=(e,t)=>{let n=Object.getPrototypeOf(t);if(n===Object.getPrototypeOf(e))return;Object.setPrototypeOf(e,n)},Qoe=(e,t)=>`/* Wrapped ${e}*/
|
|
195
195
|
${t}`,Toe=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),$oe=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Noe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=Qoe.bind(null,r,t.toString());Object.defineProperty(o,"name",$oe);let{writable:a,enumerable:c,configurable:l}=Toe;Object.defineProperty(e,"toString",{value:o,writable:a,enumerable:c,configurable:l})};function gS(e,t,{ignoreNonConfigurable:n=!1}={}){let{name:r}=e;for(let o of Reflect.ownKeys(t))_oe(e,t,o,n);return Roe(e,t),Noe(e,t,r),e}var Ooe=(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 y=this,v=()=>{if(c=void 0,l)clearTimeout(l),l=void 0;if(a)p=e.apply(y,h)},C=()=>{if(l=void 0,c)clearTimeout(c),c=void 0;if(a)p=e.apply(y,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(y,h);return p};return gS(f,e),f.cancel=()=>{if(c)clearTimeout(c),c=void 0;if(l)clearTimeout(l),l=void 0},f},AS=Ooe;var su=yt(Mq(),1);var _ae=Object.prototype.toString;function Gq(e,t,n){if(!e)return!1;if(e.constructor===t)return!0;return _ae.call(e)===n}function Jq(e){return Gq(e,Uint8Array,"[object Uint8Array]")}function kae(e){return Gq(e,ArrayBuffer,"[object ArrayBuffer]")}function Rae(e){return Jq(e)||kae(e)}function Qae(e){if(!Jq(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function Tae(e){if(!Rae(e))throw TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``)}function kS(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)Qae(o),n.set(o,r),r+=o.length;return n}var Hq={utf8:new globalThis.TextDecoder("utf8")};function RS(e,t="utf8"){return Tae(e),Hq[t]??=new globalThis.TextDecoder(t),Hq[t].decode(e)}function $ae(e){if(typeof e!=="string")throw TypeError(`Expected \`string\`, got \`${typeof e}\``)}var Nae=new globalThis.TextEncoder;function wy(e){return $ae(e),Nae.encode(e)}var v_e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));var Fae=Yq.default.default,Wq="aes-256-cbc",Kd=()=>Object.create(null),qae=(e)=>e!==void 0&&e!==null,Lae=(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`)},Sy="__internal__",QS=`${Sy}.migrations.version`;class Dy{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=aw(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 Zq.Ajv2020({allErrors:!0,useDefaults:!0,...t.ajvOptions});Fae(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=Kq.resolve(t.cwd,`${t.configName??"config"}${n}`);let r=this.store,o=Object.assign(Kd(),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{Pae.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 ${Sy} key, as it's used to manage this module internal operations.`);let{store:n}=this,r=(o,a)=>{if(Lae(o,a),this.#e.accessPropertiesByDotNotation)ow(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 iQ(this.store,e);return e in this.store}reset(...e){for(let t of e)if(qae(this.#n[t]))this.set(t,this.#n[t])}delete(e){let{store:t}=this;if(this.#e.accessPropertiesByDotNotation)oQ(t,e);else delete t[e];this.store=t}clear(){this.store=Kd();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=iu.readFileSync(this.path,this.#t?null:"utf8"),t=this._encryptData(e),n=this._deserialize(t);return this._validate(n),Object.assign(Kd(),n)}catch(e){if(e?.code==="ENOENT")return this._ensureDirectory(),Kd();if(this.#e.clearInvalidConfig&&e.name==="SyntaxError")return Kd();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:RS(e);try{let t=e.slice(0,16),n=df.pbkdf2Sync(this.#t,t.toString(),1e4,32,"sha512"),r=df.createDecipheriv(Wq,n,t),o=e.slice(17),a=typeof o==="string"?wy(o):o;return RS(kS([r.update(a),r.final()]))}catch{}return e.toString()}_handleChange(e,t){let n=e(),r=()=>{let o=n,a=e();if(Oae(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(){iu.mkdirSync(Kq.dirname(this.path),{recursive:!0})}_write(e){let t=this._serialize(e);if(this.#t){let n=df.randomBytes(16),r=df.pbkdf2Sync(this.#t,n.toString(),1e4,32,"sha512"),o=df.createCipheriv(Wq,r,n);t=kS([n,wy(":"),o.update(wy(t)),o.final()])}if(Vq.env.SNAP)iu.writeFileSync(this.path,t,{mode:this.#e.configFileMode});else try{mw(this.path,t,{mode:this.#e.configFileMode})}catch(n){if(n?.code==="EXDEV"){iu.writeFileSync(this.path,t,{mode:this.#e.configFileMode});return}throw n}}_watch(){if(this._ensureDirectory(),!iu.existsSync(this.path))this._write(Kd());if(Vq.platform==="win32")iu.watch(this.path,{persistent:!1},AS(()=>{this.events.dispatchEvent(new Event("change"))},{wait:100}));else iu.watchFile(this.path,{persistent:!1},AS(()=>{this.events.dispatchEvent(new Event("change"))},{wait:5000}))}_migrate(e,t,n){let r=this._get(QS,"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(QS,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)||!su.default.eq(r,t))this._set(QS,t)}_containsReservedKey(e){if(typeof e==="object"){if(Object.keys(e)[0]===Sy)return!0}if(typeof e!=="string")return!1;if(this.#e.accessPropertiesByDotNotation){if(e.startsWith(`${Sy}.`))return!0;return!1}return!1}_isVersionInRangeFormat(e){return su.default.clean(e)===null}_shouldPerformMigration(e,t,n){if(this._isVersionInRangeFormat(e)){if(t!=="0.0.0"&&su.default.satisfies(t,e))return!1;return su.default.satisfies(n,e)}if(su.default.lte(e,t))return!1;if(su.default.gt(e,n))return!1;return!0}_get(e,t){return rQ(this.store,e,t)}_set(e,t){let{store:n}=this;ow(n,e,t),this.store=n}}var TS="com.sequenzy.cli",$S="api-key",NS=typeof globalThis.Bun<"u",el=new Dy({projectName:"sequenzy",schema:{userId:{type:"string"},userEmail:{type:"string"},_apiKey:{type:"string"}}});async function OS(){let e=process.env.SEQUENZY_API_KEY;if(e)return e;if(NS)try{let t=await globalThis.Bun.secrets.get({service:TS,name:$S});if(t)return t}catch{}return el.get("_apiKey")}async function Xq(e){if(NS)try{await globalThis.Bun.secrets.set({service:TS,name:$S,value:e,allowUnrestrictedAccess:!1});return}catch{}el.set("_apiKey",e)}async function e1(){if(NS)try{await globalThis.Bun.secrets.delete({service:TS,name:$S})}catch{}el.delete("_apiKey")}async function H(){return!!await OS()}function By(){return{userId:el.get("userId"),userEmail:el.get("userEmail")}}function t1(e){if(e.userId!==void 0)el.set("userId",e.userId);if(e.userEmail!==void 0)el.set("userEmail",e.userEmail)}function n1(){el.clear()}function r1(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 o1(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 Uae=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 jae(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 zae(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"?jae(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 OS();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/${lh.version}`};if(r)c["x-company-id"]=r;Object.assign(c,o);let l;try{l=await fetch(`${Uae}${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=zae(p);throw new A(f.message,l.status,p,f.code,r1(l.headers.get("Retry-After")))}return l.json()}var i1=!1;function PS(e){i1=e}function xy(){return i1}var qS="https://docs.sequenzy.com",Va=`${qS}/concepts/cli`,FS=`${qS}/authentication`,s1="https://sequenzy.com/dashboard";function a1(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 Mae(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 c1(e){let t=a1(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:Va,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:Va,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:FS,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:FS,details:o};let a=Mae(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 ${s1} 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 ${s1} 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:Va,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:FS,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:Va,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:Va,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:`${qS}/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:Va,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:Va,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:Va,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:Va,details:o}}function J(){return new A("Not logged in. Run `sequenzy login` first.",401,void 0,"CLI_AUTH_REQUIRED")}function pf(e){let t=c1(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 Hae(e){let t=a1(e),n=c1(e),r=(t.rawDetails===t.message?n.description:t.message.trim())||n.description;return{success:!1,error:{code:o1(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??xy()?JSON.stringify(Hae(e)):pf(e))}import{readFileSync as Gae}from"node:fs";import{isatty as l1}from"node:tty";var tl;function u1(){tl=void 0}function LS(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 d1(){if(l1(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);tl={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 p1(e,t){if(e==="-"){if(tl){if(tl.field)LS([tl.field,t]);return tl.field=t,tl.text}if(l1(0))throw new A(`Pipe text into stdin when using ${t} file '-'.`,400,void 0,"CLI_INVALID_INPUT")}try{let n=Gae(e==="-"?0:e,"utf8");if(e==="-")tl={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 _y(e){return e.optsWithGlobals().json===!0||e.commands.some(_y)}async function Jae(e){PS(e.optsWithGlobals().json===!0),u1();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(LS(t),t.length>0)await d1()}function m1(e){let t=e.configureOutput().writeErr;e.configureOutput({writeErr:(n)=>{if(!_y(e))t?.(n)}}),e.exitOverride(),e.hook("preAction",(n,r)=>Jae(r))}async function f1(e,t){PS(!1);try{await e.parseAsync(t)}catch(n){if(n instanceof eQ){if(n.exitCode===0)return;if(_y(e))k(new A(n.message,400,void 0,"CLI_INVALID_INPUT"),{json:!0});process.exitCode=n.exitCode;return}k(n,{json:_y(e)}),process.exitCode=1}}var ky="Variant copy is edited with `sequenzy ab-tests update-variant`, not with `sequenzy sequences update-node`.";var g1;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 y=0;y<h.length;y++){let v=h[y];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 rke=Symbol("zod_brand");class Ka extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class mf extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(g1=globalThis).__zod_globalConfig??(g1.__zod_globalConfig={});var Wd=globalThis.__zod_globalConfig;function Wa(e){if(e)Object.assign(Wd,e);return Wd}function Qy(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 gf(e,t){if(typeof t==="bigint")return t.toString();return t}function Ty(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function $y(e){return e===null||e===void 0}function Ny(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var A1=Symbol("evaluating");function hn(e,t,n){let r=void 0;Object.defineProperty(e,t,{get(){if(r===A1)return;if(r===void 0)r=A1,r=n();return r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function au(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function nl(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function jS(e){return JSON.stringify(e)}function h1(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var zS="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ff(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var y1=Ty(()=>{if(Wd.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Zd(e){if(ff(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(ff(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function MS(e){if(Zd(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 b1=new Set(["string","number","symbol"]);function rl(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 v1(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Vae={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 Kae(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=nl(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 au(this,"shape",c),c},checks:[]});return va(e,a)}function Wae(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=nl(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 au(this,"shape",c),c},checks:[]});return va(e,a)}function Zae(e,t){if(!Zd(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=nl(e._zod.def,{get shape(){let a={...e._zod.def.shape,...t};return au(this,"shape",a),a}});return va(e,o)}function Yae(e,t){if(!Zd(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=nl(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return au(this,"shape",r),r}});return va(e,n)}function Xae(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=nl(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return au(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return va(e,n)}function ece(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=nl(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 au(this,"shape",p),p},checks:[]});return va(t,c)}function tce(e,t,n){let r=nl(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 au(this,"shape",a),a}});return va(t,r)}function cu(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 E1(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 Oy(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ry(e){return typeof e==="string"?e:e?.message}function Za(e,t,n){let r=e.message?e.message:Ry(e.inst?._zod.def?.error?.(e))??Ry(t?.error?.(e))??Ry(n.customError?.(e))??Ry(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 Py(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function lu(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}var I1=(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,gf,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Fy=ce("$ZodError",I1),HS=ce("$ZodError",I1,{Parent:Error});function C1(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 w1(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 qy=(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 Ka;if(c.issues.length){let l=new(o?.Err??e)(c.issues.map((p)=>Za(p,a,Wa())));throw zS(l,o?.callee),l}return c.value};var Ly=(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)=>Za(p,a,Wa())));throw zS(l,o?.callee),l}return c.value};var Af=(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 Ka;return a.issues.length?{success:!1,error:new(e??Fy)(a.issues.map((c)=>Za(c,o,Wa())))}:{success:!0,data:a.value}},S1=Af(HS),hf=(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)=>Za(c,o,Wa())))}:{success:!0,data:a.value}},D1=hf(HS),B1=(e)=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return qy(e)(t,n,o)};var x1=(e)=>(t,n,r)=>qy(e)(t,n,r);var _1=(e)=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Ly(e)(t,n,o)};var k1=(e)=>async(t,n,r)=>Ly(e)(t,n,r);var R1=(e)=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Af(e)(t,n,o)};var Q1=(e)=>(t,n,r)=>Af(e)(t,n,r);var T1=(e)=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return hf(e)(t,n,o)};var $1=(e)=>async(t,n,r)=>hf(e)(t,n,r);var N1=/^[cC][0-9a-z]{6,}$/,O1=/^[0-9a-z]+$/,P1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,F1=/^[0-9a-vA-V]{20}$/,q1=/^[A-Za-z0-9]{27}$/,L1=/^[a-zA-Z0-9_-]{21}$/,U1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var j1=/^([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})$/,GS=(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 z1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var rce="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function M1(){return new RegExp(rce,"u")}var H1=/^(?:(?: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])$/,G1=/^(([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 J1=/^((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])$/,V1=/^(([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])$/,K1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,JS=/^[A-Za-z0-9_-]*$/;var W1=/^https?$/,Z1=/^\+[1-9]\d{6,14}$/,Y1="(?:(?:\\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])))",X1=new RegExp(`^${Y1}$`);function eL(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 tL(e){return new RegExp(`^${eL(e)}$`)}function nL(e){let t=eL({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(`^${Y1}T(?:${r})$`)}var rL=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var oL=/^[^A-Z]*$/,iL=/^[^a-z]*$/;var xi=ce("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var sL=ce("$ZodCheckMaxLength",(e,t)=>{var n;xi.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let o=r.value;return!$y(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=Py(o);r.issues.push({origin:c,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),aL=ce("$ZodCheckMinLength",(e,t)=>{var n;xi.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let o=r.value;return!$y(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=Py(o);r.issues.push({origin:c,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),cL=ce("$ZodCheckLengthEquals",(e,t)=>{var n;xi.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let o=r.value;return!$y(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=Py(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})}}),yf=ce("$ZodCheckStringFormat",(e,t)=>{var n,r;if(xi.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=()=>{})}),lL=ce("$ZodCheckRegex",(e,t)=>{yf.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})}}),uL=ce("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=oL),yf.init(e,t)}),dL=ce("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=iL),yf.init(e,t)}),pL=ce("$ZodCheckIncludes",(e,t)=>{xi.init(e,t);let n=rl(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})}}),mL=ce("$ZodCheckStartsWith",(e,t)=>{xi.init(e,t);let n=new RegExp(`^${rl(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})}}),fL=ce("$ZodCheckEndsWith",(e,t)=>{xi.init(e,t);let n=new RegExp(`.*${rl(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 gL=ce("$ZodCheckOverwrite",(e,t)=>{xi.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class VS{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(`
|
|
@@ -263,7 +263,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
263
263
|
${e}:
|
|
264
264
|
${t.map((n)=>` ${n}`).join(`
|
|
265
265
|
`)}
|
|
266
|
-
`}function S(e,t){let n=t.notes??[],r=t.examples??[],o=Bz("Notes",n)+Bz("Examples",r);if(o.trim().length>0)e.addHelpText("after",o);return e}var bue={high:"FIX FIRST",medium:"WORTH FIXING",low:"HOUSEKEEPING"};function xz(e){if(!e.enabled)return"off";return`Mondays at 05:00 UTC, ${e.autonomy==="draft_fixes"?"drafts fixes":"report only"}`}function vue(e,t){let n=t.targetId??"";switch(t.kind){case"create_sequence":return`sequenzy account-health fix ${e.id}`;case"activate_sequence":return`sequenzy sequences enable ${n}`;case"pause_sequence":return`sequenzy sequences disable ${n}`;case"verify_sending_domain":return`sequenzy websites verify ${e.subjectName??n}`;default:return`dashboard: ${t.path??"/"}`}}function Eue(e){let t=e.status==="snoozed"?" (snoozed)":"";console.log(`- [${bue[e.severity]}] ${e.title}${t}`),console.log(` ${e.detail}`),console.log(` Fix: ${e.recommendation}`);for(let n of e.actions??[])console.log(` ${n.primary?"Do":"Or"}: ${n.label} -> ${vue(e,n)}`);console.log(` ID: ${e.id}`)}function Iue(e){if(!e.eligibility.eligible){let{minimumActiveSubscribers:n,activityDays:r,hasMinimumSubscribers:o}=e.eligibility;console.log(`Account health checks run for workspaces with more than ${n.toLocaleString("en-US")} active subscribers that sent email in the last ${r} days.`),console.log(o?`This workspace has not sent email in the last ${r} days.`:`This workspace has ${n.toLocaleString("en-US")} or fewer active subscribers.`);return}if(console.log(`Checks: ${xz(e.settings)}`),e.nextRunAt)console.log(`Next check: ${e.nextRunAt}`);let t=e.latestRun;if(e.runInProgress)console.log("A check is running now.");else if(t)console.log(`Last check: ${t.status} at ${t.completedAt??t.createdAt}`);if(t?.status==="completed"&&t.summary)console.log(""),console.log(t.summary);if(console.log(""),e.insights.length===0){console.log(t?"Nothing to fix.":"No check has run yet. Run one with `sequenzy account-health run`.");return}for(let n of e.insights)Eue(n)}function Cue(e,t){console.log(t?`A check is already ${e.status} (${e.id}).`:`Check queued (${e.id}). It usually finishes within a minute; see the result with \`sequenzy account-health\`.`)}function wue(e){let t={};if(e.enabled!==void 0)t.enabled=e.enabled;if(e.autonomy!==void 0)t.autonomy=e.autonomy;if(Object.keys(t).length===0)throw new A("Pass at least one setting to change",400);let n=Sz(t);if(!n.ok)throw new A(n.error,400);return t}async function Sue(e,t){if(!await H())k(J()),process.exit(1);try{if(e.kind==="get"){let o=await E("GET","/api/v1/account-health",void 0,t.company);if(t.json)return D(o);Iue(o.accountHealth);return}if(e.kind==="settings"){let o=await E("PATCH","/api/v1/account-health/settings",wue(t),t.company);if(t.json)return D(o);if(console.log(`Checks: ${xz(o.settings)}`),o.nextRunAt)console.log(`Next check: ${o.nextRunAt}`);return}if(e.kind==="run"){let o=await E("POST","/api/v1/account-health/runs",void 0,t.company);if(t.json)return D(o);Cue(o.run,o.alreadyInProgress);return}if(e.kind==="fix"){let o=await E("POST",`/api/v1/account-health/insights/${encodeURIComponent(e.insightId)}/fix`,void 0,t.company);if(t.json)return D(o);let a=`review it with \`sequenzy sequences get ${o.sequenceId}\`, then turn it on with \`sequenzy sequences enable ${o.sequenceId}\``;console.log(!o.created?`A draft for this already exists: ${o.sequenceId}.`:o.enrichmentStatus==="not_queued"?`Built draft sequence ${o.sequenceId}, but its emails could not start writing. Open it in the dashboard to write them, then ${a}.`:`Built draft sequence ${o.sequenceId}. Its emails are being written now; ${a}.`);return}if(!Dz(e.action))throw new A(`Unknown action "${e.action}". Use one of: ${tb.join(", ")}.`,400);let n={action:e.action};if(t.snoozeDays!==void 0)n.snoozeDays=Number(t.snoozeDays);let r=await E("PATCH",`/api/v1/account-health/insights/${encodeURIComponent(e.insightId)}`,n,t.company);if(t.json)return D(r);console.log(`${r.insight.title}: ${r.insight.status}`)}catch(n){k(n),process.exit(1)}}function _z(e,t=Sue){let n=(h)=>h.optsWithGlobals(),r=(h)=>h.option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON"),o=r(e.command("account-health").description("Show the account health report: what to fix in your email setup").allowExcessArguments(!1)).action((h,y)=>t({kind:"get"},n(y)));S(o,{notes:["An AI agent checks the workspace every Monday at 05:00 UTC and lists gaps: events nothing reacts to, sequences that stopped enrolling, campaign gaps, weak sequence emails, deliverability spikes and failing domains.","Workspaces need more than 1,000 active subscribers and an email sent in the last 14 days. Drafted fixes are inactive sequences; nothing is sent or activated for you."],examples:["sequenzy account-health","sequenzy account-health run","sequenzy account-health settings --autonomy report_only","sequenzy account-health insight <id> snooze --snooze-days 30"]});let a=r(o.command("get").description("Show the account health report")).action((h,y)=>t({kind:"get"},n(y)));S(a,{examples:["sequenzy account-health get --json"]});let c=r(o.command("settings").description("Turn weekly checks on or off and choose whether they draft fixes").option("--enabled","Turn weekly checks on").option("--no-enabled","Turn weekly checks off").option("--autonomy <level>","draft_fixes or report_only")).action((h,y)=>t({kind:"settings"},n(y)));S(c,{notes:["Checks run every Monday at 05:00 UTC, before the Monday weekly report that carries the findings. Who gets them is each person's own setting: sequenzy notifications set --account-health off|instant."],examples:["sequenzy account-health settings --no-enabled","sequenzy account-health settings --enabled --autonomy report_only"]});let l=r(o.command("run").description("Run a check now")).action((h,y)=>t({kind:"run"},n(y)));S(l,{notes:["Manual checks are limited to one every 10 minutes, wait a day after a check that left findings open, and never send the report email."],examples:["sequenzy account-health run"]});let p=r(o.command("fix <insightId>").description("Build the draft sequence a finding asks for (events with no sequence)")).action((h,y,v)=>t({kind:"fix",insightId:h},n(v)));S(p,{notes:["Creates an inactive draft triggered by the event, with its timing and titled email steps, and writes the emails with AI like a template. Review them, then enable it. Running it again returns the same draft without rewriting it."],examples:["sequenzy account-health fix ins_123"]});let f=r(o.command("insight <insightId> <action>").description(`Act on a finding: ${tb.join(", ")}`).option("--snooze-days <days>","Days to snooze (1-90, default 7)")).action((h,y,v,C)=>t({kind:"insight",insightId:h,action:y},n(C)));return S(f,{notes:["resolve marks it fixed; it reopens if the next check still finds it. dismiss hides it for good."],examples:["sequenzy account-health insight ins_123 dismiss","sequenzy account-health insight ins_123 snooze --snooze-days 30"]}),o}var S0=["product-info","email-design","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],kz={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",account:"/dashboard/company/{companyId}/account",subscription:"/dashboard/company/{companyId}/account?tab=subscription",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function Due(e){let n=(e??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return n.length>0?n:"https://sequenzy.com"}function Ss(e){let t=e?.trim();return t?t:void 0}function Ia(e){return encodeURIComponent(e)}function cr(e,t){return`${e}${t}`}function lr(e,t=""){return`/dashboard/company/${Ia(e)}${t}`}function Rz(e,t,n){return cr(e,`${lr(t,"/settings")}?tab=${encodeURIComponent(n)}`)}function Bue(e,t){let n=S0.map((r)=>[r,t?Rz(e,t,r):""]);return Object.fromEntries(n)}function ct(e={},t){let n=Due(t),r=Ss(e.companyId),o={},a=Bue(n,r);if(!r)return{appUrl:n,routeTemplates:kz,settingsTabValues:S0,urls:o,settingsUrls:a};o.dashboard=cr(n,lr(r)),o.campaigns=cr(n,lr(r,"/campaign")),o.landingPages=cr(n,lr(r,"/landing-pages")),o.sequences=cr(n,lr(r,"/sequences")),o.account=cr(n,lr(r,"/account")),o.subscription=`${o.account}?tab=subscription`,o.settings=cr(n,lr(r,"/settings")),o.emails=cr(n,lr(r,"/emails")),o.subscribers=cr(n,lr(r,"/subscribers")),o.sentEmails=cr(n,lr(r,"/sent-emails")),o.segments=cr(n,lr(r,"/segments")),o.metrics=cr(n,lr(r,"/metrics")),o.transactional=cr(n,lr(r,"/transactional"));let c=Ss(e.campaignId);if(c)o.campaign=cr(n,lr(r,`/campaign/${Ia(c)}`)),o.campaignPreview=`${o.campaign}?step=review`;let l=Ss(e.landingPageId);if(l)o.landingPage=cr(n,lr(r,`/landing-pages/${Ia(l)}`));let p=Ss(e.sequenceId);if(p)o.sequence=cr(n,lr(r,`/sequences/${Ia(p)}`));let f=Ss(e.emailId)??Ss(e.templateId);if(f)o.email=cr(n,lr(r,`/emails/${Ia(f)}`)),o.template=o.email;let h=Ss(e.transactionalId);if(h)o.transactionalEmail=cr(n,lr(r,`/transactional/${Ia(h)}`));let y=Ss(e.emailSendId);if(y)o.emailSend=cr(n,lr(r,`/sent-emails/${Ia(y)}`));let v=Ss(e.domainId);if(v)o.domain=cr(n,lr(r,`/settings/domain/${Ia(v)}`)),o.domainVerify=`${o.domain}/verify`;let C=Ss(e.status);if(C)o.campaignList=cr(n,lr(r,`/campaign/list/${Ia(C)}`)),o.sequenceList=cr(n,lr(r,`/sequences/list/${Ia(C)}`));let R=Ss(e.settingsTab);if(R)o.settingsTab=R==="billing"||R==="subscription"?o.subscription:Rz(n,r,R);return{appUrl:n,routeTemplates:kz,settingsTabValues:S0,urls:o,settingsUrls:a}}async function Ht(e){if(e?.trim())return e.trim();try{return(await E("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function xue(e,t){let n=await Ht(t);return ct({...e,companyId:n})}function Ce(e,t){if(t)console.log(`${e}: ${t}`)}function Ds(e,t,n,r){let a=ct({...t,companyId:r}).urls[n];return{...e,...a!==void 0&&{url:a}}}async function Qz(e){if(!await H())k(J()),process.exit(1);try{let t=await xue({campaignId:e.campaign,landingPageId:e.landingPage,sequenceId:e.sequence,emailId:e.email,templateId:e.template,transactionalId:e.transactional,emailSendId:e.emailSend,domainId:e.domain,status:e.status,settingsTab:e.settingsTab},e.company);if(e.company&&!t.urls.dashboard)throw new A("Company ID is required to build dashboard URLs",400);if(e.json){D(t);return}if(console.log(`App: ${t.appUrl}`),console.log(""),Object.keys(t.urls).length===0){console.log("No company selected. Pass --company or run `sequenzy account` to find the current company ID."),console.log(""),console.log("Route templates:");for(let[n,r]of Object.entries(t.routeTemplates))console.log(`- ${n}: ${r}`);return}console.log("URLs:");for(let[n,r]of Object.entries(t.urls))console.log(`- ${n}: ${r}`);console.log(""),console.log("Settings tabs:");for(let[n,r]of Object.entries(t.settingsUrls))console.log(`- ${n}: ${r}`)}catch(t){k(t instanceof A?t:t),process.exit(1)}}function _ue(e){let t=du(e.scopes),n={preset:e.preset??t.preset,fullAccess:e.fullAccess??t.fullAccess,selectedScopeCount:e.selectedScopeCount??t.selectedScopeCount,currentScopeCount:e.currentScopeCount??t.currentScopeCount,description:e.description??t.description},r=e.activeKey;if(console.log("API key"),r)console.log(`- Name: ${r.name??"Unknown"}`),console.log(`- ID: ${r.id}`),console.log(`- Prefix: ${r.prefix??"Unknown"}`),console.log(`- Type: ${r.type??"Unknown"}`);if(console.log(`- Permission preset: ${n.preset}`),console.log(`- Full access: ${n.fullAccess?"yes":"no"}`),console.log(`- Permissions: ${n.description}`),e.scopes!==null)console.log(`- Scopes: ${e.scopes.join(", ")}`);if(e.missingMarketingReadScopes.length>0)console.log(`- Missing marketing read scopes: ${e.missingMarketingReadScopes.join(", ")}`);if(e.canSendLive===!0)console.log("- Live delivery: yes");else if(e.canSendLive===!1)console.log(e.liveDeliveryBlockedByRole?"- Live delivery: no (your role in this workspace is read-only, so widening the key's permissions will not help)":"- Live delivery: no (this key holds no permission that can send)");let o=e.roleRestrictedScopes??[];if(o.length>0)console.log(`- Blocked by your workspace role: ${o.join(", ")} (a marketer can send campaigns but not transactional email; ask the owner for admin access if you need these)`);let a=e.missingLiveDeliveryScopes??[];if(a.length>0)console.log(`- Missing live delivery scopes: ${a.join(", ")}`);if(e.manageUrl)console.log(`- API key settings: ${e.manageUrl}`)}async function Tz(e){if(!await H())k(J()),process.exit(1);try{let t=await E("GET","/api/v1/account"),n=t.currentCompanyId!==null?ct({companyId:t.currentCompanyId}):void 0,r=t.companies.map((o)=>{let a=ct({companyId:o.id});return{...o,url:a.urls.dashboard,settingsUrl:a.urls.settings,subscriptionUrl:a.urls.subscription}});if(e.json){console.log(JSON.stringify({...t,companies:r,...n!==void 0&&{appUrls:n.urls,settingsUrls:n.settingsUrls}},null,2));return}if(console.log(`User ID: ${t.user?.id??"Unknown"}`),console.log(`Current company: ${t.currentCompanyId??"None"}`),Ce("Current company URL",n?.urls.dashboard),Ce("Current company settings",n?.urls.settings),Ce("Current company subscription",n?.urls.subscription),console.log(""),t.apiKeyPermissions)_ue(t.apiKeyPermissions),console.log("");if(t.companies.length===0){console.log(t.message??"No companies found.");return}console.log(`Companies (${t.companies.length})`);for(let o of r){let a=o.id===t.currentCompanyId?" (current)":"";if(console.log(`- ${o.name} [${o.id}]${a}`),o.role)console.log(` Role: ${o.role}`);Ce(" URL",o.url),Ce(" Settings",o.settingsUrl),Ce(" Subscription",o.subscriptionUrl)}}catch(t){k(t instanceof A?t:t),process.exit(1)}}var nb="/api/v1/account-suggestions/organization-ids",kue=2000,Rue=900000;function Xd(e,t){return`${e.toLocaleString()} ${t}${e===1?"":"s"}`}function Pz(e){if(e===void 0)return;if(e==="event"||e==="attribute")return e;throw new A('--source must be "event" or "attribute"',400)}function Fz(e){let t=e.propertyKey?.trim();if(!t)throw new A("Provide the organization ID key, for example workspaceId",400);return t}function $z(e){let t=new URLSearchParams({propertyKey:Fz(e)}),n=Pz(e.source);if(n)t.set("source",n);if(e.nameKey)t.set("nameKey",e.nameKey);if(e.limit)t.set("limit",e.limit);return`${nb}/preview?${t.toString()}`}function Nz(e){let n=[`- ${e.name?`${e.name}${e.domain?` [${e.domain}]`:""}`:`${e.externalId} (no name found)`}: ${Xd(e.contactCount,"contact")} (ID ${e.externalId})`];if(e.sampleEmails.length>0){let r=e.contactCount-e.sampleEmails.length;n.push(` ${e.sampleEmails.join(", ")}${r>0?`, +${r} more`:""}`)}return n}function Oz(e){if(e.state==="completed"&&e.result){let{result:t}=e;return`Created ${Xd(t.accountsCreated,"account")} and ${Xd(t.membershipsCreated,"membership")} (${t.accountsUpdated} updated, ${t.skipped} skipped).${t.truncated?" History was larger than one run covers; run create again to continue.":""}`}if(e.state==="failed")return`Failed: ${e.error??"unknown error"}`;if(e.state==="running")return"Running: creating accounts.";if(e.state==="queued")return"Queued: waiting for a worker.";return"Job not found."}function qz(e){return`${nb}/jobs/${encodeURIComponent(e)}`}async function Que(e,t){let n=Date.now()+Rue;for(;;){let{job:r}=await E("GET",qz(e),void 0,t);if(r.state==="completed"||r.state==="failed"||Date.now()>n)return r;await new Promise((o)=>setTimeout(o,kue))}}async function Cf(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="detect"){let n=await E("GET",nb,void 0,t.company);if(t.json){D(n);return}if(n.candidates.length===0){console.log("No organization ID found in your recent events or contact attributes.");return}console.log("Organization IDs found");for(let o of n.candidates){let a=o.source==="attribute"?`contact attribute on ${Xd(o.eventCount,"contact")}`:`event property on ${Xd(o.eventCount,"recent event")}`;console.log(`- ${o.propertyKey}: ${Xd(o.accountCount,"organization")}, ${a}${o.nameKey?`, names in ${o.nameKey}`:""}`)}let[r]=n.candidates;if(r)console.log(`Preview with: sequenzy accounts preview-org-id ${r.propertyKey}${r.source==="attribute"?" --source attribute":""}${r.nameKey?` --name-key ${r.nameKey}`:""}`);return}if(e==="preview"){let n=await E("GET",$z(t),void 0,t.company);if(t.json){D(n);return}if(n.organizations.length===0){console.log(`No organizations found for ${t.propertyKey}.`);return}console.log(`Biggest accounts ${t.propertyKey} would create (${n.organizations.length} shown)`);for(let r of n.organizations)for(let o of Nz(r))console.log(o);console.log("Names come from the name key when set, otherwise from the work email domain most contacts share. No emails are sent and no sequences start.");return}if(e==="create"){let n=Fz(t),r=Pz(t.source);if(!t.yes&&!t.json){let p=await E("GET",$z({...t,limit:"5"}),void 0,t.company);console.log(`Biggest accounts ${n} would create:`);for(let f of p.organizations)for(let h of Nz(f))console.log(h)}if(!await mt(`Create one account per ${n} and add each contact to its organization's account? No emails are sent.`,t)){console.log("Cancelled.");return}let a=await E("POST",nb,{propertyKey:n,...r&&{source:r},...t.nameKey!==void 0&&{nameKey:t.nameKey}},t.company),c=t.wait?await Que(a.jobId,t.company):a.job;if(t.json){if(D({...a,job:c}),c.state==="failed")process.exitCode=1;return}let l=a.job.settings;if(console.log(a.alreadyRunning?`A run for ${n} is already in progress (job ${a.jobId}${l?`, source ${l.source}${l.nameKey?`, names from ${l.nameKey}`:""}`:""}). Start again when it finishes to use other settings.`:`Started creating accounts from ${n} (job ${a.jobId}).`),console.log(Oz(c)),c.state==="queued"||c.state==="running"){if(t.wait)console.log("Stopped waiting after 15 minutes; the run continues.");console.log(`Check with: sequenzy accounts org-id-job ${a.jobId}`)}if(c.state==="failed")process.exitCode=1;return}if(e==="job"){let n=t.jobId?.trim();if(!n)throw new A("Job ID is required",400);let r=await E("GET",qz(n),void 0,t.company);if(t.json){D(r);return}console.log(Oz(r.job));return}}catch(n){k(n),process.exit(1)}}function jz(e,t){let n={};for(let r of e??[]){let o=r.indexOf("=");if(o<=0)throw new A(`${t} expects key=value, received "${r}"`,400);let a=r.slice(0,o).trim(),c=r.slice(o+1);if(!a)throw new A(`${t} expects key=value, received "${r}"`,400);if(c==="")n[a]=null;else if(c==="true"||c==="false")n[a]=c==="true";else if(/^-?\d+(\.\d+)?$/.test(c))n[a]=Number(c);else n[a]=c}return n}function Tue(e){if(!e.externalId||e.externalId.trim()==="")throw new A("Account external ID is required",400);let t=jz(e.attr,"--attr");return{externalId:e.externalId.trim(),...e.name!==void 0&&{name:e.name},...e.domain!==void 0&&{domain:e.domain},...Object.keys(t).length>0&&{attributes:t},...e.replaceAttributes&&{replaceAttributes:!0}}}function Lz(e){if(!e.email&&!e.subscriberExternalId)throw new A("Provide --email or --subscriber-external-id to identify the contact",400);return{...e.email!==void 0&&{email:e.email},...e.subscriberExternalId!==void 0&&{externalId:e.subscriberExternalId}}}function $ue(e){if(!e.event||e.event.trim()==="")throw new A("Event name is required",400);let t=jz(e.property,"--property");return{event:e.event.trim(),...Object.keys(t).length>0&&{properties:t},...e.recipients!==void 0&&{recipients:e.recipients},...e.eventId!==void 0&&{eventId:e.eventId},...e.occurredAt!==void 0&&{occurredAt:e.occurredAt}}}function mu(e,t=""){return`/api/v1/accounts/${encodeURIComponent(e)}${t}`}function D0(e){if(console.log(`- ${e.name??"(unnamed)"} [${e.externalId}]`),e.domain)console.log(` Domain: ${e.domain}`);console.log(` Members: ${e.memberCount}`);let t=Object.entries(e.attributes??{});if(t.length>0)console.log(` Attributes: ${t.map(([n,r])=>`${n}=${JSON.stringify(r)}`).join(", ")}`);if(e.lastEventAt)console.log(` Last event: ${e.lastEventAt}`)}function Uz(e){let t=e.email??e.externalId??e.subscriberId;console.log(`- ${t} (${e.role})`)}async function Ri(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="list"){let r=new URLSearchParams;if(t.search)r.set("search",t.search);if(t.page)r.set("page",t.page);if(t.limit)r.set("limit",t.limit);if(t.sort)r.set("sort",t.sort);if(t.order)r.set("order",t.order);let o=r.toString(),a=await E("GET",`/api/v1/accounts${o?`?${o}`:""}`,void 0,t.company);if(t.json){D(a);return}console.log(`Accounts (${a.accounts.length} of ${a.total}, page ${a.page})`);for(let c of a.accounts)D0(c);if(a.hasMore)console.log(`More available: --page ${a.page+1}`);return}if(e==="suggestions"){let r=new URLSearchParams;if(t.minContacts)r.set("minContacts",t.minContacts);if(t.limit)r.set("limit",t.limit);let o=r.toString(),a=await E("GET",`/api/v1/account-suggestions${o?`?${o}`:""}`,void 0,t.company);if(t.json){D(a);return}if(a.suggestions.length===0){console.log("No account suggestions.");return}console.log(`Suggested accounts from contact email domains (${a.suggestions.length})`);for(let c of a.suggestions)if(console.log(`- ${c.name} [${c.domain}]: ${c.contactCount} contact${c.contactCount===1?"":"s"}`),c.sampleEmails.length>0){let l=c.sampleEmails.slice(0,3),p=c.contactCount-l.length;console.log(` ${l.join(", ")}${p>0?`, +${p} more`:""}`)}console.log(`Accept with: sequenzy accounts accept-suggestions ${a.suggestions.slice(0,3).map((c)=>c.domain).join(" ")}`);return}if(e==="accept-suggestions"){let r=(t.domains??[]).map((a)=>a.trim()).filter(Boolean);if(r.length===0)throw new A("Provide at least one domain",400);let o=await E("POST","/api/v1/account-suggestions",{domains:r},t.company);if(t.json){D(o);return}console.log(`Created ${o.accountsCreated} account${o.accountsCreated===1?"":"s"} and ${o.membershipsCreated} membership${o.membershipsCreated===1?"":"s"}`);for(let a of o.results){if(a.status==="skipped"){console.log(`- ${a.domain}: skipped (${a.reason})`);continue}console.log(`- ${a.domain}: ${a.status} ${a.account?.externalId??""}, ${a.membersAdded} member${a.membersAdded===1?"":"s"} added${a.truncated?" (member cap reached)":""}`)}return}if(e==="upsert"){let r=Tue(t),o=await E("POST","/api/v1/accounts",r,t.company);if(t.json){D(o);return}console.log(`${o.created?"Created":"Updated"} account ${o.account.externalId}`),D0(o.account);return}if(!t.externalId||t.externalId.trim()==="")throw new A("Account external ID is required",400);let n=t.externalId.trim();if(e==="get"){let r=await E("GET",mu(n),void 0,t.company);if(t.json){D(r);return}if(D0(r.account),r.members&&r.members.length>0){console.log("Members:");for(let o of r.members)Uz(o)}return}if(e==="delete"){if(!await mt(`Delete account ${n} and its memberships? Contacts are kept.`,t)){console.log("Cancelled.");return}let o=await E("DELETE",mu(n),void 0,t.company);if(t.json){D(o);return}console.log(`Deleted account ${n} (${o.membersCleared} membership${o.membersCleared===1?"":"s"} cleared)`);return}if(e==="members"){let r=await E("GET",mu(n,"/members"),void 0,t.company);if(t.json){D(r);return}console.log(`Members of ${n} (${r.members.length})`);for(let o of r.members)Uz(o);return}if(e==="add-member"){let r={...Lz(t),...t.role!==void 0&&{role:t.role}},o=await E("POST",mu(n,"/members"),r,t.company);if(t.json){D(o);return}let a=o.member.email??o.member.externalId??"contact";console.log(`${o.member.created?"Added":"Updated"} ${a} as ${o.member.role} of ${n}`);return}if(e==="remove-member"){let r=Lz(t),o=await E("DELETE",mu(n,"/members"),r,t.company);if(t.json){D(o);return}console.log(o.removed?`Removed contact from ${n}`:`Contact was not a member of ${n}`);return}if(e==="events"){let r=new URLSearchParams;if(t.limit)r.set("limit",t.limit);let o=r.toString(),a=await E("GET",mu(n,`/events${o?`?${o}`:""}`),void 0,t.company);if(t.json){D(a);return}console.log(`Events for ${n} (${a.events.length})`);for(let c of a.events)console.log(`- ${c.eventTime} ${c.name} (${c.recipientCount} recipient${c.recipientCount===1?"":"s"})`);return}if(e==="event"){let r=$ue(t),o=await E("POST",mu(n,"/events"),r,t.company);if(t.json){D(o);return}console.log(`Recorded ${o.event.name} on ${n}; delivered to ${o.recipientCount} ${o.recipients==="none"?"nobody (timeline only)":`recipient${o.recipientCount===1?"":"s"} (${o.recipients})`}`);for(let a of o.deliveries){let c=a.skipped==="contact_deleted"?"skipped (contact deleted)":a.success?"ok":`failed: ${a.error??"unknown"}`;console.log(` - ${a.email??"contact"} (${a.role}): ${c}${a.automationsTriggered.length>0?`, sequences: ${a.automationsTriggered.length}`:""}`)}return}}catch(n){k(n),process.exit(1)}}function B0(e){if(e===void 0)return;return e.split(",").map((t)=>t.trim()).filter((t)=>t.length>0)}async function fu(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="handoff"){let a=B0(t.scopes),c=await E("POST","/api/v1/api-key-handoff",{...t.name!==void 0&&{name:t.name},...t.preset!==void 0&&{preset:t.preset},...a!==void 0&&{scopes:a},...t.replaces!==void 0&&{replaceApiKeyId:t.replaces}},t.company);if(t.json){D(c);return}let{handoff:l}=c;console.log("Open this link in a browser signed in as the key owner:"),console.log(l.url),console.log(""),console.log(`Key type: ${l.keyType}`),console.log(`Suggested name: ${l.name??"(dashboard default)"}`);let p=l.preset??(l.scopes?(l.permissions??du(l.scopes)).description:"(dashboard default)");if(console.log(`Suggested permissions: ${p}`),l.scopes!==null)console.log(`Scopes: ${l.scopes.join(", ")}`);if(l.replaces){let f=l.replaces.name??l.replaces.id;console.log(`Replaces: ${f}${l.replaces.isCurrentKey?" (the key you are using now)":""}`)}console.log(""),console.log(c.message);for(let f of c.nextSteps)console.log(`- ${f}`);return}if(e==="list"){let a=await E("GET","/api/v1/api-keys",void 0,t.company);if(t.json){D(a);return}if(a.apiKeys.length===0){console.log("No company API keys found.");return}for(let[c,l]of a.apiKeys.entries()){if(c>0)console.log("");console.log(`${l.name}${l.isCurrent?" (current)":""}`),console.log(`ID: ${l.id}`),console.log(`Prefix: ${l.prefix}`);let p=l.permissions??du(l.scopes);console.log(`Permission preset: ${p.preset}`),console.log(`Last used: ${ne(l.lastUsedAt)}`),console.log(`Created: ${ne(l.createdAt)}`)}return}if(e==="update"){if(!t.apiKeyId)throw new A("API key ID is required",400);let a=B0(t.scopes);if(t.name===void 0&&t.preset===void 0&&a===void 0)throw new A("Provide --name, --preset, or --scopes to update the key",400);let c=await E("PATCH",`/api/v1/api-keys/${encodeURIComponent(t.apiKeyId)}`,{...t.name!==void 0&&{name:t.name},...t.preset!==void 0&&{preset:t.preset},...a!==void 0&&{scopes:a}},t.company);if(t.json){D(c);return}console.log(c.message),console.log(`Name: ${c.apiKey.name}`),console.log(`ID: ${c.apiKey.id}`),console.log(`Prefix: ${c.apiKey.prefix}`);let l=c.apiKey.permissions??du(c.apiKey.scopes);if(console.log(`Permission preset: ${l.preset}`),console.log(`Permissions: ${l.description}`),c.apiKey.scopes!==null)console.log(`Scopes: ${c.apiKey.scopes.join(", ")}`);return}if(e==="revoke"||e==="delete"){if(!t.apiKeyId)throw new A("API key ID is required",400);if(!await mt(`Revoke API key ${t.apiKeyId}? This cannot be undone.`,t)){console.log("Aborted.");return}let a=await E("DELETE",`/api/v1/api-keys/${encodeURIComponent(t.apiKeyId)}`,void 0,t.company);if(t.json){D(a);return}console.log(a.message),console.log(`Name: ${a.apiKey.name}`),console.log(`ID: ${a.apiKey.id}`),console.log(`Prefix: ${a.apiKey.prefix}`);return}let n=B0(t.scopes),r=await E("POST","/api/v1/api-keys",{name:t.name,...t.preset!==void 0&&{preset:t.preset},...n!==void 0&&{scopes:n}},t.company);if(t.json){D(r);return}console.log(`Created API key: ${r.apiKey.name}`),console.log(`ID: ${r.apiKey.id}`),console.log(`Prefix: ${r.apiKey.prefix}`);let o=r.apiKey.permissions??du(r.apiKey.scopes);if(console.log(`Permission preset: ${o.preset}`),console.log(`Full access: ${o.fullAccess?"yes":"no"}`),console.log(`Permissions: ${o.description}`),r.apiKey.scopes!==null)console.log(`Scopes: ${r.apiKey.scopes.join(", ")}`);console.log(`Created: ${ne(r.apiKey.createdAt)}`),console.log(""),console.log(r.message),console.log(`Key: ${r.apiKey.key}`),console.log(`Env: ${r.instructions.example}`),console.log(r.instructions.note)}catch(n){k(n instanceof A?n:n),process.exit(1)}}var zz=["hourly","daily","weekly"];function Nue(e){let t=e.syncStatus==="disconnected"?"disconnected":!e.isActive?"paused":e.syncStatus==="error"?"error":e.syncStatus;if(console.log(`- ${e.segmentName??e.segmentId} -> "${e.audienceName}" (${e.adAccountId})`),console.log(` id: ${e.id} | ${e.frequency} | status: ${t} | last sync: ${e.lastSyncAt??"never"} | uploaded: ${e.lastSyncedCount}`),e.lastSyncError)console.log(` last error: ${e.lastSyncError}`)}function Mz(e){if(e===void 0)return"daily";if(!zz.includes(e))k(new A(`Invalid frequency "${e}". Use one of: ${zz.join(", ")}.`,400)),process.exit(1);return e}function x0(e,t){if(!e||e.trim().length===0)k(new A(`${t} is required.`,400)),process.exit(1);return e.trim()}async function gu(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="list"){let o=await E("GET","/api/v1/audience-syncs",void 0,t.company);if(t.json){console.log(JSON.stringify(o,null,2));return}console.log(`Audience syncs (${o.audienceSyncs.length})`);for(let a of o.audienceSyncs)Nue(a);return}if(e==="ad-accounts"){let o=await E("GET","/api/v1/ad-accounts",void 0,t.company);if(t.json){console.log(JSON.stringify(o,null,2));return}console.log(`Ad accounts (${o.adAccounts.length})`);for(let a of o.adAccounts)console.log(`- ${a.name} (${a.id})`);return}if(e==="create"){if(t.segment&&t.template)k(new A("Provide either --segment or --template, not both.",400)),process.exit(1);if(!t.segment&&!t.template)k(new A("Provide --segment <id> or --template <id> (for example --template recent-buyers).",400)),process.exit(1);let o=await E("POST","/api/v1/audience-syncs",{...t.segment?{segmentId:t.segment}:{},...t.template?{predefinedSegmentId:t.template}:{},adAccountId:x0(t.adAccount,"--ad-account"),audienceName:x0(t.name,"--name"),frequency:Mz(t.frequency)},t.company);if(t.json){console.log(JSON.stringify(o,null,2));return}console.log(`Created audience sync: ${o.audienceSync.segmentName??o.audienceSync.segmentId} -> "${o.audienceSync.audienceName}"`),console.log(`ID: ${o.audienceSync.id}`),console.log(`Frequency: ${o.audienceSync.frequency}`),console.log("The first upload to Meta is running now.");return}let n=x0(t.id,"--id");if(e==="update"){let o={};if(t.frequency!==void 0)o.frequency=Mz(t.frequency);if(t.active!==void 0){if(t.active!=="true"&&t.active!=="false")k(new A('--active must be "true" or "false".',400)),process.exit(1);o.isActive=t.active==="true"}if(Object.keys(o).length===0)k(new A("Provide --frequency and/or --active to update.",400)),process.exit(1);let a=await E("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(n)}`,o,t.company);if(t.json){console.log(JSON.stringify(a,null,2));return}console.log(`Updated audience sync ${a.audienceSync.id}: ${a.audienceSync.frequency}, ${a.audienceSync.isActive?"active":"paused"}`);return}if(e==="delete"){let o=await E("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(n)}`,void 0,t.company);if(t.json){console.log(JSON.stringify(o,null,2));return}console.log(`Removed audience sync ${n}. The Meta audience itself is kept.`);return}let r=await E("POST",`/api/v1/audience-syncs/${encodeURIComponent(n)}/sync`,void 0,t.company);if(t.json){console.log(JSON.stringify(r,null,2));return}console.log(`Queued sync for ${n}.`)}catch(n){k(n instanceof A?n:n),process.exit(1)}}var Oue={requested:"Requested",collecting:"Collecting emails",available:"In the gallery",declined:"Not added"};function Hz(e){let t=e.status==="available"&&e.brand?e.brand.url:e.status==="declined"?e.declineReason:e.note;return[`${e.domain} · ${Oue[e.status]}`,t?` ${t}`:null,` ID: ${e.id}`].filter(Boolean).join(`
|
|
266
|
+
`}function S(e,t){let n=t.notes??[],r=t.examples??[],o=Bz("Notes",n)+Bz("Examples",r);if(o.trim().length>0)e.addHelpText("after",o);return e}var bue={high:"FIX FIRST",medium:"WORTH FIXING",low:"HOUSEKEEPING"};function xz(e){if(!e.enabled)return"off";return`Mondays at 05:00 UTC, ${e.autonomy==="draft_fixes"?"drafts fixes":"report only"}`}function vue(e,t){let n=t.targetId??"";switch(t.kind){case"create_sequence":return`sequenzy account-health fix ${e.id}`;case"activate_sequence":return`sequenzy sequences enable ${n}`;case"pause_sequence":return`sequenzy sequences disable ${n}`;case"verify_sending_domain":return`sequenzy websites verify ${e.subjectName??n}`;default:return`dashboard: ${t.path??"/"}`}}function Eue(e){let t=e.status==="snoozed"?" (snoozed)":"";console.log(`- [${bue[e.severity]}] ${e.title}${t}`),console.log(` ${e.detail}`),console.log(` Fix: ${e.recommendation}`);for(let n of e.actions??[])console.log(` ${n.primary?"Do":"Or"}: ${n.label} -> ${vue(e,n)}`);console.log(` ID: ${e.id}`)}function Iue(e){if(!e.eligibility.eligible){let{minimumActiveSubscribers:n,activityDays:r,hasMinimumSubscribers:o}=e.eligibility;console.log(`Account health checks run for workspaces with more than ${n.toLocaleString("en-US")} active subscribers that sent email in the last ${r} days.`),console.log(o?`This workspace has not sent email in the last ${r} days.`:`This workspace has ${n.toLocaleString("en-US")} or fewer active subscribers.`);return}if(console.log(`Checks: ${xz(e.settings)}`),e.nextRunAt)console.log(`Next check: ${e.nextRunAt}`);let t=e.latestRun;if(e.runInProgress)console.log("A check is running now.");else if(t)console.log(`Last check: ${t.status} at ${t.completedAt??t.createdAt}`);if(t?.status==="completed"&&t.summary)console.log(""),console.log(t.summary);if(console.log(""),e.insights.length===0){console.log(t?"Nothing to fix.":"No check has run yet. Run one with `sequenzy account-health run`.");return}for(let n of e.insights)Eue(n)}function Cue(e,t){console.log(t?`A check is already ${e.status} (${e.id}).`:`Check queued (${e.id}). It usually finishes within a minute; see the result with \`sequenzy account-health\`.`)}function wue(e){let t={};if(e.enabled!==void 0)t.enabled=e.enabled;if(e.autonomy!==void 0)t.autonomy=e.autonomy;if(Object.keys(t).length===0)throw new A("Pass at least one setting to change",400);let n=Sz(t);if(!n.ok)throw new A(n.error,400);return t}async function Sue(e,t){if(!await H())k(J()),process.exit(1);try{if(e.kind==="get"){let o=await E("GET","/api/v1/account-health",void 0,t.company);if(t.json)return D(o);Iue(o.accountHealth);return}if(e.kind==="settings"){let o=await E("PATCH","/api/v1/account-health/settings",wue(t),t.company);if(t.json)return D(o);if(console.log(`Checks: ${xz(o.settings)}`),o.nextRunAt)console.log(`Next check: ${o.nextRunAt}`);return}if(e.kind==="run"){let o=await E("POST","/api/v1/account-health/runs",void 0,t.company);if(t.json)return D(o);Cue(o.run,o.alreadyInProgress);return}if(e.kind==="fix"){let o=await E("POST",`/api/v1/account-health/insights/${encodeURIComponent(e.insightId)}/fix`,void 0,t.company);if(t.json)return D(o);let a=`review it with \`sequenzy sequences get ${o.sequenceId}\`, then turn it on with \`sequenzy sequences enable ${o.sequenceId}\``,c=o.created?`Built draft sequence ${o.sequenceId}.`:`A draft for this already exists: ${o.sequenceId}.`,l=o.enrichmentStatus??(o.created?"processing":void 0);console.log(l==="not_queued"?`${c} Its emails could not start writing. Open it in the dashboard to write them, then ${a}.`:l==="processing"?`${c} Its emails are being written now; ${a}.`:c);return}if(!Dz(e.action))throw new A(`Unknown action "${e.action}". Use one of: ${tb.join(", ")}.`,400);let n={action:e.action};if(t.snoozeDays!==void 0)n.snoozeDays=Number(t.snoozeDays);let r=await E("PATCH",`/api/v1/account-health/insights/${encodeURIComponent(e.insightId)}`,n,t.company);if(t.json)return D(r);console.log(`${r.insight.title}: ${r.insight.status}`)}catch(n){k(n),process.exit(1)}}function _z(e,t=Sue){let n=(h)=>h.optsWithGlobals(),r=(h)=>h.option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON"),o=r(e.command("account-health").description("Show the account health report: what to fix in your email setup").allowExcessArguments(!1)).action((h,y)=>t({kind:"get"},n(y)));S(o,{notes:["An AI agent checks the workspace every Monday at 05:00 UTC and lists gaps: events nothing reacts to, sequences that stopped enrolling, campaign gaps, weak sequence emails, deliverability spikes and failing domains.","Workspaces need more than 1,000 active subscribers and an email sent in the last 14 days. Drafted fixes are inactive sequences; nothing is sent or activated for you."],examples:["sequenzy account-health","sequenzy account-health run","sequenzy account-health settings --autonomy report_only","sequenzy account-health insight <id> snooze --snooze-days 30"]});let a=r(o.command("get").description("Show the account health report")).action((h,y)=>t({kind:"get"},n(y)));S(a,{examples:["sequenzy account-health get --json"]});let c=r(o.command("settings").description("Turn weekly checks on or off and choose whether they draft fixes").option("--enabled","Turn weekly checks on").option("--no-enabled","Turn weekly checks off").option("--autonomy <level>","draft_fixes or report_only")).action((h,y)=>t({kind:"settings"},n(y)));S(c,{notes:["Checks run every Monday at 05:00 UTC, before the Monday weekly report that carries the findings. Who gets them is each person's own setting: sequenzy notifications set --account-health off|instant."],examples:["sequenzy account-health settings --no-enabled","sequenzy account-health settings --enabled --autonomy report_only"]});let l=r(o.command("run").description("Run a check now")).action((h,y)=>t({kind:"run"},n(y)));S(l,{notes:["Manual checks are limited to one every 10 minutes, wait a day after a check that left findings open, and never send the report email."],examples:["sequenzy account-health run"]});let p=r(o.command("fix <insightId>").description("Build the draft sequence a finding asks for (events with no sequence)")).action((h,y,v)=>t({kind:"fix",insightId:h},n(v)));S(p,{notes:["Creates an inactive draft triggered by the event, with its timing and titled email steps, and writes the emails with AI like a template. Review them, then enable it. Running it again returns the same draft, writing only steps that still have no email (a check's own drafts are written when first opened)."],examples:["sequenzy account-health fix ins_123"]});let f=r(o.command("insight <insightId> <action>").description(`Act on a finding: ${tb.join(", ")}`).option("--snooze-days <days>","Days to snooze (1-90, default 7)")).action((h,y,v,C)=>t({kind:"insight",insightId:h,action:y},n(C)));return S(f,{notes:["resolve marks it fixed; it reopens if the next check still finds it. dismiss hides it for good."],examples:["sequenzy account-health insight ins_123 dismiss","sequenzy account-health insight ins_123 snooze --snooze-days 30"]}),o}var S0=["product-info","email-design","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],kz={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",account:"/dashboard/company/{companyId}/account",subscription:"/dashboard/company/{companyId}/account?tab=subscription",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function Due(e){let n=(e??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return n.length>0?n:"https://sequenzy.com"}function Ss(e){let t=e?.trim();return t?t:void 0}function Ia(e){return encodeURIComponent(e)}function cr(e,t){return`${e}${t}`}function lr(e,t=""){return`/dashboard/company/${Ia(e)}${t}`}function Rz(e,t,n){return cr(e,`${lr(t,"/settings")}?tab=${encodeURIComponent(n)}`)}function Bue(e,t){let n=S0.map((r)=>[r,t?Rz(e,t,r):""]);return Object.fromEntries(n)}function ct(e={},t){let n=Due(t),r=Ss(e.companyId),o={},a=Bue(n,r);if(!r)return{appUrl:n,routeTemplates:kz,settingsTabValues:S0,urls:o,settingsUrls:a};o.dashboard=cr(n,lr(r)),o.campaigns=cr(n,lr(r,"/campaign")),o.landingPages=cr(n,lr(r,"/landing-pages")),o.sequences=cr(n,lr(r,"/sequences")),o.account=cr(n,lr(r,"/account")),o.subscription=`${o.account}?tab=subscription`,o.settings=cr(n,lr(r,"/settings")),o.emails=cr(n,lr(r,"/emails")),o.subscribers=cr(n,lr(r,"/subscribers")),o.sentEmails=cr(n,lr(r,"/sent-emails")),o.segments=cr(n,lr(r,"/segments")),o.metrics=cr(n,lr(r,"/metrics")),o.transactional=cr(n,lr(r,"/transactional"));let c=Ss(e.campaignId);if(c)o.campaign=cr(n,lr(r,`/campaign/${Ia(c)}`)),o.campaignPreview=`${o.campaign}?step=review`;let l=Ss(e.landingPageId);if(l)o.landingPage=cr(n,lr(r,`/landing-pages/${Ia(l)}`));let p=Ss(e.sequenceId);if(p)o.sequence=cr(n,lr(r,`/sequences/${Ia(p)}`));let f=Ss(e.emailId)??Ss(e.templateId);if(f)o.email=cr(n,lr(r,`/emails/${Ia(f)}`)),o.template=o.email;let h=Ss(e.transactionalId);if(h)o.transactionalEmail=cr(n,lr(r,`/transactional/${Ia(h)}`));let y=Ss(e.emailSendId);if(y)o.emailSend=cr(n,lr(r,`/sent-emails/${Ia(y)}`));let v=Ss(e.domainId);if(v)o.domain=cr(n,lr(r,`/settings/domain/${Ia(v)}`)),o.domainVerify=`${o.domain}/verify`;let C=Ss(e.status);if(C)o.campaignList=cr(n,lr(r,`/campaign/list/${Ia(C)}`)),o.sequenceList=cr(n,lr(r,`/sequences/list/${Ia(C)}`));let R=Ss(e.settingsTab);if(R)o.settingsTab=R==="billing"||R==="subscription"?o.subscription:Rz(n,r,R);return{appUrl:n,routeTemplates:kz,settingsTabValues:S0,urls:o,settingsUrls:a}}async function Ht(e){if(e?.trim())return e.trim();try{return(await E("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function xue(e,t){let n=await Ht(t);return ct({...e,companyId:n})}function Ce(e,t){if(t)console.log(`${e}: ${t}`)}function Ds(e,t,n,r){let a=ct({...t,companyId:r}).urls[n];return{...e,...a!==void 0&&{url:a}}}async function Qz(e){if(!await H())k(J()),process.exit(1);try{let t=await xue({campaignId:e.campaign,landingPageId:e.landingPage,sequenceId:e.sequence,emailId:e.email,templateId:e.template,transactionalId:e.transactional,emailSendId:e.emailSend,domainId:e.domain,status:e.status,settingsTab:e.settingsTab},e.company);if(e.company&&!t.urls.dashboard)throw new A("Company ID is required to build dashboard URLs",400);if(e.json){D(t);return}if(console.log(`App: ${t.appUrl}`),console.log(""),Object.keys(t.urls).length===0){console.log("No company selected. Pass --company or run `sequenzy account` to find the current company ID."),console.log(""),console.log("Route templates:");for(let[n,r]of Object.entries(t.routeTemplates))console.log(`- ${n}: ${r}`);return}console.log("URLs:");for(let[n,r]of Object.entries(t.urls))console.log(`- ${n}: ${r}`);console.log(""),console.log("Settings tabs:");for(let[n,r]of Object.entries(t.settingsUrls))console.log(`- ${n}: ${r}`)}catch(t){k(t instanceof A?t:t),process.exit(1)}}function _ue(e){let t=du(e.scopes),n={preset:e.preset??t.preset,fullAccess:e.fullAccess??t.fullAccess,selectedScopeCount:e.selectedScopeCount??t.selectedScopeCount,currentScopeCount:e.currentScopeCount??t.currentScopeCount,description:e.description??t.description},r=e.activeKey;if(console.log("API key"),r)console.log(`- Name: ${r.name??"Unknown"}`),console.log(`- ID: ${r.id}`),console.log(`- Prefix: ${r.prefix??"Unknown"}`),console.log(`- Type: ${r.type??"Unknown"}`);if(console.log(`- Permission preset: ${n.preset}`),console.log(`- Full access: ${n.fullAccess?"yes":"no"}`),console.log(`- Permissions: ${n.description}`),e.scopes!==null)console.log(`- Scopes: ${e.scopes.join(", ")}`);if(e.missingMarketingReadScopes.length>0)console.log(`- Missing marketing read scopes: ${e.missingMarketingReadScopes.join(", ")}`);if(e.canSendLive===!0)console.log("- Live delivery: yes");else if(e.canSendLive===!1)console.log(e.liveDeliveryBlockedByRole?"- Live delivery: no (your role in this workspace is read-only, so widening the key's permissions will not help)":"- Live delivery: no (this key holds no permission that can send)");let o=e.roleRestrictedScopes??[];if(o.length>0)console.log(`- Blocked by your workspace role: ${o.join(", ")} (a marketer can send campaigns but not transactional email; ask the owner for admin access if you need these)`);let a=e.missingLiveDeliveryScopes??[];if(a.length>0)console.log(`- Missing live delivery scopes: ${a.join(", ")}`);if(e.manageUrl)console.log(`- API key settings: ${e.manageUrl}`)}async function Tz(e){if(!await H())k(J()),process.exit(1);try{let t=await E("GET","/api/v1/account"),n=t.currentCompanyId!==null?ct({companyId:t.currentCompanyId}):void 0,r=t.companies.map((o)=>{let a=ct({companyId:o.id});return{...o,url:a.urls.dashboard,settingsUrl:a.urls.settings,subscriptionUrl:a.urls.subscription}});if(e.json){console.log(JSON.stringify({...t,companies:r,...n!==void 0&&{appUrls:n.urls,settingsUrls:n.settingsUrls}},null,2));return}if(console.log(`User ID: ${t.user?.id??"Unknown"}`),console.log(`Current company: ${t.currentCompanyId??"None"}`),Ce("Current company URL",n?.urls.dashboard),Ce("Current company settings",n?.urls.settings),Ce("Current company subscription",n?.urls.subscription),console.log(""),t.apiKeyPermissions)_ue(t.apiKeyPermissions),console.log("");if(t.companies.length===0){console.log(t.message??"No companies found.");return}console.log(`Companies (${t.companies.length})`);for(let o of r){let a=o.id===t.currentCompanyId?" (current)":"";if(console.log(`- ${o.name} [${o.id}]${a}`),o.role)console.log(` Role: ${o.role}`);Ce(" URL",o.url),Ce(" Settings",o.settingsUrl),Ce(" Subscription",o.subscriptionUrl)}}catch(t){k(t instanceof A?t:t),process.exit(1)}}var nb="/api/v1/account-suggestions/organization-ids",kue=2000,Rue=900000;function Xd(e,t){return`${e.toLocaleString()} ${t}${e===1?"":"s"}`}function Pz(e){if(e===void 0)return;if(e==="event"||e==="attribute")return e;throw new A('--source must be "event" or "attribute"',400)}function Fz(e){let t=e.propertyKey?.trim();if(!t)throw new A("Provide the organization ID key, for example workspaceId",400);return t}function $z(e){let t=new URLSearchParams({propertyKey:Fz(e)}),n=Pz(e.source);if(n)t.set("source",n);if(e.nameKey)t.set("nameKey",e.nameKey);if(e.limit)t.set("limit",e.limit);return`${nb}/preview?${t.toString()}`}function Nz(e){let n=[`- ${e.name?`${e.name}${e.domain?` [${e.domain}]`:""}`:`${e.externalId} (no name found)`}: ${Xd(e.contactCount,"contact")} (ID ${e.externalId})`];if(e.sampleEmails.length>0){let r=e.contactCount-e.sampleEmails.length;n.push(` ${e.sampleEmails.join(", ")}${r>0?`, +${r} more`:""}`)}return n}function Oz(e){if(e.state==="completed"&&e.result){let{result:t}=e;return`Created ${Xd(t.accountsCreated,"account")} and ${Xd(t.membershipsCreated,"membership")} (${t.accountsUpdated} updated, ${t.skipped} skipped).${t.truncated?" History was larger than one run covers; run create again to continue.":""}`}if(e.state==="failed")return`Failed: ${e.error??"unknown error"}`;if(e.state==="running")return"Running: creating accounts.";if(e.state==="queued")return"Queued: waiting for a worker.";return"Job not found."}function qz(e){return`${nb}/jobs/${encodeURIComponent(e)}`}async function Que(e,t){let n=Date.now()+Rue;for(;;){let{job:r}=await E("GET",qz(e),void 0,t);if(r.state==="completed"||r.state==="failed"||Date.now()>n)return r;await new Promise((o)=>setTimeout(o,kue))}}async function Cf(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="detect"){let n=await E("GET",nb,void 0,t.company);if(t.json){D(n);return}if(n.candidates.length===0){console.log("No organization ID found in your recent events or contact attributes.");return}console.log("Organization IDs found");for(let o of n.candidates){let a=o.source==="attribute"?`contact attribute on ${Xd(o.eventCount,"contact")}`:`event property on ${Xd(o.eventCount,"recent event")}`;console.log(`- ${o.propertyKey}: ${Xd(o.accountCount,"organization")}, ${a}${o.nameKey?`, names in ${o.nameKey}`:""}`)}let[r]=n.candidates;if(r)console.log(`Preview with: sequenzy accounts preview-org-id ${r.propertyKey}${r.source==="attribute"?" --source attribute":""}${r.nameKey?` --name-key ${r.nameKey}`:""}`);return}if(e==="preview"){let n=await E("GET",$z(t),void 0,t.company);if(t.json){D(n);return}if(n.organizations.length===0){console.log(`No organizations found for ${t.propertyKey}.`);return}console.log(`Biggest accounts ${t.propertyKey} would create (${n.organizations.length} shown)`);for(let r of n.organizations)for(let o of Nz(r))console.log(o);console.log("Names come from the name key when set, otherwise from the work email domain most contacts share. No emails are sent and no sequences start.");return}if(e==="create"){let n=Fz(t),r=Pz(t.source);if(!t.yes&&!t.json){let p=await E("GET",$z({...t,limit:"5"}),void 0,t.company);console.log(`Biggest accounts ${n} would create:`);for(let f of p.organizations)for(let h of Nz(f))console.log(h)}if(!await mt(`Create one account per ${n} and add each contact to its organization's account? No emails are sent.`,t)){console.log("Cancelled.");return}let a=await E("POST",nb,{propertyKey:n,...r&&{source:r},...t.nameKey!==void 0&&{nameKey:t.nameKey}},t.company),c=t.wait?await Que(a.jobId,t.company):a.job;if(t.json){if(D({...a,job:c}),c.state==="failed")process.exitCode=1;return}let l=a.job.settings;if(console.log(a.alreadyRunning?`A run for ${n} is already in progress (job ${a.jobId}${l?`, source ${l.source}${l.nameKey?`, names from ${l.nameKey}`:""}`:""}). Start again when it finishes to use other settings.`:`Started creating accounts from ${n} (job ${a.jobId}).`),console.log(Oz(c)),c.state==="queued"||c.state==="running"){if(t.wait)console.log("Stopped waiting after 15 minutes; the run continues.");console.log(`Check with: sequenzy accounts org-id-job ${a.jobId}`)}if(c.state==="failed")process.exitCode=1;return}if(e==="job"){let n=t.jobId?.trim();if(!n)throw new A("Job ID is required",400);let r=await E("GET",qz(n),void 0,t.company);if(t.json){D(r);return}console.log(Oz(r.job));return}}catch(n){k(n),process.exit(1)}}function jz(e,t){let n={};for(let r of e??[]){let o=r.indexOf("=");if(o<=0)throw new A(`${t} expects key=value, received "${r}"`,400);let a=r.slice(0,o).trim(),c=r.slice(o+1);if(!a)throw new A(`${t} expects key=value, received "${r}"`,400);if(c==="")n[a]=null;else if(c==="true"||c==="false")n[a]=c==="true";else if(/^-?\d+(\.\d+)?$/.test(c))n[a]=Number(c);else n[a]=c}return n}function Tue(e){if(!e.externalId||e.externalId.trim()==="")throw new A("Account external ID is required",400);let t=jz(e.attr,"--attr");return{externalId:e.externalId.trim(),...e.name!==void 0&&{name:e.name},...e.domain!==void 0&&{domain:e.domain},...Object.keys(t).length>0&&{attributes:t},...e.replaceAttributes&&{replaceAttributes:!0}}}function Lz(e){if(!e.email&&!e.subscriberExternalId)throw new A("Provide --email or --subscriber-external-id to identify the contact",400);return{...e.email!==void 0&&{email:e.email},...e.subscriberExternalId!==void 0&&{externalId:e.subscriberExternalId}}}function $ue(e){if(!e.event||e.event.trim()==="")throw new A("Event name is required",400);let t=jz(e.property,"--property");return{event:e.event.trim(),...Object.keys(t).length>0&&{properties:t},...e.recipients!==void 0&&{recipients:e.recipients},...e.eventId!==void 0&&{eventId:e.eventId},...e.occurredAt!==void 0&&{occurredAt:e.occurredAt}}}function mu(e,t=""){return`/api/v1/accounts/${encodeURIComponent(e)}${t}`}function D0(e){if(console.log(`- ${e.name??"(unnamed)"} [${e.externalId}]`),e.domain)console.log(` Domain: ${e.domain}`);console.log(` Members: ${e.memberCount}`);let t=Object.entries(e.attributes??{});if(t.length>0)console.log(` Attributes: ${t.map(([n,r])=>`${n}=${JSON.stringify(r)}`).join(", ")}`);if(e.lastEventAt)console.log(` Last event: ${e.lastEventAt}`)}function Uz(e){let t=e.email??e.externalId??e.subscriberId;console.log(`- ${t} (${e.role})`)}async function Ri(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="list"){let r=new URLSearchParams;if(t.search)r.set("search",t.search);if(t.page)r.set("page",t.page);if(t.limit)r.set("limit",t.limit);if(t.sort)r.set("sort",t.sort);if(t.order)r.set("order",t.order);let o=r.toString(),a=await E("GET",`/api/v1/accounts${o?`?${o}`:""}`,void 0,t.company);if(t.json){D(a);return}console.log(`Accounts (${a.accounts.length} of ${a.total}, page ${a.page})`);for(let c of a.accounts)D0(c);if(a.hasMore)console.log(`More available: --page ${a.page+1}`);return}if(e==="suggestions"){let r=new URLSearchParams;if(t.minContacts)r.set("minContacts",t.minContacts);if(t.limit)r.set("limit",t.limit);let o=r.toString(),a=await E("GET",`/api/v1/account-suggestions${o?`?${o}`:""}`,void 0,t.company);if(t.json){D(a);return}if(a.suggestions.length===0){console.log("No account suggestions.");return}console.log(`Suggested accounts from contact email domains (${a.suggestions.length})`);for(let c of a.suggestions)if(console.log(`- ${c.name} [${c.domain}]: ${c.contactCount} contact${c.contactCount===1?"":"s"}`),c.sampleEmails.length>0){let l=c.sampleEmails.slice(0,3),p=c.contactCount-l.length;console.log(` ${l.join(", ")}${p>0?`, +${p} more`:""}`)}console.log(`Accept with: sequenzy accounts accept-suggestions ${a.suggestions.slice(0,3).map((c)=>c.domain).join(" ")}`);return}if(e==="accept-suggestions"){let r=(t.domains??[]).map((a)=>a.trim()).filter(Boolean);if(r.length===0)throw new A("Provide at least one domain",400);let o=await E("POST","/api/v1/account-suggestions",{domains:r},t.company);if(t.json){D(o);return}console.log(`Created ${o.accountsCreated} account${o.accountsCreated===1?"":"s"} and ${o.membershipsCreated} membership${o.membershipsCreated===1?"":"s"}`);for(let a of o.results){if(a.status==="skipped"){console.log(`- ${a.domain}: skipped (${a.reason})`);continue}console.log(`- ${a.domain}: ${a.status} ${a.account?.externalId??""}, ${a.membersAdded} member${a.membersAdded===1?"":"s"} added${a.truncated?" (member cap reached)":""}`)}return}if(e==="upsert"){let r=Tue(t),o=await E("POST","/api/v1/accounts",r,t.company);if(t.json){D(o);return}console.log(`${o.created?"Created":"Updated"} account ${o.account.externalId}`),D0(o.account);return}if(!t.externalId||t.externalId.trim()==="")throw new A("Account external ID is required",400);let n=t.externalId.trim();if(e==="get"){let r=await E("GET",mu(n),void 0,t.company);if(t.json){D(r);return}if(D0(r.account),r.members&&r.members.length>0){console.log("Members:");for(let o of r.members)Uz(o)}return}if(e==="delete"){if(!await mt(`Delete account ${n} and its memberships? Contacts are kept.`,t)){console.log("Cancelled.");return}let o=await E("DELETE",mu(n),void 0,t.company);if(t.json){D(o);return}console.log(`Deleted account ${n} (${o.membersCleared} membership${o.membersCleared===1?"":"s"} cleared)`);return}if(e==="members"){let r=await E("GET",mu(n,"/members"),void 0,t.company);if(t.json){D(r);return}console.log(`Members of ${n} (${r.members.length})`);for(let o of r.members)Uz(o);return}if(e==="add-member"){let r={...Lz(t),...t.role!==void 0&&{role:t.role}},o=await E("POST",mu(n,"/members"),r,t.company);if(t.json){D(o);return}let a=o.member.email??o.member.externalId??"contact";console.log(`${o.member.created?"Added":"Updated"} ${a} as ${o.member.role} of ${n}`);return}if(e==="remove-member"){let r=Lz(t),o=await E("DELETE",mu(n,"/members"),r,t.company);if(t.json){D(o);return}console.log(o.removed?`Removed contact from ${n}`:`Contact was not a member of ${n}`);return}if(e==="events"){let r=new URLSearchParams;if(t.limit)r.set("limit",t.limit);let o=r.toString(),a=await E("GET",mu(n,`/events${o?`?${o}`:""}`),void 0,t.company);if(t.json){D(a);return}console.log(`Events for ${n} (${a.events.length})`);for(let c of a.events)console.log(`- ${c.eventTime} ${c.name} (${c.recipientCount} recipient${c.recipientCount===1?"":"s"})`);return}if(e==="event"){let r=$ue(t),o=await E("POST",mu(n,"/events"),r,t.company);if(t.json){D(o);return}console.log(`Recorded ${o.event.name} on ${n}; delivered to ${o.recipientCount} ${o.recipients==="none"?"nobody (timeline only)":`recipient${o.recipientCount===1?"":"s"} (${o.recipients})`}`);for(let a of o.deliveries){let c=a.skipped==="contact_deleted"?"skipped (contact deleted)":a.success?"ok":`failed: ${a.error??"unknown"}`;console.log(` - ${a.email??"contact"} (${a.role}): ${c}${a.automationsTriggered.length>0?`, sequences: ${a.automationsTriggered.length}`:""}`)}return}}catch(n){k(n),process.exit(1)}}function B0(e){if(e===void 0)return;return e.split(",").map((t)=>t.trim()).filter((t)=>t.length>0)}async function fu(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="handoff"){let a=B0(t.scopes),c=await E("POST","/api/v1/api-key-handoff",{...t.name!==void 0&&{name:t.name},...t.preset!==void 0&&{preset:t.preset},...a!==void 0&&{scopes:a},...t.replaces!==void 0&&{replaceApiKeyId:t.replaces}},t.company);if(t.json){D(c);return}let{handoff:l}=c;console.log("Open this link in a browser signed in as the key owner:"),console.log(l.url),console.log(""),console.log(`Key type: ${l.keyType}`),console.log(`Suggested name: ${l.name??"(dashboard default)"}`);let p=l.preset??(l.scopes?(l.permissions??du(l.scopes)).description:"(dashboard default)");if(console.log(`Suggested permissions: ${p}`),l.scopes!==null)console.log(`Scopes: ${l.scopes.join(", ")}`);if(l.replaces){let f=l.replaces.name??l.replaces.id;console.log(`Replaces: ${f}${l.replaces.isCurrentKey?" (the key you are using now)":""}`)}console.log(""),console.log(c.message);for(let f of c.nextSteps)console.log(`- ${f}`);return}if(e==="list"){let a=await E("GET","/api/v1/api-keys",void 0,t.company);if(t.json){D(a);return}if(a.apiKeys.length===0){console.log("No company API keys found.");return}for(let[c,l]of a.apiKeys.entries()){if(c>0)console.log("");console.log(`${l.name}${l.isCurrent?" (current)":""}`),console.log(`ID: ${l.id}`),console.log(`Prefix: ${l.prefix}`);let p=l.permissions??du(l.scopes);console.log(`Permission preset: ${p.preset}`),console.log(`Last used: ${ne(l.lastUsedAt)}`),console.log(`Created: ${ne(l.createdAt)}`)}return}if(e==="update"){if(!t.apiKeyId)throw new A("API key ID is required",400);let a=B0(t.scopes);if(t.name===void 0&&t.preset===void 0&&a===void 0)throw new A("Provide --name, --preset, or --scopes to update the key",400);let c=await E("PATCH",`/api/v1/api-keys/${encodeURIComponent(t.apiKeyId)}`,{...t.name!==void 0&&{name:t.name},...t.preset!==void 0&&{preset:t.preset},...a!==void 0&&{scopes:a}},t.company);if(t.json){D(c);return}console.log(c.message),console.log(`Name: ${c.apiKey.name}`),console.log(`ID: ${c.apiKey.id}`),console.log(`Prefix: ${c.apiKey.prefix}`);let l=c.apiKey.permissions??du(c.apiKey.scopes);if(console.log(`Permission preset: ${l.preset}`),console.log(`Permissions: ${l.description}`),c.apiKey.scopes!==null)console.log(`Scopes: ${c.apiKey.scopes.join(", ")}`);return}if(e==="revoke"||e==="delete"){if(!t.apiKeyId)throw new A("API key ID is required",400);if(!await mt(`Revoke API key ${t.apiKeyId}? This cannot be undone.`,t)){console.log("Aborted.");return}let a=await E("DELETE",`/api/v1/api-keys/${encodeURIComponent(t.apiKeyId)}`,void 0,t.company);if(t.json){D(a);return}console.log(a.message),console.log(`Name: ${a.apiKey.name}`),console.log(`ID: ${a.apiKey.id}`),console.log(`Prefix: ${a.apiKey.prefix}`);return}let n=B0(t.scopes),r=await E("POST","/api/v1/api-keys",{name:t.name,...t.preset!==void 0&&{preset:t.preset},...n!==void 0&&{scopes:n}},t.company);if(t.json){D(r);return}console.log(`Created API key: ${r.apiKey.name}`),console.log(`ID: ${r.apiKey.id}`),console.log(`Prefix: ${r.apiKey.prefix}`);let o=r.apiKey.permissions??du(r.apiKey.scopes);if(console.log(`Permission preset: ${o.preset}`),console.log(`Full access: ${o.fullAccess?"yes":"no"}`),console.log(`Permissions: ${o.description}`),r.apiKey.scopes!==null)console.log(`Scopes: ${r.apiKey.scopes.join(", ")}`);console.log(`Created: ${ne(r.apiKey.createdAt)}`),console.log(""),console.log(r.message),console.log(`Key: ${r.apiKey.key}`),console.log(`Env: ${r.instructions.example}`),console.log(r.instructions.note)}catch(n){k(n instanceof A?n:n),process.exit(1)}}var zz=["hourly","daily","weekly"];function Nue(e){let t=e.syncStatus==="disconnected"?"disconnected":!e.isActive?"paused":e.syncStatus==="error"?"error":e.syncStatus;if(console.log(`- ${e.segmentName??e.segmentId} -> "${e.audienceName}" (${e.adAccountId})`),console.log(` id: ${e.id} | ${e.frequency} | status: ${t} | last sync: ${e.lastSyncAt??"never"} | uploaded: ${e.lastSyncedCount}`),e.lastSyncError)console.log(` last error: ${e.lastSyncError}`)}function Mz(e){if(e===void 0)return"daily";if(!zz.includes(e))k(new A(`Invalid frequency "${e}". Use one of: ${zz.join(", ")}.`,400)),process.exit(1);return e}function x0(e,t){if(!e||e.trim().length===0)k(new A(`${t} is required.`,400)),process.exit(1);return e.trim()}async function gu(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="list"){let o=await E("GET","/api/v1/audience-syncs",void 0,t.company);if(t.json){console.log(JSON.stringify(o,null,2));return}console.log(`Audience syncs (${o.audienceSyncs.length})`);for(let a of o.audienceSyncs)Nue(a);return}if(e==="ad-accounts"){let o=await E("GET","/api/v1/ad-accounts",void 0,t.company);if(t.json){console.log(JSON.stringify(o,null,2));return}console.log(`Ad accounts (${o.adAccounts.length})`);for(let a of o.adAccounts)console.log(`- ${a.name} (${a.id})`);return}if(e==="create"){if(t.segment&&t.template)k(new A("Provide either --segment or --template, not both.",400)),process.exit(1);if(!t.segment&&!t.template)k(new A("Provide --segment <id> or --template <id> (for example --template recent-buyers).",400)),process.exit(1);let o=await E("POST","/api/v1/audience-syncs",{...t.segment?{segmentId:t.segment}:{},...t.template?{predefinedSegmentId:t.template}:{},adAccountId:x0(t.adAccount,"--ad-account"),audienceName:x0(t.name,"--name"),frequency:Mz(t.frequency)},t.company);if(t.json){console.log(JSON.stringify(o,null,2));return}console.log(`Created audience sync: ${o.audienceSync.segmentName??o.audienceSync.segmentId} -> "${o.audienceSync.audienceName}"`),console.log(`ID: ${o.audienceSync.id}`),console.log(`Frequency: ${o.audienceSync.frequency}`),console.log("The first upload to Meta is running now.");return}let n=x0(t.id,"--id");if(e==="update"){let o={};if(t.frequency!==void 0)o.frequency=Mz(t.frequency);if(t.active!==void 0){if(t.active!=="true"&&t.active!=="false")k(new A('--active must be "true" or "false".',400)),process.exit(1);o.isActive=t.active==="true"}if(Object.keys(o).length===0)k(new A("Provide --frequency and/or --active to update.",400)),process.exit(1);let a=await E("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(n)}`,o,t.company);if(t.json){console.log(JSON.stringify(a,null,2));return}console.log(`Updated audience sync ${a.audienceSync.id}: ${a.audienceSync.frequency}, ${a.audienceSync.isActive?"active":"paused"}`);return}if(e==="delete"){let o=await E("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(n)}`,void 0,t.company);if(t.json){console.log(JSON.stringify(o,null,2));return}console.log(`Removed audience sync ${n}. The Meta audience itself is kept.`);return}let r=await E("POST",`/api/v1/audience-syncs/${encodeURIComponent(n)}/sync`,void 0,t.company);if(t.json){console.log(JSON.stringify(r,null,2));return}console.log(`Queued sync for ${n}.`)}catch(n){k(n instanceof A?n:n),process.exit(1)}}var Oue={requested:"Requested",collecting:"Collecting emails",available:"In the gallery",declined:"Not added"};function Hz(e){let t=e.status==="available"&&e.brand?e.brand.url:e.status==="declined"?e.declineReason:e.note;return[`${e.domain} · ${Oue[e.status]}`,t?` ${t}`:null,` ID: ${e.id}`].filter(Boolean).join(`
|
|
267
267
|
`)}async function _0(){if(!await H())k(J()),process.exit(1)}async function Pue(e){await _0();try{let t=await E("GET","/api/v1/gallery/brand-requests",void 0,e.company);if(e.json)return D(t);if(t.requests.length===0){console.log("No brand requests yet. Ask for one with `sequenzy brand-requests add competitor.com`.");return}for(let n of t.requests)console.log(Hz(n))}catch(t){k(t),process.exit(1)}}async function Fue(e,t){await _0();try{let n=await E("POST","/api/v1/gallery/brand-requests",{website:e,...t.note?{note:t.note}:{}},t.company);if(t.json)return D(n);console.log(n.message),console.log(Hz(n.request))}catch(n){k(n),process.exit(1)}}async function que(e,t){await _0();try{let n=await E("DELETE",`/api/v1/gallery/brand-requests/${encodeURIComponent(e)}`,void 0,t.company);if(t.json)return D(n);console.log(`Removed brand request ${n.id}`)}catch(n){k(n),process.exit(1)}}function Gz(e,t={list:Pue,add:Fue,remove:que}){let n=e.command("brand-requests").description("Ask for brands (like competitors) to be added to the email gallery"),r=n.command("list",{isDefault:!0}).description("Your requests and where each one stands").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((c)=>t.list(c)),o=n.command("add <website>").description("Request a brand by its website, e.g. competitor.com").option("--note <text>","What you want to see from them (up to 300 characters)").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((c,l)=>t.add(c,l)),a=n.command("remove <id>").description("Withdraw a request").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((c,l)=>t.remove(c,l));S(n,{notes:["Requests move from Requested to Collecting emails once the brand is added, then In the gallery once its emails are in; you then find them with `sequenzy references`. Asking again for the same website keeps one request."],examples:['sequenzy brand-requests add competitor.com --note "Their onboarding emails"',"sequenzy brand-requests","sequenzy brand-requests remove req_123"]}),S(o,{examples:["sequenzy brand-requests add https://competitor.com/pricing"]}),S(r,{examples:["sequenzy brand-requests list --json"]}),S(a,{examples:["sequenzy brand-requests remove req_123"]})}var Jz=["close","fresh","bold"],Lue=3000,Uue=300;function jue(e){if(!e.id)throw new A("Campaign ID is required",400);return e.id}function ep(e){if(!e.variationId)throw new A("Variation ID is required",400);return e.variationId}function zue(e){let t=[e.status!=="ready"?e.status:null,e.inUse?"in campaign":null].filter(Boolean);return`- ${e.label} ${e.name} [${e.id}]${t.length>0?` (${t.join(", ")})`:""}`}function al(e){if(console.log(zue(e)),e.summary)console.log(` ${e.summary}`);if(e.error)console.log(` Error: ${e.error}`);if(e.emailTheme||e.fontFamily)console.log(` Own look: ${[e.emailTheme?"theme":null,e.fontFamily?`font ${e.fontFamily}`:null].filter(Boolean).join(", ")}`)}function Vz(e){if(e.style===void 0)return{};if(!Jz.includes(e.style))throw new A(`--style must be one of ${Jz.join(", ")}`,400);return{style:e.style}}function Kz(e){return(e.sections??"").split(",").map((t)=>t.trim()).filter(Boolean)}function Wz(e){let t=Fe(e.emailThemeJson,e.emailThemeFile,"email-theme");if(t!==void 0&&t!==null&&(typeof t!=="object"||Array.isArray(t)))throw new A("email-theme JSON must be an object or null",400);return{...t!==void 0?{emailTheme:t}:{},...e.fontFamily!==void 0?{fontFamily:e.fontFamily.trim().toLowerCase()==="null"?null:e.fontFamily}:{}}}function Mue(e){if(e.resetPosition)return{position:null};if(e.position===void 0)return{};let[t,n,r]=e.position.split(",").map((a)=>a.trim()),o={x:Number(t),y:Number(n)};if(r!==void 0||!t||!n||!Number.isFinite(o.x)||!Number.isFinite(o.y))throw new A("--position must be two numbers: x,y",400);return{position:o}}function Zz(e){return ws({html:e.html,htmlFile:e.htmlFile,blocksJson:e.blocksJson,blocksFile:e.blocksFile})}async function Yz(e,t){return(await E("GET",`/api/v1/campaigns/${e}/variations`,void 0,t)).variations}async function Hue(e,t,n){let r=at(n.timeout,"--timeout")??Uue,o=Date.now()+r*1000;for(;;){let a=(await Yz(e,n.company)).filter((c)=>t.includes(c.id));if(a.every((c)=>c.status!=="generating"))return a;if(Date.now()>o)throw new A(`Variations are still generating after ${r}s. Check later with: sequenzy campaigns variations list ${e}`,408);await new Promise((c)=>setTimeout(c,Lue))}}async function Bs(e,t){if(!await H())k(J()),process.exit(1);try{let n=jue(t),r=`/api/v1/campaigns/${n}/variations`;if(e==="list"){let l=await Yz(n,t.company);if(t.json)return D({success:!0,variations:l});if(l.length===0){console.log("No variations yet."),console.log(`Generate some: sequenzy campaigns variations generate ${n} --prompt "Shorter and warmer"`);return}console.log(`Variations (${l.length})`);for(let p of l)al(p);return}if(e==="get"){let l=await E("GET",`${r}/${ep(t)}`,void 0,t.company);if(t.json)return D(l);al(l.variation);return}if(e==="create"){if(!t.name)throw new A("--name is required",400);let l=Zz(t);if(!l.html&&!l.blocks)throw new A("Provide the content with --blocks-json, --blocks-file, --html or --html-file",400);let p=await E("POST",r,{name:t.name,...l,...t.summary!==void 0?{summary:t.summary}:{},...t.subject!==void 0?{subject:t.subject}:{},...t.previewText!==void 0?{previewText:t.previewText}:{},...t.parent?{parentVariationId:t.parent}:{},...Wz(t)},t.company);if(t.json)return D(p);_n(p),console.log("Variation saved:"),al(p.variation);return}if(e==="generate"){if(!t.prompt?.trim())throw new A("--prompt is required",400);let l=at(t.count,"--count"),p=await E("POST",`${r}/generate`,{prompt:t.prompt,...l!==void 0?{count:l}:{},...t.parent?{parentVariationId:t.parent}:{},...Vz(t)},t.company),f=p.variations.map((y)=>y.id);if(!t.wait){if(t.json)return D(p);console.log(`Generating ${f.length} variations:`);for(let y of p.variations)al(y);console.log(`Check progress: sequenzy campaigns variations list ${n}`);return}let h=await Hue(n,f,t);if(t.json)return D({success:!0,variations:h});for(let y of h)al(y);return}if(e==="update"){let l=Zz(t),p=await E("PATCH",`${r}/${ep(t)}`,{...l,...t.name!==void 0?{name:t.name}:{},...t.summary!==void 0?{summary:t.summary}:{},...t.subject!==void 0?{subject:t.subject}:{},...t.previewText!==void 0?{previewText:t.previewText}:{},...Wz(t),...Mue(t)},t.company);if(t.json)return D(p);_n(p),console.log("Variation updated:"),al(p.variation);return}if(e==="discard"){let l=ep(t),p=await E("DELETE",`${r}/${l}`,void 0,t.company);if(t.json)return D(p);console.log(`Variation discarded. Undo with: sequenzy campaigns variations restore ${n} ${l}`);return}if(e==="restore"){let l=await E("POST",`${r}/${ep(t)}/restore`,void 0,t.company);if(t.json)return D(l);console.log("Variation restored:"),al(l.variation);return}if(e==="use"){let l=await E("POST",`${r}/${ep(t)}/use`,void 0,t.company);if(t.json)return D(l);if(console.log(`${l.variation.label} ${l.variation.name} is now in the campaign.`),l.savedPrevious)console.log(`The previous content is saved as ${l.savedPrevious.label} [${l.savedPrevious.id}].`);return}if(e==="edit"){if(!t.prompt?.trim())throw new A("--prompt is required",400);let l=Kz(t),p=await E("POST",`${r}/${ep(t)}/edit`,{prompt:t.prompt,...l.length>0?{sectionIds:l}:{}},t.company);if(t.json)return D(p);console.log("Variation changed:"),al(p.variation);return}if(!t.prompt?.trim())throw new A("--prompt is required",400);let o=Kz(t);if(o.length===0)throw new A("--sections needs at least one block id",400);let a=at(t.count,"--count"),c=await E("POST",`${r}/section-options`,{prompt:t.prompt,sectionIds:o,...a!==void 0?{count:a}:{},...t.variation?{variationId:t.variation}:{},...Vz(t)},t.company);if(t.json)return D(c);console.log(`Options (${c.options.length}):`),c.options.forEach((l,p)=>{console.log(`${p+1}. ${l.name}`),console.log(` ${l.summary}`)}),console.log("Nothing was saved. Use --json to get each option's replacement blocks, then apply one with `sequenzy campaigns variations update`.")}catch(n){k(n),process.exit(1)}}function o2(e){let t=e?.trim();return t?t:void 0}function i2(e){if(e.previewText!==void 0&&e.preheaderText!==void 0)throw new A("Provide either --preview-text or --preheader-text, not both",400);return e.previewText??e.preheaderText}function Gue(e,t){if(!e.name)throw new A("Campaign name is required",400);let n=o2(e.prompt);if(e.prompt!==void 0&&n===void 0)throw new A("--prompt cannot be empty",400);if(n!==void 0&&(t.html!==void 0||t.blocks!==void 0))throw new A("Provide either --prompt, --html/--html-file, or --blocks-json/--blocks-file, not multiple content sources",400);if(n===void 0&&(e.style!==void 0||e.tone!==void 0))throw new A("--style and --tone require --prompt",400);if(s2(e,t),!e.subject&&n===void 0)throw new A("Campaign subject is required unless --prompt is provided",400)}function Jue(e,t,n={},r=void 0){if(e.replyTo!==void 0&&e.replyProfile!==void 0)throw new A("Provide either --reply-to or --reply-profile, not both",400);let o=i2(e),a=s2(e,t),c=f2(e),l=p2(e);if(e.name===void 0&&e.subject===void 0&&o===void 0&&e.trackingCode===void 0&&t.html===void 0&&t.blocks===void 0&&a===void 0&&e.fromEmail===void 0&&e.fromName===void 0&&e.senderProfileId===void 0&&e.replyTo===void 0&&e.replyToName===void 0&&e.replyProfile===void 0&&e.label===void 0&&n.campaignData===void 0&&n.computedLists===void 0&&r===void 0&&c===void 0&&e.sendTimeWindowHours===void 0&&l===void 0)throw new A("Provide at least one of: --name, --subject, --preview-text, --preheader-text, --tracking-code, --html, --html-file, --blocks-json, --blocks-file, --email-preset, --from-email, --from-name, --sender-profile-id, --reply-to, --reply-to-name, --reply-profile, --label, --campaign-data-json, --campaign-data-file, --computed-lists-json, --computed-lists-file, --segment, --target-lists-json, --target-lists-file, --clear-target-lists, --send-time-optimization, --disable-send-time-optimization, --send-time-window-hours, --max-recipients, --clear-max-recipients",400);let p=m2(e.sendTimeWindowHours);return{name:e.name,subject:e.subject,...o!==void 0&&{previewText:o},...e.trackingCode!==void 0&&{trackingCode:e.trackingCode},html:t.html,blocks:t.blocks,...a!==void 0&&{emailPreset:a},...e.fromEmail!==void 0&&{fromEmail:e.fromEmail},...e.fromName!==void 0&&{fromName:e.fromName},...e.senderProfileId!==void 0&&{senderProfileId:e.senderProfileId},replyTo:e.replyTo,...e.replyToName!==void 0&&{replyToName:e.replyToName},replyProfileId:e.replyProfile,labels:e.label,...n.campaignData!==void 0&&{campaignData:n.campaignData},...n.computedLists!==void 0&&{computedLists:n.computedLists},...r!==void 0&&{targetLists:r},...c!==void 0&&{sendTimeOptimization:c},...p!==void 0&&{sendTimeWindowHours:p},...l!==void 0&&{maxRecipients:l}}}function s2(e,t){if(e.emailPreset===void 0)return;if(e.emailPreset!=="branded"&&e.emailPreset!=="minimal")throw new A("--email-preset must be branded or minimal",400);if(t.html!==void 0)throw new A("--email-preset is only supported for native Sequenzy blocks and cannot be combined with --html/--html-file",400);return e.emailPreset}function Vue(e){let t=Fe(e.campaignDataJson,e.campaignDataFile,"campaign-data"),n=Fe(e.computedListsJson,e.computedListsFile,"computed-lists");if(t!==void 0&&t!==null&&(typeof t!=="object"||Array.isArray(t)))throw new A("campaign-data JSON must be an object or null",400);if(n!==void 0&&!Array.isArray(n))throw new A("computed-lists JSON must be an array",400);return{...t!==void 0&&{campaignData:t},...n!==void 0&&{computedLists:n}}}function a2(e){let t=Fe(e.targetListsJson,e.targetListsFile,"target-lists");if(t!==void 0&&(typeof t!=="object"||t===null||Array.isArray(t)))throw new A("target-lists JSON must be an object",400);return t}function c2(e,t){if([e.segment!==void 0,e.lists!==void 0,t!==void 0].filter(Boolean).length>1)throw new A("Provide at most one of --segment, --lists, or target list options",400)}function l2(e){let t=a2(e);if(c2(e,t),e.segment!==void 0)return{type:"segment",segmentId:e.segment};let n=u2(e);if(n!==void 0)return{type:"lists",listIds:n};return t}function u2(e){if(e.lists===void 0)return;let t=e.lists.flatMap((n)=>n.split(",")).map((n)=>n.trim()).filter((n)=>n.length>0);if(t.length===0)throw new A("--lists requires at least one list ID",400);return t}function Kue(e){let t=l2(e);if(e.clearTargetLists){if(t!==void 0)throw new A("Provide either --clear-target-lists or an audience option, not both",400);return null}return t}function d2(e){if(e===void 0)return;let t=Number(e);if(!Number.isInteger(t)||t<1||t>72)throw new A("--spread-over-hours must be an integer between 1 and 72",400);return t}var Wue=1e7;function Zue(e){if(e===void 0)return;let t=/^\d+$/.test(e.trim())?Number(e.trim()):NaN;if(!Number.isInteger(t)||t<1||t>Wue)throw new A("--max-recipients must be an integer between 1 and 10000000",400);return t}function p2(e){if(e.clearMaxRecipients===!0&&e.maxRecipients!==void 0)throw new A("Use either --max-recipients or --clear-max-recipients, not both",400);if(e.clearMaxRecipients===!0)return null;return Zue(e.maxRecipients)}function m2(e){if(e===void 0)return;let t=Number(e);if(!Number.isInteger(t)||t<1||t>24)throw new A("--send-time-window-hours must be an integer between 1 and 24",400);return t}function f2(e){if(e.sendTimeOptimization===!0&&e.disableSendTimeOptimization===!0)throw new A("Use either --send-time-optimization or --disable-send-time-optimization, not both",400);if(e.disableSendTimeOptimization===!0)return!1;return e.sendTimeOptimization}var Yue=new Set(["campaign","ab_test","variant"]);function Xue(e){let t=d2(e.spreadOverHours);return{...t!==void 0&&{spreadOverHours:t}}}function ede(e){let t=e.mode??"campaign";if(!Yue.has(t))throw new A("--mode must be one of: campaign, ab_test, variant",400);if(t==="variant"&&!e.variantId)throw new A("--variant-id is required when --mode is variant",400);if(t!=="variant"&&e.variantId!==void 0)throw new A("--variant-id requires --mode variant",400);return{mode:t,...e.variantId!==void 0&&{variantId:e.variantId}}}function tde(e){if(e===void 0)return;if(e!=="weekly"&&e!=="monthly")throw new A("--repeat must be one of: weekly, monthly",400);return e}function nde(e,t){if(!e.at?.trim())throw new A("--at is required",400);let n=d2(e.spreadOverHours),r=f2(e),o=m2(e.sendTimeWindowHours),a=p2(e),c=tde(e.repeat);if(e.inRecipientTimezone&&!e.scheduledTimezone?.trim())throw new A("--in-recipient-timezone requires --scheduled-timezone (the IANA zone --at refers to, e.g. America/New_York)",400);return{scheduledAt:e.at,...t!==void 0&&{targetLists:t},...r!==void 0&&{sendTimeOptimization:r},...o!==void 0&&{sendTimeWindowHours:o},...n!==void 0&&{spreadOverHours:n},...a!==void 0&&{maxRecipients:a},...c!==void 0&&{recurringInterval:c},...e.inRecipientTimezone!==void 0&&{sendInRecipientTimezone:e.inRecipientTimezone},...e.scheduledTimezone!==void 0&&{scheduledTimezone:e.scheduledTimezone.trim()}}}function Xz(e){if(!e.replyToEmail)return"None";return e.replyToName?`${e.replyToName} <${e.replyToEmail}>`:e.replyToEmail}function rb(e){return e&&e.length>0?e.join(", "):"None"}function e2(e){if(e.sendInRecipientTimezone)return e.scheduledTimezone?`Recipient's local time (wall clock from ${e.scheduledTimezone})`:"Recipient's local time";if(e.sendTimeOptimization)return`Optimal send time (${e.sendTimeWindowHours??12}h window)`;if(e.spreadOverHours)return`Spread over ${e.spreadOverHours}h`;return"No pacing recorded"}function t2(e){if(!e.maxRecipients||e.maxRecipients<1)return null;return`First ${e.maxRecipients.toLocaleString("en-US")} recipients`}function n2(e,t=""){if(e===void 0||e==="email")return;console.log(`${t}Channel: ${e.toUpperCase()} (managed from the dashboard)`)}function k0(e){let t=tz(e);if(!t)return"Not set (choose it when scheduling)";switch(t.type){case"all":return"All active subscribers";case"lists":return t.listIds.length>0?`Lists: ${t.listIds.join(", ")}`:"Lists: none selected";case"segment":return t.segmentId?`Segment: ${t.segmentId}`:"Segment: none selected";case"filtered":return`Filtered (${t.filters.length} filter${t.filters.length===1?"":"s"})`;case"rules":return`Rules (${t.include.length} include, ${(t.exclude??[]).length} exclude${t.includedSubscriberIds?.length?`, ${t.includedSubscriberIds.length} selected contacts`:""})`}}function ob(e){if(e.length===0)return"none";return e.map((t)=>t.missing?`${t.id} (missing)`:`${t.name} [${t.id}]`).join(", ")}function r2(e){if(e.type==="lists")return`lists ${ob(e.lists??[])}`;if(e.type==="segments")return`segments ${ob(e.segments??[])}`;if(e.type==="filtered")return`${e.filters?.length??0} filter condition(s)`;return"all active subscribers"}function rde(e){let{audience:t}=e;if(console.log(e.campaignName),console.log(`ID: ${e.campaignId}`),console.log(`Status: ${e.status}`),e.scheduledAt)console.log(`Scheduled: ${ne(e.scheduledAt)}`);if(console.log(""),console.log(`Targeting: ${t.type}`),console.log(`Recipients: ${e.recipientCount}`),console.log(`Summary: ${t.summary}`),t.isUnset)console.log("WARNING: targeting is not set. Scheduling sends to every active subscriber.");if(t.lists.length>0)console.log(`Lists: ${ob(t.lists)}`);if(t.segments.length>0)console.log(`Segments: ${ob(t.segments)}`);if(t.filters.length>0)console.log(`Filters: ${t.filters.length} condition(s)`);for(let n of t.include)console.log(`Include: ${r2(n)}`);for(let n of t.exclude)console.log(`Exclude: ${r2(n)}`);if(t.excludedCampaignOpenerIds.length>0)console.log(`Excluding openers of: ${t.excludedCampaignOpenerIds.join(", ")}`);if(t.excludedSubscriberIds.length>0)console.log(`Excluded subscribers: ${t.excludedSubscriberIds.length}`);if(t.includedSubscriberIds.length>0)console.log(`Individually added subscribers: ${t.includedSubscriberIds.length}`)}function ode(e,t){if(t===void 0)return e;let n=ct({companyId:t,campaignId:e.id});return{...e,...n.urls.campaign!==void 0&&{url:n.urls.campaign},...n.urls.campaignPreview!==void 0&&{previewUrl:n.urls.campaignPreview}}}function ide(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},...at(e.attributionWindowHours,"--attribution-window-hours")!==void 0&&{attributionWindowHours:at(e.attributionWindowHours,"--attribution-window-hours")},...e.isActive&&{isActive:!0},...e.notActive&&{isActive:!1}}}async function ur(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="from-audience"){let p=Fe(t.selectionJson,t.selectionFile,"selection");if(!p||typeof p!=="object"||Array.isArray(p))throw new A("Provide a selection object with --selection-json or --selection-file",400);let f=await E("POST","/api/v1/campaigns/from-audience",{...t.name?{name:t.name}:{},selection:p},t.company);if(t.json){D(f);return}console.log(`Created draft: ${f.campaign.name} (${f.campaign.id})`),console.log(`Saved ${f.audience.selectedCount} contacts; ${f.audience.eligibleCount} currently eligible for email.`),console.log("Review the content and audience before scheduling. Email eligibility is checked again before sending.");return}if(e==="list"){let p=new URLSearchParams;if(t.status)p.set("status",t.status);if(t.label)for(let R of t.label)p.append("label",R);if(t.limit)p.set("limit",t.limit);if(t.offset)p.set("offset",t.offset);let f=await E("GET",`/api/v1/campaigns${p.size>0?`?${p.toString()}`:""}`,void 0,t.company),h=await Ht(t.company),y=h!==void 0?ct({companyId:h,status:t.status}):void 0,v=f.campaigns.map((R)=>ode(R,h));if(t.json){D({...f,campaigns:v,...y!==void 0&&{appUrls:y.urls}});return}let C=f.pagination;console.log(C?`Campaigns (${f.campaigns.length} of ${C.total})`:`Campaigns (${f.campaigns.length})`);for(let R of v){if(console.log(`- ${R.name} [${R.id}]`),console.log(` Subject: ${R.subject}`),R.emailId)console.log(` Format: ${Cs(R.emailPreset)}`);if(console.log(` Status: ${R.status}`),R.status==="draft"&&R.hasAudience)console.log(" Audience: set (review eligibility before sending)");if(n2(R.type," "),R.rejectionComment)console.log(` Rejection feedback: ${R.rejectionComment}`);if(console.log(` Labels: ${rb(R.labels)}`),console.log(` Created: ${ne(R.createdAt)}`),Ce(" URL",R.url),Ce(" Preview URL",R.previewUrl),R.scheduledAt)console.log(` Scheduled: ${ne(R.scheduledAt)}`);if(R.sentAt)console.log(` Sent: ${ne(R.sentAt)}`);let F=e2(R);if(F!=="No pacing recorded")console.log(` Delivery: ${F}`);let L=t2(R);if(L)console.log(` Recipient limit: ${L}`)}if(C?.hasMore)console.log(`More campaigns available. Re-run with --offset ${C.offset+C.count} to fetch the next page.`);return}let n=ws({html:t.html,htmlFile:t.htmlFile,blocksJson:t.blocksJson,blocksFile:t.blocksFile});if(e==="create"){Gue(t,n);let p=o2(t.prompt),f=i2(t),h=a2(t);c2(t,h);let y=u2(t),v=await E("POST","/api/v1/campaigns",{name:t.name,...t.subject!==void 0&&{subject:t.subject},...f!==void 0&&{previewText:f},...p!==void 0&&{prompt:p},...t.style!==void 0&&{style:t.style},...t.tone!==void 0&&{tone:t.tone},...n.html!==void 0&&{html:n.html},...n.blocks!==void 0&&{blocks:n.blocks},...t.emailPreset!==void 0&&{emailPreset:t.emailPreset},...t.label!==void 0&&{labels:t.label},...t.trackingCode!==void 0&&{trackingCode:t.trackingCode},...t.status!==void 0&&{status:t.status},...t.sentAt!==void 0&&{sentAt:t.sentAt},...t.fromEmail!==void 0&&{fromEmail:t.fromEmail},...t.fromName!==void 0&&{fromName:t.fromName},...t.senderProfileId!==void 0&&{senderProfileId:t.senderProfileId},...t.replyTo!==void 0&&{replyTo:t.replyTo},...t.replyToName!==void 0&&{replyToName:t.replyToName},...t.replyProfile!==void 0&&{replyProfileId:t.replyProfile},...t.segment!==void 0&&{segmentId:t.segment},...y!==void 0&&{listIds:y},...h!==void 0&&{targetLists:h}},t.company),C=await Ht(t.company),R=v.campaign?.id??v.campaignId,F=C!==void 0&&R!==void 0?ct({companyId:C,campaignId:R}):void 0;if(t.json){D({...v,...v.campaign!==void 0&&F?.urls.campaign!==void 0&&{campaign:{...v.campaign,url:F.urls.campaign,previewUrl:F.urls.campaignPreview}},...F!==void 0&&{appUrls:F.urls}});return}if(_n(v),console.log(`Created campaign: ${v.campaign?.name??t.name}`),console.log(`ID: ${v.campaign?.id??"Unknown"}`),console.log(`Status: ${v.campaign?.status??"Unknown"}`),v.campaign?.sentAt)console.log(`Sent: ${ne(v.campaign.sentAt)}`);if(console.log(`Subject: ${v.campaign?.subject??t.subject??"Generated"}`),console.log(`Labels: ${rb(v.campaign?.labels)}`),console.log(`Audience: ${k0(v.campaign?.targetLists)}`),p!==void 0)console.log("Content: generated from prompt");Ce("URL",F?.urls.campaign??v.campaign?.url),Ce("Preview URL",F?.urls.campaignPreview??v.campaign?.previewUrl);return}if(!t.id)throw new A("Campaign ID is required",400);if(e==="unschedule"||e==="cancel"||e==="pause"){let p=await E("POST",`/api/v1/campaigns/${t.id}/${e}`,void 0,t.company);if(t.json){D(p);return}let f=e==="unschedule"?"unscheduled":e==="cancel"?"cancelled":"paused";console.log(`Campaign ${f}: ${p.campaign?.name??t.id}`),console.log(`ID: ${p.campaign?.id??t.id}`),console.log(`Status: ${p.campaign?.status??f}`),Ce("URL",p.campaign?.url);return}if(e==="resume"){let p=await E("POST",`/api/v1/campaigns/${t.id}/resume`,Xue(t),t.company);if(t.json){D(p);return}console.log(`Campaign resumed: ${p.campaign?.name??t.id}`),console.log(`ID: ${p.campaign?.id??t.id}`),console.log(`Status: ${p.campaign?.status??"sending"}`),Ce("URL",p.campaign?.url);return}if(e==="delete"){if(!await mt(`Delete campaign ${t.id}?`,t)){console.log("Aborted.");return}let p=await E("DELETE",`/api/v1/campaigns/${t.id}`,void 0,t.company);if(t.json){D(p);return}console.log(`Deleted campaign: ${t.id}`);return}if(e==="duplicate"){let p=await E("POST",`/api/v1/campaigns/${t.id}/duplicate`,ede(t),t.company);if(t.json){D(p);return}if(console.log(`Duplicated campaign: ${p.campaign?.name??t.id}`),console.log(`New campaign ID: ${p.campaign?.id??"Unknown"}`),console.log(`Status: ${p.campaign?.status??"draft"}`),p.emailId!==void 0)console.log(`New email ID: ${p.emailId}`);Ce("URL",p.campaign?.url),Ce("Preview URL",p.campaign?.previewUrl);return}if(e==="resend-to-non-openers"){let p=await E("POST",`/api/v1/campaigns/${t.id}/resend-to-non-openers`,void 0,t.company);if(t.json){D(p);return}if(console.log(`Created non-opener resend draft: ${p.campaign?.name??t.id}`),console.log(`New campaign ID: ${p.campaign?.id??"Unknown"}`),console.log(`Status: ${p.campaign?.status??"draft"}`),p.estimatedNonOpenerCount!==void 0)console.log(`Estimated recipients: ~${p.estimatedNonOpenerCount}`);Ce("URL",p.campaign?.url);return}if(e==="schedule"){let p=l2(t),f=await E("POST",`/api/v1/campaigns/${t.id}/schedule`,nde(t,p),t.company),h=await Ht(t.company),y=h!==void 0?ct({companyId:h,campaignId:t.id}):void 0;if(t.json){D({...f,...f.campaign!==void 0&&y?.urls.campaign!==void 0&&{campaign:{...f.campaign,url:y.urls.campaign,previewUrl:y.urls.campaignPreview}},previewUrl:f.previewUrl??y?.urls.campaignPreview??void 0,...y!==void 0&&{appUrls:y.urls}});return}console.log(`Scheduled campaign: ${f.campaign?.name??t.id}`),console.log(`ID: ${f.campaign?.id??t.id}`),console.log(`Status: ${f.campaign?.status??"scheduled"}`),console.log(`Scheduled: ${ne(f.scheduledAt??f.campaign?.scheduledAt??null)}`),Ce("URL",y?.urls.campaign??f.campaign?.url),Ce("Preview URL",f.previewUrl??y?.urls.campaignPreview??f.campaign?.previewUrl);return}if(e==="update"){let p=Vue(t),f=Kue(t),h=Jue(t,n,p,f),y=await E("PUT",`/api/v1/campaigns/${t.id}`,h,t.company),v=await Ht(t.company),C=v!==void 0?ct({companyId:v,campaignId:t.id}):void 0;if(t.json){D({...y,...y.campaign!==void 0&&C?.urls.campaign!==void 0&&{campaign:{...y.campaign,url:C.urls.campaign,previewUrl:C.urls.campaignPreview}},...C!==void 0&&{appUrls:C.urls}});return}if(_n(y),console.log(`Updated campaign: ${y.campaign?.name??t.id}`),console.log(`ID: ${y.campaign?.id??t.id}`),console.log(`Status: ${y.campaign?.status??"Unknown"}`),console.log(`Labels: ${rb(y.campaign?.labels)}`),console.log(`Audience: ${k0(y.campaign?.targetLists)}`),Ce("URL",C?.urls.campaign??y.campaign?.url),Ce("Preview URL",C?.urls.campaignPreview??y.campaign?.previewUrl),y.campaign)console.log(`Reply-To: ${Xz(y.campaign)}`);return}if(e==="test"){if(!t.to)throw new A("--to is required",400);let p=await E("POST",`/api/v1/campaigns/${t.id}/test`,{to:t.to},t.company),f=await Ht(t.company),h=f!==void 0?ct({companyId:f,campaignId:t.id,...p.emailSendId?{emailSendId:p.emailSendId}:{}}):void 0;if(t.json){D({...p,...h!==void 0&&{appUrls:h.urls}});return}if(console.log(p.message??`Test requested for ${t.id}`),p.emailSendId)console.log(`Email send ID: ${p.emailSendId}`);Ce("URL",h?.urls.campaign),Ce("Preview URL",h?.urls.campaignPreview),Ce("Email send URL",h?.urls.emailSend);return}if(e==="audience"){let p=await E("GET",`/api/v1/campaigns/${t.id}/audience`,void 0,t.company);if(t.json){D(p);return}rde(p);return}if(e==="share"){let p=await E("POST",`/api/v1/campaigns/${t.id}/share-link`,void 0,t.company);if(t.json){D(p);return}console.log(p.created?"Public link created.":"Public link already active."),Ce("Share URL",p.shareUrl),console.log("Anyone with the link sees an anonymized copy - no subscriber data, no tracking.");return}if(e==="unshare"){let p=await E("DELETE",`/api/v1/campaigns/${t.id}/share-link`,void 0,t.company);if(t.json){D(p);return}console.log(p.revoked?"Public link revoked. The old URL now returns 404.":"No public link to revoke.");return}if(e==="goals"){if(!t.id)throw new A("Campaign ID is required",400);let p=await E("GET",`/api/v1/campaigns/${t.id}/goals`,void 0,t.company);if(t.json)return D(p);let f=Array.isArray(p.goals)?p.goals:[],h=Array.isArray(p.companyGoals)?p.companyGoals:[];console.log(`Campaign goals (${f.length})`);for(let y of f){if(typeof y!=="object"||y===null)continue;let v=y;console.log(`- ${String(v.name??"Unnamed goal")} [${String(v.id??"unknown")}]`)}if(h.length>0){console.log(`Company-wide goals (${h.length})`),console.log("Apply automatically after an open or click; managed in Settings.");for(let y of h){if(typeof y!=="object"||y===null)continue;let v=y;console.log(`- ${String(v.name??"Unnamed goal")} [${String(v.id??"unknown")}] (${String(v.attributionWindowHours)}h window${v.isActive===!1?", inactive":""})`)}}return}if(e==="goal-create"||e==="goal-update"){if(!t.id)throw new A("Campaign ID is required",400);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 p=await E(e==="goal-create"?"POST":"PATCH",`/api/v1/campaigns/${t.id}/goals${t.goalId?`/${t.goalId}`:""}`,ide(t),t.company);if(t.json)return D(p);let f=p.goal;if(console.log(`${e==="goal-create"?"Created":"Updated"} campaign goal: ${String(f?.name??t.name??t.goalId)}`),f?.id)console.log(`ID: ${String(f.id)}`);return}if(e==="goal-delete"){if(!t.id)throw new A("Campaign ID is required",400);if(!t.goalId)throw new A("Goal ID is required",400);let p=await E("DELETE",`/api/v1/campaigns/${t.id}/goals/${t.goalId}`,void 0,t.company);if(t.json)return D(p);console.log(`Deleted campaign goal: ${t.goalId}`);return}let r=await E("GET",`/api/v1/campaigns/${t.id}`,void 0,t.company),o=await Ht(t.company),a=o!==void 0?ct({companyId:o,campaignId:t.id}):void 0;if(t.json){D({...r,...a?.urls.campaign!==void 0&&{campaign:{...r.campaign,url:a.urls.campaign,previewUrl:a.urls.campaignPreview}},...a!==void 0&&{appUrls:a.urls}});return}let c=r.campaign;if(console.log(c.name),console.log(`ID: ${c.id}`),Ce("URL",a?.urls.campaign??c.url),Ce("Preview URL",a?.urls.campaignPreview??c.previewUrl),c.shareUrl)Ce("Share URL",c.shareUrl);if(console.log(`Status: ${c.status}`),n2(c.type),c.rejectionComment)console.log(`Rejection feedback: ${c.rejectionComment}`);if(console.log(`Subject: ${c.subject}`),c.emailId)console.log(`Email ID: ${c.emailId}`),console.log(`Format: ${Cs(c.emailPreset)}`);if(c.trackingCode)console.log(`Tracking code: ${c.trackingCode}`);if(console.log(`Labels: ${rb(c.labels)}`),console.log(`Audience: ${k0(c.targetLists)}`),console.log(`Preheader: ${c.preheader||"None"}`),c.replyToEmail||c.replyProfileId)console.log(`Reply-To: ${Xz(c)}`);console.log(`Blocks: ${c.blocks.length}`),console.log(`Created: ${ne(c.createdAt)}`),console.log(`Scheduled: ${ne(c.scheduledAt)}`),console.log(`Sent: ${ne(c.sentAt)}`),console.log(`Delivery: ${e2(c)}`);let l=t2(c);if(l)console.log(`Recipient limit: ${l}`)}catch(n){k(n instanceof A?n:n),process.exit(1)}}async function g2(e){if(!await H())k(J()),process.exit(1);try{let t=Fe(e.items,e.itemsFile,"items"),n=t===void 0?[]:t,r=Fe(e.fields,void 0,"fields"),o=await E("POST","/api/v1/email-blocks/line-items/assist",{items:n,...e.priceUnit!==void 0?{priceUnit:e.priceUnit}:{},...r!==void 0?{itemFields:r}:{},...e.scenario!==void 0?{scenario:e.scenario}:{}},e.company);if(e.json){D(o);return}console.log(`${o.isSample?"Sample preview":"Supplied event data"}: ${o.scenario} (${o.previewItems.length} items)`);for(let a of o.suggestions)console.log(`${a.field} → ${a.path}: ${a.example}`);for(let a of o.priceCandidates)console.log(`Confirm price units: ${a.path} = ${a.example}. Set priceUnit to minor for cents or major for major units.`);console.log("Design presets:");for(let a of o.presets)console.log(`${a.label}: ${JSON.stringify(a.settings)}`);console.log(`Preview items (not saved):
|
|
268
268
|
${JSON.stringify(o.previewItems,null,2)}`)}catch(t){k(t),process.exit(1)}}import{writeFile as sde}from"node:fs/promises";function ade(e){switch(e.type){case"campaign":return`/api/v1/campaigns/${e.id}/render`;case"sequence-step":return`/api/v1/sequences/${e.sequenceId}/nodes/${e.nodeId}/render`;case"template":return`/api/v1/templates/${e.id}/render`}}function A2(e,t){let n={};for(let r of t??[]){let o=r.indexOf("=");if(o<=0)throw new A(`Invalid ${e} "${r}". Expected key=value.`,400);n[r.slice(0,o)]=r.slice(o+1)}return n}function R0(e){if(e.subscriber&&e.email)throw new A("Use either --subscriber or --email, not both.",400);let t={...If("--vars-json",e.varsJson),...A2("--var",e.var)},n={...If("--attrs-json",e.attrsJson),...A2("--attr",e.attr)},r=(e.tag??[]).map((a)=>a.trim()).filter(Boolean);if(e.emptyTags&&r.length>0)throw new A("Use either --tag or --empty-tags, not both.",400);let o=r.length>0||e.emptyTags===!0;if(o&&!e.email)throw new A(e.subscriber?"--tag/--empty-tags describe an ad-hoc --email contact. A --subscriber render already evaluates conditions against that contact's stored tags, so drop the flag.":"--tag/--empty-tags describe the contact from --email. Pass --email, or use --subscriber to render as a stored contact with its own tags.",400);if(Object.keys(n).length>0&&!e.email)throw new A(e.subscriber?"--attr/--attrs-json describe an ad-hoc --email contact. A --subscriber render already uses that contact's stored attributes, so drop these flags.":"--attr/--attrs-json describe the contact from --email. Pass --email, or use --subscriber to render as a stored contact with its own attributes.",400);return{...e.subscriber?{subscriberId:e.subscriber}:{},...e.email?{subscriber:{email:e.email,...e.firstName?{firstName:e.firstName}:{},...e.lastName?{lastName:e.lastName}:{},...Object.keys(n).length>0?{customAttributes:n}:{},...o?{tags:r}:{}}}:{},...Object.keys(t).length>0?{variables:t}:{},...e.locale?{locale:e.locale}:{},...e.variant?{variantId:e.variant}:{},...e.tracking?{tracking:!0}:{}}}function Q0(e){if(!e?.length)return;let t=e.filter((r)=>r.reason==="unknown"),n=e.filter((r)=>r.reason==="no_value");if(t.length>0)console.log(`Unrecognized merge tags (empty or defaulted for every recipient): ${t.map((r)=>`{{${r.tag}}}`).join(", ")}`);if(n.length>0)console.log(`Empty for this contact: ${n.map((r)=>`{{${r.tag}}}`).join(", ")}`)}function T0(e){if(!e?.length)return;console.log("Conditions not evaluated (rendered as false):");for(let t of e)console.log(` ${t.description} - ${t.hint}`)}async function ib(e,t){if(!await H())k(J()),process.exit(1);try{let n=R0(t),r=await E("POST",ade(e),n,t.company);if(t.json){D(r);return}if(t.out==="-"){process.stdout.write(r.html);return}if(t.out)await sde(t.out,r.html,"utf8");if(console.log(`Subject: ${r.subject}`),console.log(`Preview text: ${r.previewText||"None"}`),console.log(`Locale: ${r.locale}`),r.entity.variantId)console.log(`Variant: ${r.entity.variantId}`);if(console.log(`Personalized: ${r.personalized?"Yes":"No (sample contact)"}`),console.log(`Tracking: ${r.trackingApplied?"Auto-UTM applied":"Clean links"}`),console.log(`HTML: ${r.html.length} bytes`),Q0(r.unresolvedMergeTags),T0(r.unevaluatedConditions),t.out)console.log(`Written to: ${t.out}`);else console.log("Pass --out <file> to save the HTML, or --out - to stream it.")}catch(n){k(n instanceof A?n:n),process.exit(1)}}function cde(e){switch(e.type){case"campaign":return`/api/v1/campaigns/${e.id}/check`;case"sequence-step":return`/api/v1/sequences/${e.sequenceId}/nodes/${e.nodeId}/check`;case"template":return`/api/v1/templates/${e.id}/check`}}function lde(e){if(e===void 0)return null;let t=e.trim().toLowerCase();if(t==="error"||t==="warning")return t;throw new A(`Invalid --fail-on "${e}". Use error or warning.`,400)}function ude(e,t){return e.some((n)=>n.severity==="error"||t==="warning"&&n.severity==="warning")}var dde={error:"x",warning:"!",info:"-"},pde={ok:"OK",broken:"Broken",invalid:"Won't work",server_error:"Server error",unreachable:"Unreachable",restricted:"Couldn't verify",personalized:"Personalized",not_checked:"Not checked"};function $0(e,t){return`${e} ${t}${e===1?"":"s"}`}function mde(e){let t=e.issues.filter((p)=>p.severity==="error"),n=e.issues.filter((p)=>p.severity==="warning"),r=e.issues.filter((p)=>p.severity==="info");if(console.log(`Email check: ${e.grade} (${e.score}/100), likely ${e.placement}`),e.entity.variantId)console.log(`Variant: ${e.entity.variantId}`);let o=e.linkSummary,a=[`${o.ok} ok`];if(o.broken>0)a.push(`${o.broken} broken`);let c=e.links.filter((p)=>p.status==="unreachable").length,l=e.links.filter((p)=>p.status==="server_error").length;if(c>0)a.push(`${c} unreachable`);if(l>0)a.push(`${l} server error${l===1?"":"s"}`);if(o.restricted>0)a.push(`${o.restricted} couldn't verify`);if(o.notChecked>0)a.push(`${o.notChecked} not checked`);console.log(`Links and images: ${o.total}${o.total>0?` (${a.join(", ")})`:""}${e.linksChecked?"":" - live checks skipped"}`);for(let p of e.links){if(p.status==="ok"||p.status==="personalized")continue;if(p.status==="not_checked"&&e.linksChecked===!1)continue;console.log(` ${pde[p.status]??p.status}: ${p.label} ${p.url||"(no URL)"} - ${p.message}`)}if(e.issues.length===0)console.log("No issues found.");else{console.log(`Issues: ${$0(t.length,"error")}, ${$0(n.length,"warning")}, ${$0(r.length,"tip")}`);for(let p of[...t,...n,...r]){let f=p.blockId?` (block ${p.blockId})`:"";console.log(` ${dde[p.severity]} ${p.message}${f}${p.rule?` [${p.rule}]`:""}`)}}Q0(e.unresolvedMergeTags),T0(e.unevaluatedConditions)}async function sb(e,t){if(!await H())k(J()),process.exit(1);let n=!1;try{let r=lde(t.failOn),o={...R0(t),...t.links===!1?{links:!1}:{}},a=await E("POST",cde(e),o,t.company);if(t.json)D(a);else mde(a);n=r!==null&&ude(a.issues,r)}catch(r){k(r),process.exit(1)}if(n)process.exit(1)}function fde(e){let t=e.domain?.trim(),n=e.name?.trim(),r=!!e.withoutWebsite&&!t,o=kn(e.description,e.descriptionFile,"description")?.trim();if(!e.domain&&!r)throw new A("Domain is required unless --without-website is set",400);if(r&&!n)throw new A("Name is required when starting without a website",400);if(o&&o.length>500)throw new A("Description must be 500 characters or fewer",400);return{...r?{noWebsite:!0,name:n}:{domain:e.domain,...e.name!==void 0?{name:e.name}:{}},...o?{description:o}:{},...e.withWelcomeSequence?{withWelcomeSequence:!0}:{}}}function b2(e){let t=e.supportedLocales.join(", "),n=e.subscriberLocaleAttribute??"not configured";return`${e.primaryLocale} -> [${t}] | fallback ${e.fallbackLocale} | attr ${n} | sync ${e.autoSyncMode}`}function gde(e){let t=kn(e.description,e.descriptionFile,"description"),n=kn(e.companyContext,e.companyContextFile,"company-context"),r=kn(e.emailDesignPrompt,e.emailDesignPromptFile,"email-design-prompt"),o=Fe(e.brandColorsJson,e.brandColorsFile,"brand-colors"),a=Fe(e.valuePropsJson,e.valuePropsFile,"value-props"),c=Fe(e.testimonialsJson,e.testimonialsFile,"testimonials"),l=Fe(e.socialLinksJson,e.socialLinksFile,"social-links"),p=Fe(e.pricingJson,e.pricingFile,"pricing"),f=Fe(e.emailThemeJson,e.emailThemeFile,"email-theme");if(o!==void 0&&(typeof o!=="object"||Array.isArray(o)||o===null))throw new A("brand-colors JSON must be an object",400);if(a!==void 0&&!Array.isArray(a))throw new A("value-props JSON must be an array",400);if(c!==void 0&&!Array.isArray(c))throw new A("testimonials JSON must be an array",400);if(l!==void 0&&(typeof l!=="object"||Array.isArray(l)||l===null))throw new A("social-links JSON must be an object",400);if(p!==void 0&&(typeof p!=="object"||Array.isArray(p)||p===null))throw new A("pricing JSON must be an object",400);if(f!==void 0&&f!==null&&(typeof f!=="object"||Array.isArray(f)))throw new A("email-theme JSON must be an object or null",400);if(e.enableReplyTracking&&e.disableReplyTracking)throw new A("Use only one of --enable-reply-tracking or --disable-reply-tracking",400);if(e.enableReplyForwarding&&e.disableReplyForwarding)throw new A("Use only one of --enable-reply-forwarding or --disable-reply-forwarding",400);if(e.replyTrackingDomainMode!==void 0&&e.replyTrackingDomainMode!=="sequenzy"&&e.replyTrackingDomainMode!=="custom")throw new A("reply-tracking-domain-mode must be sequenzy or custom",400);let h=e.defaultList??[];if([h.length>0,e.defaultListsNone===!0,e.defaultListsAll===!0].filter(Boolean).length>1)throw new A("--default-list, --default-lists-none, and --default-lists-all are mutually exclusive",400);let v={};if(e.renameMatchingFooters){if(!e.name?.trim()||e.previousCompanyName===void 0)throw new A("--rename-matching-footers requires --name and --previous-company-name",400);v.renameMatchingFooters=!0,v.previousCompanyName=e.previousCompanyName}let C=[["name","name"],["logoUrl","logoUrl"],["founderName","founderName"],["primaryColor","primaryColor"],["toneVoice","toneVoice"],["emailLengthPreference","emailLengthPreference"],["emailPreset","emailPreset"],["privacyPolicyUrl","privacyPolicyUrl"],["termsUrl","termsUrl"],["address","address"],["language","language"],["fontFamily","fontFamily"],["emailDirection","emailDirection"],["senderProfileId","senderProfileId"],["fromEmail","fromEmail"],["fromName","fromName"],["replyProfileId","replyProfileId"],["replyTo","replyTo"],["replyToName","replyToName"]];for(let[R,F]of C){let L=e[R];if(typeof L==="string")v[F]=L}if(e.emailStyle!==void 0){if(!["visual","plain","ask"].includes(e.emailStyle))throw new A("email-style must be visual, plain or ask",400);v.emailStylePreference=e.emailStyle==="ask"?null:e.emailStyle}if(t!==void 0)v.description=t;if(n!==void 0)v.companyContext=n;if(r!==void 0)v.emailDesignPrompt=r;if(o!==void 0)v.brandColors=o;if(a!==void 0)v.valueProps=a;if(c!==void 0)v.testimonials=c;if(l!==void 0)v.socialLinks=l;if(p!==void 0)v.pricing=p;if(f!==void 0)v.emailTheme=f;if(e.enableReplyTracking)v.replyTrackingEnabled=!0;if(e.disableReplyTracking)v.replyTrackingEnabled=!1;if(e.replyTrackingDomainMode!==void 0)v.replyTrackingDomainMode=e.replyTrackingDomainMode;if(e.enableReplyForwarding)v.forwardReplies=!0;if(e.disableReplyForwarding)v.forwardReplies=!1;if(e.defaultListsAll)v.defaultSubscriberListIds=null;else if(e.defaultListsNone)v.defaultSubscriberListIds=[];else if(h.length>0)v.defaultSubscriberListIds=h;if(Object.keys(v).length===0)throw new A("Provide at least one company update option",400);return v}function h2(e,t){if(!t)return"Not set";return e?`${e} <${t}>`:t}function Ade(e){if(e===null)return"All lists (every current and future list)";if(e.length===0)return"No lists";return`${e.length} specific list${e.length===1?"":"s"}: ${e.join(", ")}`}function hde(e){if(!e.visible)return e.reason==="email_partner"?"Hidden (email-partner entitlement)":`Hidden (paid plan${e.subscriptionTier?`: ${e.subscriptionTier}`:""})`;if(e.reason==="inactive_subscription")return`Visible (subscription ${e.subscriptionStatus??"inactive"}; renew to remove)`;return"Visible (free plan; upgrade to remove)"}function yde(e){if(e==="plain")return"Simple text (plain)";if(e==="visual")return"Designed (visual)";return"Not chosen (designed until you pick)"}function y2(e){if(console.log(e.name),console.log(`ID: ${e.id}`),console.log(`Status: ${e.status}`),console.log(`Website: ${e.websiteUrl??"Not set"}`),console.log(`Logo: ${e.logoUrl??"Not set"}`),console.log(`Primary color: ${e.primaryColor??"Not set"}`),console.log(`Founder: ${e.founderName??"Not set"}`),console.log(`Description: ${e.description??"Not set"}`),console.log(`Tone: ${e.toneVoice??"Not set"}`),console.log(`Context: ${e.companyContext??"Not set"}`),console.log(`Design prompt: ${e.emailDesignPrompt??"Not set"}`),console.log(`Email length: ${e.emailLengthPreference}`),e.emailStylePreference!==void 0)console.log(`AI email style: ${yde(e.emailStylePreference)}`);if(e.emailPreset)console.log(`Header and footer: ${e.emailPreset==="minimal"?"Compact footer, no logo (minimal)":"Logo and full footer (branded)"}`);console.log(`Primary language: ${e.language}`),console.log(`Email direction: ${e.emailDirection}`),console.log(`Sequenzy email branding: ${hde(e.emailBranding)}`),console.log(`Subscription: ${e.emailBranding.subscriptionUrl}`),console.log(`Default lists for new contacts: ${Ade(e.defaultSubscriberListIds)}`),console.log(`Default From: ${h2(e.defaultFromName,e.defaultFromEmail)}`),console.log(`Default Reply-To: ${h2(e.defaultReplyToName,e.defaultReplyToEmail)}`),console.log(`Reply tracking: ${e.replyTrackingEnabled?"Enabled":"Disabled"}`),console.log(`Reply domain mode: ${e.replyTrackingDomainMode}`),console.log(`Reply forwarding: ${e.forwardReplies?"Enabled":"Disabled"}`),console.log(`Reply retention: ${e.replyRetentionDays} days`),console.log(`Font family: ${e.fontFamily??"Not set"}`),console.log(`Email theme: ${e.emailTheme?`customized (${e.emailTheme.presetId??"default"} preset)`:"Platform default"}`),console.log(`Address: ${e.address??"Not set"}`),console.log(`Privacy policy: ${e.privacyPolicyUrl??"Not set"}`),console.log(`Terms: ${e.termsUrl??"Not set"}`),console.log(`Created: ${ne(e.createdAt)}`),console.log(`Localization: ${b2(e.emailLocalizationConfig)}`)}async function wf(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="list"){let c=await E("GET","/api/v1/companies"),l=c.companies.map((f)=>{let h=ct({companyId:f.id});return{...f,url:h.urls.dashboard,settingsUrl:h.urls.settings,subscriptionUrl:h.urls.subscription}}),p=c.currentCompanyId!==null?ct({companyId:c.currentCompanyId}):void 0;if(t.json){D({...c,companies:l,...p!==void 0&&{appUrls:p.urls}});return}console.log(`Companies (${c.companies.length})`);for(let f of l){let h=f.id===c.currentCompanyId?" (current)":"";console.log(`- ${f.name} [${f.id}]${h}`),console.log(` Status: ${f.status}`),console.log(` Website: ${f.websiteUrl??"Not set"}`),Ce(" URL",f.url),Ce(" Settings",f.settingsUrl),Ce(" Subscription",f.subscriptionUrl),console.log(` Localization: ${b2(f.emailLocalizationConfig)}`)}return}if(!t.id){if(e!=="create")throw new A("Company ID is required",400)}if(e==="create"){let c=await E("POST","/api/v1/companies",fde(t)),l=ct({companyId:c.company.id});if(t.json){D({...c,company:{...c.company,url:l.urls.dashboard,settingsUrl:l.urls.settings,subscriptionUrl:l.urls.subscription},appUrls:l.urls,settingsUrls:l.settingsUrls});return}if(console.log(c.company.name),console.log(`ID: ${c.company.id}`),Ce("URL",l.urls.dashboard),Ce("Settings",l.urls.settings),Ce("Subscription",l.urls.subscription),console.log(`Status: ${c.company.status}`),console.log(`Website: ${c.company.websiteUrl??"Not set"}`),c.welcomeAutomationId)console.log(`Welcome sequence: ${c.welcomeAutomationId}`),console.log(`Generation job: ${c.welcomeEnrichmentJobId??"Not queued; open the editor to retry"}`);console.log(""),console.log(c.message);return}if(e==="update"){let c=t.id;if(!c)throw new A("Company ID is required",400);let l=await E("PATCH",`/api/v1/companies/${c}`,gde(t)),p=ct({companyId:c});if(t.json){D({...l,company:{...l.company,url:p.urls.dashboard,settingsUrl:p.urls.settings,subscriptionUrl:p.urls.subscription},appUrls:p.urls,settingsUrls:p.settingsUrls});return}console.log("Company updated"),y2(l.company),Ce("URL",p.urls.dashboard),Ce("Settings",p.urls.settings);return}let n=await E("GET",`/api/v1/companies/${t.id}`),r=ct({companyId:t.id});if(t.json){D({...n,company:{...n.company,url:r.urls.dashboard,settingsUrl:r.urls.settings,subscriptionUrl:r.urls.subscription},appUrls:r.urls,settingsUrls:r.settingsUrls});return}let o=n.company;Ce("URL",r.urls.dashboard),Ce("Settings",r.urls.settings),y2(o);let a=Object.entries(o.emailLocalizationConfig.valueMappings);if(a.length>0){console.log("Mappings:");for(let[c,l]of a)console.log(`- ${c} -> ${l}`)}}catch(n){k(n instanceof A?n:n),process.exit(1)}}var v2=["email_events","sms_events","custom_events","subscribers"],E2=["every_5_minutes","every_15_minutes","hourly","daily"],bde=["s3","gcs"],I2=30,Ca="SEQUENZY_DATA_EXPORT_SECRET";function ec(e){k(new A(e,400)),process.exit(1)}function ab(e,t){if(!e||e.trim().length===0)ec(`${t} is required.`);return e.trim()}function N0(e,t,n){if(e===void 0)return;if(!t.includes(e))ec(`Invalid ${n} "${e}". Use one of: ${t.join(", ")}.`);return e}function C2(e){if(e===void 0)return;let t=e.split(",").map((r)=>r.trim()).filter(Boolean),n=t.filter((r)=>!v2.includes(r));if(t.length===0||n.length>0)ec(`--datasets must be a comma-separated list of: ${v2.join(", ")}.`);return t}function vde(e,t=new Date){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0||n>I2)ec(`--backfill-days must be a whole number from 0 to ${I2}.`);if(n===0)return;return new Date(t.getTime()-n*86400000+60000).toISOString()}function w2(e){return e??process.env[Ca]??void 0}function Ede(e){let t=e.provider==="gcs"?"gs":"s3",n=e.pathPrefix?`/${e.pathPrefix}`:"";return`${t}://${e.bucket}${n}/`}function Ide(e){if(!e.isEnabled)return"paused";return e.status==="failed"?"failing":e.status}function cb(e){console.log(`- ${e.name} -> ${Ede(e)}`),console.log(` id: ${e.id} | ${e.frequency} | status: ${Ide(e)} | datasets: ${e.datasets.join(", ")}`),console.log(` last success: ${e.lastSuccessAt??"never"} | next run: ${e.nextRunAt??"not scheduled"} | rows exported: ${e.totalRowsExported}`);for(let[t,n]of Object.entries(e.exportedThrough))console.log(` ${t} exported through: ${n??"not started"}`);if(e.lastError)console.log(` last error: ${e.lastError}`)}async function tc(e,t){if(!await H())k(J()),process.exit(1);let n=(r,o)=>{if(t.json){console.log(JSON.stringify(r,null,2));return}o()};try{if(e==="list"){let c=await E("GET","/api/v1/data-exports",void 0,t.company);n(c,()=>{console.log(`Data exports (${c.dataExports.length})`);for(let l of c.dataExports)cb(l)});return}if(e==="create"){let c=N0(t.provider,bde,"--provider")??"s3",l=w2(t.secretAccessKey);if(!l)ec(`Provide --secret-access-key or set ${Ca} in the environment.`);let p=C2(t.datasets),f=N0(t.frequency,E2,"--frequency"),h=vde(t.backfillDays),y=await E("POST","/api/v1/data-exports",{name:ab(t.name,"--name"),provider:c,bucket:ab(t.bucket,"--bucket"),...t.region!==void 0?{region:t.region}:{},...t.endpoint!==void 0?{endpoint:t.endpoint}:{},...t.prefix!==void 0?{pathPrefix:t.prefix}:{},accessKeyId:ab(t.accessKeyId,"--access-key-id"),secretAccessKey:l,...p?{datasets:p}:{},...f?{frequency:f}:{},...h?{startFrom:h}:{}},t.company);n(y,()=>{console.log(`Created data export ${y.dataExport.id}`),cb(y.dataExport),console.log("Bucket access was verified with a test file. The first export is running now.")});return}let r=encodeURIComponent(ab(t.id,"<id>"));if(e==="get"){let c=await E("GET",`/api/v1/data-exports/${r}`,void 0,t.company);n(c,()=>cb(c.dataExport));return}if(e==="update"){let c={};if(t.name!==void 0)c.name=t.name;if(t.bucket!==void 0)c.bucket=t.bucket;if(t.region!==void 0)c.region=t.region;if(t.endpoint!==void 0)c.endpoint=t.endpoint;if(t.prefix!==void 0)c.pathPrefix=t.prefix;let l=C2(t.datasets);if(l)c.datasets=l;let p=N0(t.frequency,E2,"--frequency");if(p)c.frequency=p;if(t.enabled!==void 0){if(t.enabled!=="true"&&t.enabled!=="false")ec('--enabled must be "true" or "false".');c.isEnabled=t.enabled==="true"}if(t.accessKeyId!==void 0){let h=w2(t.secretAccessKey);if(!h)ec(`Rotating credentials needs --secret-access-key or ${Ca}.`);c.accessKeyId=t.accessKeyId,c.secretAccessKey=h}else if(t.secretAccessKey!==void 0)ec("Provide --access-key-id together with --secret-access-key.");if(Object.keys(c).length===0)ec("Nothing to update. Pass --name, --datasets, --frequency, --enabled, --bucket, --region, --endpoint, --prefix or new credentials.");let f=await E("PATCH",`/api/v1/data-exports/${r}`,c,t.company);n(f,()=>{console.log(`Updated data export ${f.dataExport.id}`),cb(f.dataExport)});return}if(e==="delete"){if(!await mt(`Delete data export ${decodeURIComponent(r)}? Files already written stay in the bucket.`,t)){console.log("Cancelled.");return}let l=await E("DELETE",`/api/v1/data-exports/${r}`,void 0,t.company);n(l,()=>console.log(`Deleted data export ${l.dataExportId}. Files already written were kept.`));return}if(e==="test"){let c=await E("POST",`/api/v1/data-exports/${r}/test`,void 0,t.company);n(c,()=>console.log(`Connection works. Test file written at ${c.testedAt}.`));return}if(e==="run"){let c=await E("POST",`/api/v1/data-exports/${r}/run`,void 0,t.company);n(c,()=>console.log(`Queued an export for ${c.dataExport.name}. Check progress with \`sequenzy data-exports runs ${c.dataExport.id}\`.`));return}let o=t.limit?`?limit=${encodeURIComponent(t.limit)}`:"",a=await E("GET",`/api/v1/data-exports/${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.status==="running"?"in progress":`${c.rowCount} rows, ${c.fileCount} files, ${c.byteCount} bytes`;if(console.log(`- ${c.startedAt} ${c.status}${c.isManual?" (manual)":""}: ${l}`),c.error)console.log(` error: ${c.error}`)}})}catch(r){k(r),process.exit(1)}}import{readFileSync as Cde}from"node:fs";import{isatty as wde}from"node:tty";function Sde(e,t=(r)=>Cde(r,"utf8"),n=wde(0)){if(e==="-"&&n)throw new A("Pass the design.md file to save, for example 'sequenzy design-md update design.md', or pipe it into stdin.",400);try{return t(e==="-"?0:e)}catch(r){throw new A(`Could not read ${e==="-"?"stdin":e}: ${r instanceof Error?r.message:String(r)}`,400)}}function Dde(e,t){if(!e.trim())throw new A("design.md is empty. Run 'sequenzy design-md get > design.md', edit it, then update from that file.",400);return{markdown:e,...t.expectedVersion?{expectedVersion:t.expectedVersion}:{},...t.dryRun?{dryRun:!0}:{}}}function Bde(e){return e.line?`line ${e.line}: ${e.message}`:e.message}async function O0(e,t){if(!await H())k(J()),process.exit(1);try{if(e==="get"){let o=await E("GET","/api/v1/design-md",void 0,t.company);if(t.json){D(o);return}process.stdout.write(o.markdown),console.error(`version: ${o.version}`);return}let n=Sde(t.file??"-"),r=await E("PUT","/api/v1/design-md",Dde(n,t),t.company);if(t.json){D(r);return}if(r.message)console.log(r.message);for(let o of r.warnings??[])console.log(`Warning: ${Bde(o)}`);console.log(`version: ${r.version}`)}catch(n){k(n),process.exit(1)}}function xde(e){if(e.withoutLayoutRules&&e.layoutRules!==void 0)throw new A("Use either --layout-rules or --without-layout-rules, not both.",400);if(e.withoutLayoutRules)return[];if(e.layoutRules===void 0)return null;let t=e.layoutRules.split(",").map((n)=>n.trim()).filter(Boolean);if(!t.length)throw new A("Pass at least one rule ID to --layout-rules, or use --without-layout-rules.",400);return t}async function P0(e,t){try{if(!await H())throw J();let n;if(e!=="get"){let o=t.expectedStyleId?.trim();if(t.ifUnset&&t.expectedStyleId!==void 0)throw new A("Use either --if-unset or --expected-style-id, not both.",400);if(!o&&!(e==="save"&&t.ifUnset))throw new A("Get the current style first, then pass --expected-style-id <revisionId>. For an initial save, use --if-unset.",400);if(n={expectedStyleId:o??null},e==="save"){if(!t.emailId?.trim())throw new A("An email ID is required.",400);if(n.emailId=t.emailId,t.canvasFile)n.canvas=JSON.parse(kn(void 0,t.canvasFile,"canvas")??"");let a=xde(t);if(a)n.layoutRuleIds=a;if(t.notes!==void 0){if(t.notes.length>500)throw new A("Notes must be 500 characters or fewer.",400);n.notes=t.notes}}}let r=await E(e==="get"?"GET":e==="save"?"PUT":"DELETE","/api/v1/email-ai-style",n,t.company);if(t.json){D(r);return}if(r.style){console.log(`Saved AI style: ${r.style.sourceName}`),console.log(`Source email: ${r.style.sourceEmailId}`),console.log(`Saved at: ${r.style.savedAt}`);let o=r.style.layout?.rules??[];console.log(o.length?`Layout habits (${o.length}):`:"Layout habits: none");for(let a of o)console.log(` - ${a.description} [${a.id}]`);if(r.style.notes)console.log(`Notes: ${r.style.notes}`)}else console.log(e==="clear"?"AI style cleared. Future generations use your brand defaults.":"No active saved AI style.");console.log(`Revision: ${r.revisionId??"none"}`),console.log(`Can manage: ${r.canManage?"yes":"no"}`)}catch(n){k(n),process.exitCode=1}}function S2(e){let t=e.command("email-ai-style").description("Get, save or clear the company's saved AI email style").action(()=>t.help());S(t,{notes:["Saving snapshots appearance plus detected layout habits (for example dotted dividers around every button). Existing emails and source content stay unchanged.","All detected habits are kept unless you pass --layout-rules with the IDs to keep or --without-layout-rules. Review them with get after saving.","Read the current revision before replacing or clearing. A conflict requires a fresh review, not an automatic retry."],examples:["sequenzy email-ai-style get --json","sequenzy email-ai-style save email_123 --if-unset",'sequenzy email-ai-style save email_123 --expected-style-id style_123 --layout-rules "around|button|divider:dots" --notes "Keep the dots around buttons"',"sequenzy email-ai-style clear --expected-style-id style_123"]}),t.command("get").description("Show the current saved style and revision").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((n)=>P0("get",n)),t.command("save <email-id>").description("Capture an email's appearance as the company AI default").option("--if-unset","Save only when no style is stored").option("--expected-style-id <id>","Revision ID returned by get").option("--canvas-file <path>","Optional JSON snapshot with blocks, theme, fontFamily and emailPreset; otherwise use the stored email").option("--layout-rules <ids>","Comma-separated IDs of detected layout habits to keep; omit to keep all").option("--without-layout-rules","Keep appearance only, no layout habits").option("--notes <text>","Design notes for future generations (up to 500 characters)").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((n,r)=>P0("save",{...r,emailId:n})),t.command("clear").description("Clear only the saved style you reviewed").requiredOption("--expected-style-id <id>","Revision ID returned by get").option("-c, --company <id>","Company ID override for personal API keys").option("--json","Print raw JSON").action((n)=>P0("clear",n))}function D2(e,t){let n=(c)=>{let l=c.values?.length?` (${c.values.map((p)=>String(p)).join(" | ")})`:"";return`${c.name}: ${c.type}${l}`},r=e.filter((c)=>c.required).map(n),o=e.filter((c)=>!c.required).map(n),a=[];if(r.length>0){let c=`{ ${r.join(", ")} }`;a.push(t?`[${c}]`:c)}else if(t)a.push("[{ }]");if(o.length>0)a.push(a.length>0?`+ optional ${o.join(", ")}`:`optional ${o.join(", ")}`);return a.join(" ")}function _de(e){if(e.values&&e.values.length>0)return e.values.map((t)=>String(t)).join(" | ");if(e.itemFields&&e.itemFields.length>0)return D2(e.itemFields,!0);if(e.fields&&e.fields.length>0)return D2(e.fields,!1);return""}var kde={any_contact:"any contact",inline_tags_or_stored_subscriber:"--tag on an --email contact, or --subscriber",stored_subscriber:"--subscriber only"};function Rde(e){if(!e?.length)return;console.log(""),console.log("Condition fields (the `conditions` array on any block)"),console.log("");for(let t of e){if(console.log(` ${t.field} ${t.operators.join(", ")}`),console.log(` value: ${t.valueFormat}`),t.values?.length)console.log(` values: ${t.values.join(", ")}`);if(t.serverEvaluated)console.log(` preview: ${kde[t.previewSupport]}`);console.log(` example: ${JSON.stringify(t.example)}`)}console.log(""),console.log('Fields with no preview line resolve from any contact. A condition a render cannot evaluate is rendered as false and listed under "Conditions not evaluated".')}function Qde(e){console.log(""),console.log("Every block also takes a `conditions` array, and each condition field accepts only its own operators."),console.log(`Run \`sequenzy blocks ${e} --conditions\` for the field, operator, and value table.`)}function Tde(e){console.log("Email block types"),console.log("");let t=Math.max(...e.map((n)=>n.type.length),4);for(let n of e){let r=n.required.length>0?`requires ${n.required.join(", ")}`:"no required fields",o=n.creatable?" ":"*";console.log(`${o} ${n.type.padEnd(t)} ${r}`)}console.log(""),console.log("* managed by the editor - prefer not to hand-author these. Pass --creatable-only to hide them."),console.log("Pass a block type for full field details, e.g. `sequenzy blocks list`."),console.log("Every block takes a `conditions` array. Run `sequenzy blocks conditional-group` for the field, operator, and value table.")}function $de(e,t){if(console.log(`${e.type}${e.creatable?"":" (managed by the editor)"}`),e.reason)console.log(e.reason);console.log("");let n=Math.max(...e.fields.map((o)=>o.name.length),5),r=Math.max(...e.fields.map((o)=>o.type.length),8);for(let o of e.fields){let a=o.required?"required":"optional";console.log(` ${o.name.padEnd(n)} ${o.type.padEnd(r)} ${a} ${_de(o)}`.trimEnd())}if(e.notes&&e.notes.length>0){console.log("");for(let o of e.notes)console.log(`- ${o}`)}if(e.example)if(console.log(""),t.example)console.log("Example:"),console.log(JSON.stringify(e.example,null,2));else console.log(`Example: ${JSON.stringify(e.example)}`)}function Nde(e,t){let n=e?.trim();if(n){let r=`/api/v1/email-blocks/${encodeURIComponent(n)}`;return t.conditions?`${r}?conditionFields=true`:r}return t.creatableOnly?"/api/v1/email-blocks?creatableOnly=true":"/api/v1/email-blocks"}async function B2(e,t){if(!await H())k(J()),process.exit(1);try{let n=Nde(e,t),r=await E("GET",n,void 0,t.company);if(t.json){D(r);return}if("blockType"in r){if($de(r.blockType,t),r.conditionFields)Rde(r.conditionFields);else if(r.conditionFieldsHint)Qde(r.blockType.type);return}Tde(r.blockTypes)}catch(n){k(n instanceof A?n:n),process.exit(1)}}import{mkdir as Ode,writeFile as Pde}from"node:fs/promises";import{resolve as x2}from"node:path";function F0(e){let t=[...new Set(e.applyTo?.split(",").map((n)=>n.trim()).filter(Boolean)??[])];if(e.applyTo!==void 0&&!t.length)throw new A("--apply-to requires at least one category",400);if(t.some((n)=>!["sequences","campaigns","transactional","templates"].includes(n)))throw new A("--apply-to accepts sequences,campaigns,transactional,templates",400);if(e.includeCustomized&&!t.length)throw new A("--include-customized requires --apply-to",400);return{scopes:t,includeCustomized:e.includeCustomized??!1}}function q0(e){console.log(`Affected email versions: ${e.affected.length}`);for(let[t,n]of Object.entries(e.counts))console.log(` ${t}: ${n}`);console.log(`Skipped: ${e.skipped.length}`);for(let t of e.skipped)console.log(` ${t.name} (${t.kind}:${t.id}): ${t.reason}`);console.log(`Preview token: ${e.token}`)}async function _2(e,t){if(!e.renderedPreview)throw new A("The server did not return a rendered preview",500);let n=x2(t);await Ode(n,{recursive:!0});let r=[];async function o(a,c){let l=x2(n,a);await Pde(l,c,"utf8"),r.push(l)}await o("footer.html",e.renderedPreview.footerHtml);for(let[a,c]of e.renderedPreview.samples.entries())await o(`sample-${a+1}-before.html`,c.beforeHtml),await o(`sample-${a+1}-after.html`,c.afterHtml);return r}function Fde(e){let t=e.defaultSlot!==null?` [default ${e.defaultSlot}]`:"";return`${e.id} ${e.name}${t} v${e.version} ${e.blocks.length} block${e.blocks.length===1?"":"s"} updated ${ne(e.updatedAt)}`}function k2(e){if(console.log(`ID: ${e.id}`),console.log(`Name: ${e.name}`),e.description)console.log(`Description: ${e.description}`);console.log(`Type: ${e.componentType}`),console.log(`Default slot: ${e.defaultSlot??"not pinned as a default"}`),console.log(`Version: ${e.version}`),console.log(`Blocks: ${e.blocks.length}`),console.log(`Updated: ${ne(e.updatedAt)}`)}function lb(e,t){let n=Fe(e.blocksJson,e.blocksFile,"blocks");if(n===void 0){if(t)throw new A("Provide component blocks with --blocks-json or --blocks-file",400);return}let r=Array.isArray(n)?n:typeof n==="object"&&n!==null&&("component"in n)&&typeof n.component==="object"&&n.component!==null&&("blocks"in n.component)?n.component.blocks:void 0;if(!Array.isArray(r))throw new A("blocks JSON must be an array or a component response containing component.blocks",400);if(r.length===0)throw new A("blocks JSON must contain at least one block",400);return r}async function nc(e,t,n){if(!await H())k(J()),process.exit(1);try{if(e==="list"){let o=new URLSearchParams;if(n.type)o.set("type",n.type);if(n.defaultsOnly)o.set("defaultsOnly","true");let a=await E("GET",`/api/v1/email-components${o.size>0?`?${o}`:""}`,void 0,n.company);if(n.json){D(a);return}if(a.components.length===0){console.log("No email components found.");return}for(let c of a.components)console.log(Fde(c));return}if(e==="footer-get"){let o=await E("GET","/api/v1/email-components/defaults/footer",void 0,n.company);if(n.json){D(o);return}k2(o.component),console.log(`
|
|
269
269
|
Edit these blocks and write them back with: sequenzy components footer set --blocks-file <file>`);return}if(e==="footer-preview"){let o={blocks:lb(n,!0),application:F0(n),renderPreview:n.renderPreview||Boolean(n.outputDir)};if(n.name!==void 0)o.name=n.name;if(n.description!==void 0)o.description=n.description;if(n.sampleId||n.sampleKind){if(!n.sampleId||!n.sampleKind||!["email","ab_variant","localization"].includes(n.sampleKind))throw new A("Provide --sample-id and --sample-kind (email, ab_variant, localization) together",400);o.sample={id:n.sampleId,kind:n.sampleKind},o.renderPreview=!0}let a=await E("POST","/api/v1/email-components/defaults/footer/preview",o,n.company),c=n.outputDir?await _2(a,n.outputDir):void 0;if(n.json){D({...a,...c?{previewFiles:c}:{}});return}if(q0(a.application),c)for(let l of c)console.log(`Preview HTML: ${l}`);if(a.renderedPreview)console.log(a.renderedPreview.note);console.log("Apply using footer set with the same blocks, metadata and scope options plus --preview-token <token>."),_n(a);return}if(e==="footer-set"){let o=lb(n,!0),a=F0(n),c=a.scopes.length>0;if(c&&!n.previewToken)throw new A("Run components footer preview with the same options, then provide --preview-token to apply to existing emails",400);if(!await mt(c?`Save the default footer and apply the reviewed preview to ${a.scopes.join(", ")}${a.includeCustomized?", including customized footers":""}?`:"Replace the company's default email footer for future emails? Existing emails keep their saved footer.",n)){console.log("Aborted.");return}let l={blocks:o};if(n.previewToken)l.application=a,l.previewToken=n.previewToken;if(n.name!==void 0)l.name=n.name;if(n.description!==void 0)l.description=n.description;let p=await E("PUT","/api/v1/email-components/defaults/footer",l,n.company);if(n.json){D(p);return}if(console.log(`Saved default footer "${p.component.name}" (v${p.component.version}).`),p.application)q0(p.application);_n(p);return}if(e==="create"){let o=t??n.name;if(!o)throw new A("Component name is required",400);let a=lb(n,!0),c={name:o,blocks:a};if(n.description!==void 0)c.description=n.description;if(n.type!==void 0)c.componentType=n.type;let l=await E("POST","/api/v1/email-components",c,n.company);if(n.json){D(l);return}console.log(`Created component "${l.component.name}" (${l.component.id}).`),_n(l);return}if(!t)throw new A("Component ID is required",400);if(e==="get"){let o=await E("GET",`/api/v1/email-components/${encodeURIComponent(t)}`,void 0,n.company);if(n.json){D(o);return}k2(o.component);return}if(e==="update"){let o=lb(n,!1),a={};if(n.name!==void 0)a.name=n.name;if(n.description!==void 0)a.description=n.description;if(n.type!==void 0)a.componentType=n.type;if(o!==void 0)a.blocks=o;if(Object.keys(a).length===0)throw new A("Provide at least one of: --name, --description, --type, --blocks-json, --blocks-file",400);let c=await E("PATCH",`/api/v1/email-components/${encodeURIComponent(t)}`,a,n.company);if(n.json){D(c);return}console.log(`Updated component "${c.component.name}" (v${c.component.version}).`),_n(c);return}if(!await mt(`Delete email component ${t}? Emails that already use it keep their copied blocks.`,n)){console.log("Aborted.");return}let r=await E("DELETE",`/api/v1/email-components/${encodeURIComponent(t)}`,void 0,n.company);if(n.json){D(r);return}console.log(`Deleted component ${r.id}.`)}catch(r){k(r instanceof A?r:r),process.exit(1)}}function qde(e){let t=Object.entries({kickerStyle:e.kickerStyle,titleAlignment:e.titleAlignment,buttonShape:e.buttonShape,dividerStyle:e.dividerStyle,density:e.density,openerTreatments:e.openerTreatments?.split(",").map((r)=>r.trim()).filter(Boolean)}).filter(([,r])=>r!==void 0);if(e.reset){if(t.length>0||e.spine!==void 0)throw new A("--reset cannot be combined with other adjustments",400);return{reset:!0}}let n={};if(t.length>0)n.designCode=Object.fromEntries(t);if(e.spine!==void 0)n.compositionSpine=e.spine;if(Object.keys(n).length===0)throw new A("Provide at least one adjustment flag (e.g. --button-shape pill), or --reset",400);return n}function R2(e){let t=e.designSystem;if(console.log(`Email design system${e.isDefault?" (derived from brand context)":" (custom - carried by the design direction text)"}`),console.log(`- Composition spine: ${t.compositionSpine}`),console.log(`- Kicker style: ${t.designCode.kickerStyle}`),console.log(`- Title alignment: ${t.designCode.titleAlignment}`),console.log(`- Button shape: ${t.designCode.buttonShape}`),console.log(`- Divider style: ${t.designCode.dividerStyle}`),console.log(`- Density: ${t.designCode.density}`),console.log(`- Opener treatments: ${t.designCode.openerTreatments.join(", ")}`),e.directionText)console.log(`- Direction text:
|