fern-api 5.217.0 → 5.217.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +6 -6
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -3479,7 +3479,7 @@ ${zeu.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&zqo(th
3479
3479
  `).length),this}updateBottomBar(t){return g9t(this.rl,1),this.rl.output.unmute(),this.clean(),this.bottomBar=t,this.render(),this.rl.output.mute(),this}writeLog(t){return this.rl.output.unmute(),this.clean(),this.rl.output.write(this.enforceLF(t.toString())),this.render(),this.rl.output.mute(),this}enforceLF(t){return/[\n\r]$/.test(t)?t:t+`
3480
3480
  `}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&_Zr(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var Ud=Ae(Z3(),1),rru=Ae(HGt(),1);var E$r=Ae(Z3(),1),eru=Ae(HGt(),1),I$r=function(e,t,r){return typeof e[t]!="function"?(0,E$r.of)(e):(0,E$r.from)((0,eru.default)(e[t])(r).then(n=>(e[t]=n,e)))};var tru={set:(e,t="",r)=>{let n=e;t.split(".").forEach((i,o,s)=>{i==="__proto__"||i==="constructor"||(o===s.length-1?n[i]=r:(!(i in n)||typeof n[i]!="object")&&(n[i]={}),n=n[i])})},get:(e,t="",r)=>{let n=o=>String.prototype.split.call(t,o).filter(Boolean).reduce((s,a)=>s!=null?s[a]:s,e),i=n(/[,[\]]+?/)||n(/[,.[\]]+?/);return i===void 0||i===e?r:i}},Nlt=class extends PUe{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let n;return Array.isArray(t)?n=(0,Ud.from)(t):(0,Ud.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,Ud.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,Ud.from)([t]),this.process=n.pipe((0,Ud.concatMap)(this.processQuestion.bind(this)),(0,Ud.publish)()),this.process.connect(),this.process.pipe((0,Ud.reduce)((i,o)=>(tru.set(i,o.name,o.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,Ud.defer)(()=>(0,Ud.of)(t).pipe((0,Ud.concatMap)(this.setDefaultType.bind(this)),(0,Ud.concatMap)(this.filterIfRunnable.bind(this)),(0,Ud.concatMap)(()=>I$r(t,"message",this.answers)),(0,Ud.concatMap)(()=>I$r(t,"default",this.answers)),(0,Ud.concatMap)(()=>I$r(t,"choices",this.answers)),(0,Ud.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Ud.defer)(()=>(0,Ud.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Ud.defer)(()=>(0,Ud.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&tru.get(this.answers,t.name)!==void 0)return Ud.EMPTY;if(t.when===!1)return Ud.EMPTY;if(typeof t.when!="function")return(0,Ud.of)(t);let{answers:r}=this;return(0,Ud.defer)(()=>(0,Ud.from)((0,rru.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,Ud.filter)(n=>n!=null)))}};function nru(e){let t=function(r,n){let i;try{i=new Nlt(t.prompts,e)}catch(s){return Promise.reject(s)}let o=i.run(r,n);return o.ui=i,o};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",y9t),this.registerPrompt("input",xUe),this.registerPrompt("number",b9t),this.registerPrompt("confirm",E9t),this.registerPrompt("rawlist",I9t),this.registerPrompt("expand",v9t),this.registerPrompt("checkbox",C9t),this.registerPrompt("password",x9t),this.registerPrompt("editor",R9t)},t.restoreDefaultPrompts(),t}var o7o=nru();function lsh(e,t){o7o.registerPrompt(e,t)}function ush(){o7o.restoreDefaultPrompts()}var psh={prompt:o7o,ui:{BottomBar:k9t,Prompt:Nlt},createPromptModule:nru,registerPrompt:lsh,restoreDefaultPrompts:ush,Separator:FQ},Il=psh;var fsh=["prod","pre-prod","beta","dev","local"];function dsh(e){return fsh.some(t=>t===e)}function UK(e="prod"){let t=e?.trim();return t!=null&&dsh(t)?t:"local"}function v$r(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?!1:process.env.FERN_DISABLE_TELEMETRY!=="true"}var jlt=require("path");function oru(){let e=msh();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function msh(e=process.argv[1]?(0,jlt.dirname)(process.argv[1]):process.cwd(),t=jlt.sep==="\\"){let r=t?iru(e):e;return n=>{if(!n)return;let i=t?iru(n):n,{dir:o,base:s,ext:a}=jlt.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let c=decodeURIComponent(s);o||(o=".");let l=o.lastIndexOf("/node_modules");if(l>-1)return`${o.slice(l+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let u=o.slice(r.length+1).replace(/\//g,".");return u?`${u}:${c}`:c}return c}}function iru(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var ST={};ne(ST,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>L$r,DOMExceptionCoercer:()=>v7o,EXCEPTION_STEP_INTERNAL_FIELDS:()=>V9t,ErrorCoercer:()=>M9t,ErrorEventCoercer:()=>C7o,ErrorPropertiesBuilder:()=>Q9t,EventCoercer:()=>x7o,ExceptionStepsBuffer:()=>O7o,ObjectCoercer:()=>_9t,PrimitiveCoercer:()=>U9t,PromiseRejectionEventCoercer:()=>S7o,ReduceableCache:()=>w7o,StringCoercer:()=>L9t,chromeStackLineParser:()=>y7o,createDefaultStackParser:()=>I7o,createStackParser:()=>Hru,geckoStackLineParser:()=>b7o,getInjectedReleaseId:()=>Oah,getUtf8ByteLength:()=>Jru,nodeStackLineParser:()=>_ru,opera10StackLineParser:()=>Qru,opera11StackLineParser:()=>Mru,resolveExceptionStepsConfig:()=>T7o,reverseAndStripFrames:()=>Wru,stripReservedExceptionStepFields:()=>Sah,winjsStackLineParser:()=>zru});var jQ=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({});function GSe(e){let t=[];return JSON.stringify(e,function(r,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(n))return"[Circular]";t.push(n)}return n}})??"null"}var hsh=Array.isArray,aru=Object.prototype,PHv=aru.hasOwnProperty,C$r=aru.toString,e_=hsh||function(e){return C$r.call(e)==="[object Array]"};var F9t=e=>e===Object(e)&&!e_(e);var Ome=e=>e===void 0,pR=e=>C$r.call(e)=="[object String]",s7o=e=>pR(e)&&e.trim().length===0,a7o=e=>e===null,VK=e=>Ome(e)||a7o(e),zlt=e=>C$r.call(e)=="[object Number]"&&e===e;var cru=e=>C$r.call(e)==="[object Boolean]";function x$r(e){return e===null||typeof e!="object"}function BUe(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function qSe(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return pru(e,Error)}}function lru(e){return BUe(e,"ErrorEvent")}function Qlt(e){return"u">typeof Event&&pru(e,Event)}function uru(e){return BUe(e,"Object")}function pru(e,t){try{return e instanceof t}catch{return!1}}var gsh=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],S$r=new Map,Ash=256;function ysh(e,t){let r="";for(let n=0;n<t.length;n++){let i=t[n];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}var fru=function(e,t=[]){if(!e)return!1;let r=ysh(e,t),n=S$r.get(r);if(n!==void 0)return n;let i=e.toLowerCase(),o=gsh.concat(t).some(s=>i.indexOf(s.toLowerCase())!==-1);return S$r.size>=Ash&&S$r.clear(),S$r.set(r,o),o};function N9t(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),zlt(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),N9t(i??r,t,r,n))}var bsh=864e5,Esh=1,Ish=10;function dru(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??Esh,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??Ish}}var w$r=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=N9t(t.bucketSize,0,100,t._logger),this._refillRate=N9t(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=N9t(t.refillInterval,0,bsh,t._logger)}_applyRefill(t,r){let n=r-t.lastAccess,i=Math.floor(n/this._refillInterval);if(i>0){let o=i*this._refillRate;t.tokens=Math.min(t.tokens+o,this._bucketSize),t.lastAccess=t.lastAccess+i*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),n=String(t),i=this._buckets[n];return i?this._applyRefill(i,r):(i={tokens:this._bucketSize,lastAccess:r},this._buckets[n]=i),i.tokens===0?!0:(i.tokens--,i.tokens===0&&this._onBucketRateLimited?.(t),i.tokens===0)}stop(){this._buckets={}}};var T$r="0123456789abcdef",O$r=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length===16)return new e(t);throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||t<0||r<0||n<0||i<0||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");let o=new Uint8Array(16);return o[0]=t/2**40,o[1]=t/2**32,o[2]=t/2**24,o[3]=t/2**16,o[4]=t/256,o[5]=t,o[6]=112|r>>>8,o[7]=r,o[8]=128|n>>>24,o[9]=n>>>16,o[10]=n>>>8,o[11]=n,o[12]=i>>>24,o[13]=i>>>16,o[14]=i>>>8,o[15]=i,new e(o)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;default:break}if(r){let n=new Uint8Array(16);for(let i=0;i<16;i+=4){let o=parseInt(r.substring(2*i,2*i+8),16);n[i+0]=o>>>24,n[i+1]=o>>>16,n[i+2]=o>>>8,n[i+3]=o}return new e(n)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=T$r.charAt(this.bytes[r]>>>4),t+=T$r.charAt(15&this.bytes[r]),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=T$r.charAt(this.bytes[r]>>>4),t+=T$r.charAt(15&this.bytes[r]);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},c7o=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??vsh()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let n=this.generateOrAbortCore(t,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(t,r)),n}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return O$r.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,O$r.ofInner(t)}},vsh=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),mru,F2=()=>Csh().toString(),Csh=()=>(mru||(mru=new c7o)).generate();var P$r=class{add(t){let r=F2(),n=++this.nextId;return this.promiseByIds[r]={id:n,promise:t},t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds).map(n=>n.promise),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds).map(n=>n.promise),r=t.length}getPromises(t=[],r=this.nextId){let n=new Set(t);return Object.values(this.promiseByIds).filter(i=>i.id<=r&&!n.has(i.promise)).map(i=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function xsh(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var hru=(e,t,r)=>{function n(o,...s){t(()=>{let a=r[o];a(e,...s)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>hru(`${e} ${o}`,t,r)}},Ssh=e=>e();function gru(e,t=Ssh){return hru(e,t,xsh())}var Llt="Mobile",D$r="iOS",Mlt="Android",Iru="Tablet",GHv=Mlt+" "+Iru;var Tsh="Apple",qHv=Tsh+" Watch",vru="Safari",R$r="BlackBerry",Cru="Samsung",Osh=Cru+"Browser",Psh=Cru+" Internet",k$r="Chrome",Bsh=k$r+" OS",Dsh=k$r+" "+D$r,xru="Internet Explorer",Rsh=xru+" "+Llt,p7o="Opera",WHv=p7o+" Mini",Sru="Edge",ksh="Microsoft "+Sru,f7o="Firefox",Fsh=f7o+" "+D$r,d7o="Nintendo",m7o="PlayStation",B$r="Xbox",Nsh=Mlt+" "+Llt,jsh=Llt+" "+vru,j9t="Windows",zsh=j9t+" Phone";var wru="Generic",HHv=wru+" "+Llt.toLowerCase(),KHv=wru+" "+Iru.toLowerCase(),Qsh="Konqueror",Msh="Oculus Browser",Aru="Vivaldi",Lsh="Yandex",yru="Whale",_sh="DuckDuckGo",Ush="Pale Moon",bru="Waterfox",Eru="Brave",Tru="Claude",Oru="Codex",Pru="ChatGPT",Vsh="Google Search App",Wb="(\\d+(\\.\\d+)?)",l7o=new RegExp("Version/"+Wb),u7o=new RegExp("("+Tru+"|"+Oru+"|"+Pru+")\\/"+Wb);var JHv=new RegExp(B$r,"i"),YHv=new RegExp(m7o+" \\w+","i"),XHv=new RegExp(d7o+" \\w+","i"),Gsh=new RegExp(R$r+"|PlayBook|BB10","i"),qsh={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var ZHv={[Rsh]:[new RegExp("rv:"+Wb)],[ksh]:[new RegExp(Sru+"?\\/"+Wb)],[k$r]:[new RegExp("("+k$r+"|CrMo)\\/"+Wb)],[Dsh]:[new RegExp("CriOS\\/"+Wb)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Wb)],[vru]:[l7o],[jsh]:[l7o],[p7o]:[new RegExp("("+p7o+"|OPR)\\/"+Wb)],[f7o]:[new RegExp(f7o+"\\/"+Wb)],[Fsh]:[new RegExp("FxiOS\\/"+Wb)],[Qsh]:[new RegExp("Konqueror[:/]?"+Wb,"i")],[R$r]:[new RegExp(R$r+" "+Wb),l7o],[Nsh]:[new RegExp("android\\s"+Wb,"i")],[Psh]:[new RegExp(Osh+"\\/"+Wb)],[Msh]:[new RegExp("OculusBrowser\\/"+Wb)],[Aru]:[new RegExp(Aru+"\\/"+Wb)],[Lsh]:[new RegExp("YaBrowser\\/"+Wb)],[yru]:[new RegExp(yru+"\\/"+Wb)],[Eru]:[new RegExp(Eru+"\\/"+Wb)],[Tru]:[u7o],[Oru]:[u7o],[Pru]:[u7o],[_sh]:[new RegExp("(DuckDuckGo|Ddg)\\/"+Wb)],[Ush]:[new RegExp("PaleMoon\\/"+Wb)],[bru]:[new RegExp(bru+"\\/"+Wb)],[Vsh]:[new RegExp("GSA\\/"+Wb)],[xru]:[new RegExp("(rv:|MSIE )"+Wb)],Mozilla:[new RegExp("rv:"+Wb)]};var $Hv=[[new RegExp(B$r+"; "+B$r+" (.*?)[);]","i"),e=>[B$r,e&&e[1]||""]],[new RegExp(d7o,"i"),[d7o,""]],[new RegExp(m7o,"i"),[m7o,""]],[Gsh,[R$r,""]],[new RegExp(j9t,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[zsh,""];if(new RegExp(Llt).test(t)&&!/IEMobile\b/.test(t))return[j9t+" "+Llt,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=qsh[n]||"";return/arm/i.test(t)&&(i="RT"),[j9t,i]}return[j9t,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[D$r,t.join(".")]}return[D$r,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=Ome(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Mlt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Mlt+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Mlt,t.join(".")]}return[Mlt,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Bsh,""]],[/Linux|debian/i,["Linux",""]]];var F$r="[Circular]",N$r="[Truncated]",Z5="[Unserializable]",Bru="[Function]",rKv=Date.prototype.getTime,nKv=Date.prototype.toISOString;function ire(e){let t="";for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="\uFFFD"}else t+=n>=56320&&n<=57343?"\uFFFD":e[r]}return t}function Pme(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let n of r){let i;try{i=t[n]}catch{i=Z5}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}function h7o(e,t=Date.now()){if(typeof e!="string"||!e)return;let r=e.trim(),n=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(n)){let s=1e3*Math.min(Number(n),300);return s>0?s:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;let i=/^\w{3} \w{3} /.test(n)?n+" GMT":n,o=Date.parse(i)-t;if(!(!Number.isFinite(o)||o<=0))return Math.min(o,3e5)}var DUe=class{record(t){if(t.kind==="too-large")return;if(t.kind!=="retry-later")return void this.reset();if(!t.retryAfterMs)return;let r=this.isOpen(),n=Date.now(),i=Math.min(t.retryAfterMs,3e5);if(!r){this._installedAt=n,this._until=n+i;return}this._until=Math.max(this._until,Math.min(n+i,this._installedAt+3e5))}remainingMs(){let t=Date.now();if(t<this._installedAt-5e3)return this.reset(),0;let r=Math.min(3e5,Math.max(0,this._until-t));return r===0&&this.reset(),r}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var Dru="utf8",Wsh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Hsh(e){return typeof e=="string"&&Wsh.test(e)}function RUe(e,t){return Hsh(e)?e:t()}function _lt(e,t){let r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function Rru(e){return e?.replace(/\/+$/,"")}async function kru(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){n>0&&await new Promise(i=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function g7o(){return new Date().toISOString()}function N2(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function WSe(e,t,r){let n;try{return await Promise.race([e,new Promise((i,o)=>{n=N2(()=>{try{r?.(),i()}catch(s){o(s)}},t)})])}finally{clearTimeout(n)}}var Fru=e=>e&&typeof e.then=="function";function z9t(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var j$r,Nru,z$r;function jru(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return z$r&&r.length===Nru||(Nru=r.length,z$r=r.reduce((n,i)=>{j$r||(j$r={});let o=j$r[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let l=s[a]?.filename,u=t[i];if(l&&u){n[l]=u,j$r[i]=[l,u];break}}}return n},{})),z$r}var A7o=50,Ksh=1e3,Jsh=100,Ysh=4,Q9t=class{constructor(t,r,n=[]){this.coercers=t,this.stackParser=r,this.modifiers=n}buildFromUnknown(t,r={}){let i=r&&r.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,r,0).apply(t),a=this.buildParsingContext(r),c=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(c,i),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&e_(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let n;t.cause!=null&&(n=this.parseStacktrace(t.cause,r));let i;if(t.stack!=""&&t.stack!=null)try{i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)}catch{}return{...t,cause:n,stack:i,errors:t.errors?.map(o=>this.parseStacktrace(o,r))}}applyChunkIds(t,r){return t.map(n=>(n.filename&&r&&(n.chunk_id=r[n.filename]),n))}applyCoercers(t,r){for(let n of this.coercers)if(n.match(t))return n.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let n of this.modifiers)r=await n(r);return r}convertToExceptionList(t,r){let n=[],i=(o,s,a)=>{let c=n.length,l=s===void 0?{type:typeof r.type=="string"&&r.type.length>0?r.type:"generic",...typeof r.handled=="boolean"?{handled:r.handled}:r.handled===void 0?{handled:!0}:{},synthetic:typeof r.synthetic=="boolean"?r.synthetic:o.synthetic,exception_id:c}:{type:"chained",source:a,synthetic:o.synthetic,exception_id:c,parent_id:s},u={type:o.type,value:o.value,mechanism:l};o.stack&&(u.stacktrace={type:"raw",frames:o.stack}),n.push(u),o.cause&&i(o.cause,c,"cause");for(let p of o.errors??[])i(p,c,"member")};return i(t),n}buildParsingContext(t){return{chunkIdMap:jru(this.stackParser),skipFirstLines:t.skipFirstLines??1}}getAggregateErrors(t){try{if(qSe(t)){let r=Object.getPrototypeOf(t);for(let n=0;r&&n<Jsh;n++){let i=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof i=="function"&&i.name==="AggregateError"){let o=t.errors;return e_(o)?o:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(t,r,n=0){let i=0,o=0,s=!1,a=new Set,c=[],l={},u=(f,m,g=0)=>{let A=p(m,g),b=A.apply;if(A.apply=D=>{c.push(f);try{return b(D)}finally{c.pop()}},g>Ysh||g>0&&c.indexOf(f)!==-1)return this.coerceFallback(A);let I=typeof f=="object"&&f!==null||typeof f=="function";if(g===0&&i>=A7o||I&&a.has(f))return;I&&a.add(f),g===0&&i++;let C=this.getAggregateErrors(f);s||=!!C;let x;try{if(x=this.applyCoercers(f,A),!x)throw l}catch(D){if(D===l){g===0&&i--;return}if(!s)throw D;x=this.coerceFallback(A)}if(!C||i>=A7o)return x;let S;try{S=C.length}catch{return x}if(!Number.isInteger(S)||S<0||S>4294967295)return x;let B=[];for(let D=0;i<A7o&&o<Ksh&&D<S;D++){o++;let R;try{R=A.next(C[D])}catch{i++,R=this.coerceFallback(p(m+1))}R&&B.push(R)}return{...x,errors:B}},p=(f,m=0)=>({...r,syntheticException:f==0?r.syntheticException:void 0,mechanism:f==0?t:{},apply:g=>{let A=u(g,f,m+1);if(!A)throw l;return A},next:g=>u(g,f+1)}),d=p(n);return{...d,apply:f=>u(f,n)??this.coerceFallback(d)}}};var mB="?",Xsh="<anonymous>",Zsh=/^([a-z][a-z0-9.+-]+):/i,$sh=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function eah(e){if(!e||e===Xsh)return!1;let t=Zsh.exec(e);return!t||$sh.includes(t[1].toLowerCase())}function ore(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?mB:r,in_app:eah(t)};return Ome(n)||(o.lineno=n),Ome(i)||(o.colno=i),o}var Q$r=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:mB,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var tah=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,rah=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,nah=/\((\S*)(?::(\d+))(?::(\d+))\)/,y7o=(e,t)=>{let r=tah.exec(e);if(r){let[,i,o,s]=r;return ore(t,i,mB,+o,+s)}let n=rah.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=nah.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=Q$r(n[1]||mB,n[2]);return ore(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var iah=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,oah=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,b7o=(e,t)=>{let r=iah.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=oah.exec(r[3]);s&&(r[1]=r[1]||"eval",r[3]=s[1],r[4]=s[2],r[5]="")}let i=r[3],o=r[1]||mB;return[o,i]=Q$r(o,i),ore(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var sah=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,zru=(e,t)=>{let r=sah.exec(e);return r?ore(t,r[2],r[1]||mB,+r[3],r[4]?+r[4]:void 0):void 0};var aah=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Qru=(e,t)=>{let r=aah.exec(e);return r?ore(t,r[2],r[3]||mB,+r[1]):void 0},cah=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Mru=(e,t)=>{let r=cah.exec(e);return r?ore(t,r[5],r[3]||r[4]||mB,+r[1],+r[2]):void 0};var lah=/^\s*[-]{4,}$/,uah=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,pah=/^Promise\.(?:all|any)$/,fah=/^index \d+$/,dah="node:internal/promise",_ru=(e,t)=>{let r=e.match(uah);if(r){let n,i,o,s,a;if(r[1]){o=r[1];let u=o.lastIndexOf(".");if(o[u-1]==="."&&u--,u>0){n=o.slice(0,u),i=o.slice(u+1);let p=n.indexOf(".Module");p>0&&(o=o.slice(p+1),n=n.slice(0,p))}s=void 0}i&&(s=n,a=i),i==="<anonymous>"&&(a=void 0,o=void 0),o===void 0&&(a=a||mB,o=s?`${s}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!l&&(c=r[5]),pah.test(o)&&fah.test(c||"")&&(c=dah),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:Lru(r[3]),colno:Lru(r[4]),in_app:mah(c||"",l),platform:t}}if(e.match(lah))return{filename:e,platform:t}};function mah(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function Lru(e){return parseInt(e||"",10)||void 0}var Uru=/\(error: (.*)\)/,Vru=50,hah=10,gah=1e3;function E7o(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function Aah(e){for(let t=1;t<=hah;t++){let r=e.length-2*t;if(r<0)break;let n=!0;for(let i=0;i<t;i++){let o=e[r+i];if(!E7o(o,e[r+t+i])){n=!1;break}}if(n){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}function yah(e,t){let r=t.start+t.length,n=qru(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function Gru(e,t){let r=t.start;for(;r>0&&E7o(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function qru(e,t){let r=t.start+t.length,n=r;for(;n<e.length&&E7o(e[n],e[n-t.length]);)n++;return n-r}function bah(e,t){let r=t[0],n=e.length-(r?Gru(e,r):0);for(let i of t)n-=qru(e,i);return n}function Eah(e){let t=e.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),r=0;for(let n=1;n<t.length;n++)Iah(t,n,r)&&(r=n);e.push(...e.splice(0,r))}function Iah(e,t,r){for(let n=0;n<e.length;n++){let i=e[(t+n)%e.length],o=e[(r+n)%e.length];if(i!==o)return i<o}return!1}function Wru(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Vru).map(r=>({...r,filename:r.filename||vah(t).filename,function:r.function||mB}))}function vah(e){return e[e.length-1]||{}}function I7o(){return Hru("web:javascript",y7o,b7o)}function Hru(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
3481
3481
  `),s=Math.min(o.length,n+gah),a=[];for(let u=n;u<s;u++){let p=o[u];if(p.length>1024)continue;let d=Uru.test(p)?p.replace(Uru,"$1"):p;if(!d.match(/\S*Error: /)){for(let f of t){let m=f(d,e);if(m){i.push(m);let g=Aah(i);if(g){for(let A=a.length-1;A>=0;A--){let b=a[A];if(b.start+b.length<=g.start)break;a.pop()}a.push(g)}break}}if(bah(i,a)>=Vru)break}}let c=[...a].sort((u,p)=>p.start-u.start),l=c[c.length-1];if(l){let u=Gru(i,l);i.splice(l.start-u,u);for(let p of c)p.start-=u}for(let u of c)yah(i,u);return a.some(u=>u.start===0&&i.length===u.length)&&Eah(i),Wru(i)}}var v7o=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=pR(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return BUe(t,"DOMException")}isDOMError(t){return BUe(t,"DOMError")}};var M9t=class{match(t){return qSe(t)}coerce(t,r){let n=this.getStack(t),i=n===void 0?r.syntheticException?.stack:void 0,o=!!i;return{type:this.getType(t),value:this.getMessage(t,r),stack:n??i,cause:t.cause?r.next(t.cause):void 0,synthetic:o}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){try{let r=t.stacktrace;if(typeof r=="string"&&r.length>0)return r;let n=t.stack;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}};var C7o=class{match(t){if(!lru(t))return!1;let r=t;return r.error!=null||this._hasUsableMessage(r)}coerce(t,r){if(t.error!=null)return r.apply(t.error);let n=r.apply(t.message);return{...n,stack:this._buildLocationStack(t)??n.stack,synthetic:!0}}_hasUsableMessage(t){return pR(t.message)&&t.message.length>0}_buildLocationStack(t){let r=t,n=r.lineno??0,i=r.colno??0;if(!(!pR(r.filename)||r.filename.length===0)&&n!==0)return`Error
3482
- at ${r.filename}:${n}:${i}`}};var Cah=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,L9t=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(Cah);return i&&(r=i[1],n=i[2]),[r,n]}};var Kru=["fatal","error","warning","log","info","debug"];function M$r(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var _9t=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:this.getStack(t)??r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(Qlt(t))return t.constructor.name;let r="name"in t?t.name:void 0;return pR(r)&&!s7o(r)?r:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=M$r(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return pR(t)&&!s7o(t)&&Kru.indexOf(t)>=0}getStack(t){try{return pR(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:pR(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(qSe(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var x7o=class{match(t){return Qlt(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${M$r(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var U9t=class{match(t){return x$r(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var S7o=class{match(t){return BUe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Qlt(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return x$r(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var w7o=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var V9t={MESSAGE:"$message",TIMESTAMP:"$timestamp"},xah=new Set([V9t.MESSAGE,V9t.TIMESTAMP]),L$r={enabled:!0,max_bytes:32768};function T7o(e){return e?{enabled:e.enabled??L$r.enabled,max_bytes:wah(e.max_bytes,L$r.max_bytes)}:{...L$r}}function Sah(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>xah.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var O7o=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=T7o(t)}setConfig(t){this._config=T7o(t),this._trimToMaxBytes()}add(t){let r=Tah(t);if(!r)return;let n=Jru(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function wah(e,t){if(!zlt(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function Tah(e){let t;try{t=GSe(e)}catch{return}try{let r=JSON.parse(t);if(!F9t(r))return;let n=r,i=n[V9t.MESSAGE],o=n[V9t.TIMESTAMP];return!pR(i)||i.trim().length===0||!pR(o)&&!zlt(o)?void 0:{step:n,json:t}}catch{return}}function Jru(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}function Oah(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var P7o=e=>{if("flags"in e){let t=Yru(e.flags),r=Xru(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,Ult(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Pah(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function Pah(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var Yru=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,G9t(r)]).filter(([,t])=>t!==void 0)),Xru=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?Ult(n):void 0]}))},G9t=e=>e===void 0?void 0:e.variant??e.enabled,Ult=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Zru=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],Bah=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...Zru,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],q9t=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return Bah.forEach(n),t.forEach(n),r};var _$r=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}};function B7o(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var Rah="NativeGzipValidationError",kah=31,Fah=139,Nah=8,jah=e=>e.length>=2&&e[0]===kah&&e[1]===Fah;var W9t,zah=()=>{if(W9t)return W9t;W9t=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;W9t[e]=t>>>0}return W9t},Qah=e=>{let t=zah(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},U$r=e=>{throw _lt(Rah,`Native gzip produced invalid output: ${e}`)},Mah=async(e,t)=>{e.size<18&&U$r("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!jah(r)||r[2]!==Nah)&&U$r("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==Qah(t)&&U$r("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&U$r("invalid-size")};async function H9t(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async l=>{try{await o.abort(l)}catch{}throw l}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await Mah(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var $5=class extends Error{constructor(t,r,n,i){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return h7o(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let t=_lt("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=N2(()=>{this._bodyReadTimedOut=!0;let o=_lt("AbortError","Response body read timed out");i(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(t=>JSON.parse(t))}cancelResponseBody(t){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(t),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},Bme=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var nnu=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function $ru(e){if(e instanceof $5){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function Lah(e){return typeof e=="object"&&(e instanceof $5||inu(e))}function inu(e){return e instanceof Bme}function _ah(e){if(e instanceof $5)return e.status===502||e.status===504;if(!(e instanceof Bme))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var enu=10485760;function tnu(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,Dru):new TextEncoder().encode(e).length}catch{return 0}}function Vlt(e){return typeof e=="object"&&e instanceof $5&&e.status===413}function V$r(e){return e instanceof $5?e.status===408||e.status===429||e.status>=500:inu(e)}function rnu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var D7o="default",K9t=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Q9t([new M9t,new _9t,new L9t,new U9t],I7o())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new P$r,this._events=new _$r,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=gru("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Rru(i||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:V$r},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!B7o()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(jQ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(jQ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(jQ.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){let r=t.properties||{},n={...r,...this.getCommonEventProperties()};return nnu(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=q9t(n)),{distinct_id:t.distinct_id,event:t.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(t,r,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{type:"required",consume:i=>i.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,l={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:_ah},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:P7o(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof $5)return{type:"api_error",statusCode:t.status};if(t instanceof Bme){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(t,r,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let c=G9t(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,i,o,s,[t]);return a===void 0?void 0:{response:a.flags[t],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,i,o,s,[t]);if(!a)return;let c=a[t];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let l=c.response;return l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r,{type:"required",consume:o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);return this._logger.error(a),this._events.emit("error",new Error(s)),Promise.resolve(void 0)}return o.json()}}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(jQ.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(jQ.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(jQ.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return D7o}persistedQueueKeyForRoute(t){return jQ.Queue}getActiveQueueRoutes(){return[D7o]}getRouteQueue(t){return this.getPersistedProperty(this.persistedQueueKeyForRoute(t))||[]}enqueue(t,r,n,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let s=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(o)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(s,a),this._events.emit(t,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=N2(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,i??this.getQueueRouteKey(o))}catch(s){this._events.emit("error",s)}}}normalizeMessage(t){let{type:r,library:n,library_version:i,...o}=t,s=rnu(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=RUe(o.uuid,F2),o}normalizeTimestampForWire(t){let r=t instanceof Date?t:typeof t=="string"?new Date(t):null;if(!r||Number.isNaN(r.getTime()))return t;let n=r.toISOString(),i=typeof t=="string"?t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}prepareMessage(t,r){let n={...t,timestamp:r?.timestamp?r?.timestamp:g7o(),uuid:RUe(r?.uuid,F2)};return(r?.disableGeoip??this.disableGeoip)&&(rnu(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async t=>{await $ru(t)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(t,r=[]){let n=r.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],t);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(t){if(this.disabled)return Promise.resolve();if(!t&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(t)return this.waitForPendingPromises(n,[r,i])}).then(()=>z9t([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),z9t([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}compressPayload(t){return H9t(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=D7o){let i={api_key:this.apiKey,batch:t.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:g7o()};this.historicalMigration&&(i.historical_migration=!0);let o=GSe(i),s=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(s,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(i=>this.getRouteQueue(i).length>0))return;let r=[],n;for(let i of t)try{await this._flushRoute(i,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(t,r){let n=this.persistedQueueKeyForRoute(t),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),c=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),l=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(b=>b===m||typeof g=="string"&&g.length>0&&b.message?.uuid===g);return A===-1?!0:(d.splice(A,1),!1)});this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:p=>Vlt(p)?!1:V$r(p)};try{await this.sendBatch(c,u,t)}catch(p){if(Vlt(p)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof Bme||await l(),this._events.emit("error",p),p}await l(),r.push(...c),s+=c.length}}async _sendOtlpBatch({path:t,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let i;try{i=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let o=tnu(i);if(o>enu)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${enu}`)),{kind:"too-large",measuredLocally:!0};let s=r==="bearer"?`${this.host}/i/v1/${t}`:`${this.host}/i/v1/${t}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),c=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(s,l,{type:"successful-write"},{retryCheck:u=>Vlt(u)||u instanceof $5&&u.retryAfterMs!==void 0?!1:V$r(u)}),{kind:"ok"}}catch(u){if(Vlt(u))return{kind:"too-large"};if(V$r(u)){let p=u instanceof $5?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:u}}}async _sendLogsBatch(t){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:t})}async _sendMetricsBatch(t){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:t})}async _sendTracesBatch(t){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:t})}async fetchWithRetry(t,r,n,i,o){let s=r.body?r.body:"",a=tnu(s),c={...this._retryOptions,...i},l=0;return await kru(async()=>{l++;let u=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((C,x)=>{f=N2(()=>{let S=_lt("AbortError",`Request timed out after ${p}ms`);x(S),u.abort(S)},p)}),g,A=!1,b,I=()=>b??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let C;try{C=this.fetch(t,{signal:u.signal,...r})}catch(B){throw new Bme(B)}C.then(B=>{u.signal.aborted&&!A&&Promise.resolve(B.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([C,m]),A=!0}catch(B){throw new Bme(B)}let x=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!x&&(g.status<200||g.status>=S))throw new $5(g,a,d,u);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(B){throw u.signal.aborted?new Bme(B):B}}finally{clearTimeout(f),u.signal.aborted&&g&&I()}},{...c,retryCheck:u=>{let p=c.retryCheck(u);return p&&l<=c.retryCount&&u instanceof $5&&u.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:WSe((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(s=>this.getRouteQueue(s).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!Lah(i))throw i;await $ru(i)}})(),t,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:t}),r=!0})}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var Wah=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var lYv=new RegExp(Wah.source,"i"),onu=/[a-z][a-z0-9+.-]{0,63}:\/\//i,uYv=new RegExp(`^${onu.source}`,"i"),pYv=new RegExp(onu.source,"gi");var Hah=["is_not","is_set"],Kah=1152921504606847e3,Ul=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function R7o(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!R7o(t in e?e[t]:null))return!1;return!0}function k7o(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!k7o(t in e?e[t]:null))return!1;return!0}function J9t(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Ul("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new Ul("Cannot stringify an unpaired surrogate like the flags service")}}function q$r(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void J9t(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Ul(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new Ul("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&q$r(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Ul("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new Ul("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))J9t(n),q$r(e[n],t)}finally{t.delete(e)}return}throw new Ul(`Cannot represent ${typeof e} like the flags service`)}}function Jah(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let i=e.charCodeAt(r),o=t.charCodeAt(n),s=i>=55296&&i<=56319,a=o>=55296&&o<=56319,c=s?e.charCodeAt(r+1):0,l=a?t.charCodeAt(n+1):0,u=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+l-56320+65536:o;if(u!==p)return u-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function F7o(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return J9t(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new Ul(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new Ul(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new Ul("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let n=0;n<e.length;n++)r.push(n in e?F7o(e[n],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Ul("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new Ul("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(J9t),`{${n.sort(Jah).map(i=>`${JSON.stringify(i)}:${F7o(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new Ul(`Cannot stringify ${typeof e} like the flags service`)}function G$r(e){return typeof e=="string"?(J9t(e),e):F7o(e)}function snu(e){try{return new RegExp(e),!0}catch{return!1}}function e8(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function cnu(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new Ul(`Invalid semver: ${t}`);return parseInt(e,10)}function Cw(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new Ul(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:cnu(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function t8(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function Yah(e,t){let r=Cw(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Xah(e,t){let[r,n,i]=Cw(e,t),o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function Zah(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new Ul(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return cnu(c,e,t)}catch{}throw new Ul(`Invalid wildcard semver: ${e}`)},s=o(i[0]);if(i.length===1)return{lower:[s,0,0],upper:[s+1,0,0]};let a=o(i[1]);return{lower:[s,a,0],upper:[s,a+1,0]}}function anu(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Ul(`${e} is in an invalid date format`)}throw new Ul(`The date provided ${e} must be a string, number, or date object`)}function N7o(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r||!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o==="h")n.setUTCHours(n.getUTCHours()-i);else if(o==="d")n.setUTCDate(n.getUTCDate()-i);else if(o==="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o==="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}function j7o(e,t,r={}){let n=e.key,i=e.value,o=e.operator||"exact",s=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new Ul(`Property ${n} not found in propertyValues`);let c=t[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!Hah.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let l=(p,d)=>{if(r.propertyMatchingVersion!==2&&R7o(p)||Array.isArray(p)&&p.length===0)return q$r(d),k7o(p)===k7o(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&R7o(p))return q$r(d),!1;if(Array.isArray(p)){let f=G$r(d).toLowerCase();return p.some(m=>G$r(m).toLowerCase()===f)}return G$r(p).toLowerCase()===G$r(d).toLowerCase()},u=(p,d,f)=>{if(f==="gt")return p>d;if(f==="gte")return p>=d;if(f==="lt")return p<d;if(f==="lte")return p<=d;throw new Error(`Invalid operator: ${f}`)};switch(o){case"exact":return l(i,c);case"is_not":return!l(i,c);case"is_set":return!0;case"icontains":return e8(c).includes(e8(i));case"not_icontains":return!e8(c).includes(e8(i));case"starts_with":return e8(c).startsWith(e8(i));case"not_starts_with":return!e8(c).startsWith(e8(i));case"ends_with":return e8(c).endsWith(e8(i));case"not_ends_with":return!e8(c).endsWith(e8(i));case"regex":return snu(String(i))&&String(c).match(String(i))!==null;case"not_regex":return snu(String(i))&&String(c).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let p=typeof i=="number"?i:parseFloat(String(i)),d=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(p)&&Number.isFinite(d)?u(d,p,o):u(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Ul("Date operations cannot be performed on boolean values");let p=N7o(String(i));p==null&&(p=anu(i));let d=anu(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return t8(Cw(String(c),s),Cw(String(i),s))===0;case"semver_neq":return t8(Cw(String(c),s),Cw(String(i),s))!==0;case"semver_gt":return t8(Cw(String(c),s),Cw(String(i),s))>0;case"semver_gte":return t8(Cw(String(c),s),Cw(String(i),s))>=0;case"semver_lt":return t8(Cw(String(c),s),Cw(String(i),s))<0;case"semver_lte":return t8(Cw(String(c),s),Cw(String(i),s))<=0;case"semver_tilde":{let p=Cw(String(c),s),{lower:d,upper:f}=Yah(String(i),s);return t8(p,d)>=0&&t8(p,f)<0}case"semver_caret":{let p=Cw(String(c),s),{lower:d,upper:f}=Xah(String(i),s);return t8(p,d)>=0&&t8(p,f)<0}case"semver_wildcard":{let p=Cw(String(c),s),{lower:d,upper:f}=Zah(String(i),s);return t8(p,d)>=0&&t8(p,f)<0}default:throw new Ul(`Unknown operator: ${o}`)}}async function lnu(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function Y9t(e,t,r="",n="."){let i=await lnu(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/Kah}async function z7o(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await Y9t("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function W$r(e){let t=[],r=0;for(let n of e){let i=r+n.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:n.key}),r=i}return t}async function Q7o(e,t,r){let n=await Y9t(e,t,"variant");return W$r(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function M7o(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,n=e[r]||null;return n==null?null:Ult(n)}var unu=9223372036854776e3,$ah="9223372036854775808",ech=Object.prototype.propertyIsEnumerable;function tch(){return{ancestors:new WeakSet,remainingNodes:1e4}}function sre(e,t){try{return pnu(e,t,tch(),0)}catch{return[]}}function rch(e,t){let r=e.toString(),n=BigInt($ah);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function U7o(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:N$r};if(r.remainingNodes--,cru(e))return{boolValue:e};if(typeof e=="bigint")return rch(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();return e>=unu||e<-unu?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:ire(e)};if(typeof e=="function")return{stringValue:Bru};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:F$r};if(n>=20)return{stringValue:N$r};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?ire(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return U7o(i.call(e),t,r,n+1)}catch{}return e_(e)?{arrayValue:{values:nch(e,t,r,n+1)}}:{kvlistValue:{values:pnu(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:ire(String(e))}}function nch(e,t,r,n){let i=[],o=Math.min(e.length,1e3),s=0;for(;s<o&&r.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(VK(a))continue;i.push(U7o(a,t,r,n))}catch{i.push({stringValue:Z5})}return e.length>s&&i.push({stringValue:N$r}),i}function pnu(e,t,r,n){let i=[];for(let o in e)if(ech.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if(a7o(s)||Ome(s))continue;i.push({key:ire(o),value:U7o(s,t,r,n)})}catch{i.push({key:ire(o),value:{stringValue:Z5}})}}return i}function Z9t(e,t,r){return{...Pme({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var ich=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function $9t(e,t){let r=Pme({},e),n={};for(let i of ich)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...sre(r,t),...sre(n,t)]}var fnu={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function och(e){if(e)return Object.prototype.hasOwnProperty.call(fnu,e)?fnu[e]:e}function V7o(e,t){let r=och(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var sch={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},TYv=sch.info;var kUe=class{constructor(t){this._onFire=t,this._firesAt=0}get pending(){return!!this._timer}arm(t){this.clear(),this._firesAt=Date.now()+t,this._timer=N2(()=>{this._timer=void 0,this._onFire()},t)}armNoEarlierThan(t){this._timer&&Date.now()+t<=this._firesAt||this.arm(t)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function eqt(){return 1-.25+Math.random()*.25*2}var r8=1;function tqt(e,t,r,n){let i=Math.min(Math.max(0,t-1),6),o=e*2**i,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*r)}var rqt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function G7o(e){return String(e)+"000000"}function q7o(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}function dnu(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function W7o(e,t,r){return Z9t(e,t,r)}function H7o(e,t,r,n){return{resourceMetrics:[{resource:{attributes:$9t(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function K$r(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}}var mnu=1,nqt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new kUe(()=>this.flush().catch(i=>{this._logger.error("Metrics flush failed:",i)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new DUe,this._consecutiveFlushFailures=0,this._flushJitter=r8,this._generation=0}count(t,r=1,n){this._capture({name:t,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(t,r,n){this._capture({name:t,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(t,r,n){this._capture({name:t,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let t=this._flushPromise,n=(async()=>{t&&await t.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let t=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(t)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=r8,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(t){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(t);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=r.attributes?{...r.attributes}:void 0,i=q7o(r.type,r.name,r.unit,n)}catch(a){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(r.name);s===void 0?this._typeByName.set(r.name,r.type):s!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${s}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(t,r){switch(t.type){case"count":t.total=(t.total??0)+r;break;case"gauge":t.last=r;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(rqt.length+1).fill(0)});let n=t.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[dnu(r,rqt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=e_(r)?r:[r],i=t;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(tqt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let t=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(t));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=eqt()):(this._consecutiveFlushFailures=0,this._flushJitter=r8),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(t),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(t){return H7o(this._buildMetrics(t),W7o(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=G7o(Date.now()),n=new Map;for(let i of t.values()){let o=q7o(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:mnu,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:mnu,dataPoints:[]},n.set(o,s));let a=sre(i.attributes??{},this._logger),c=G7o(i.windowStartMs);if(i.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(l)}else if(i.type==="gauge"){let l={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(l)}else if(i.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:rqt};s.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(t){for(let[r,n]of t){let i=this._series.get(r);if(!i){this._admitNewSeries()&&this._series.set(r,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var uch="0".repeat(32),pch="0".repeat(16),fch=/^[0-9a-f]+$/;function dch(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());return t}function mch(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function hnu(e){let t=mch(dch(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function gnu(){return hnu(16)}function Anu(){return hnu(8)}function ynu(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&fch.test(e)}function bnu(e){return ynu(e,32,uch)}function Enu(e){return ynu(e,16,pch)}var hch=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Inu(e){let t=vnu(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:gch(t.flags)}}function gch(e){return 1&parseInt(e,16)?Y$r:Ach}function vnu(e){if(typeof e!="string")return;let t=hch.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!bnu(n)||!Enu(i)))return{version:r,traceId:n,spanId:i,flags:o}}function Cnu(e){return vnu(e)&&e.trim()}function J$r(e){return Array.isArray(e)&&e.length===1?e[0]:e}var Y$r="01",Ach="00";function xnu(e,t,r=Y$r){return`00-${e}-${t}-${r}`}var ych=32,K7o=512;function X$r(e){if(typeof e!="string")return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>ych)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=K7o?t:Ech(r)}}var bch=128;function Ech(e){let t=[...e],r=()=>t.reduce((n,i)=>n+i.length,0)+t.length-1;for(let n=t.length-1;n>=0&&r()>K7o;n--)t[n].length>bch&&t.splice(n,1);for(;t.length&&r()>K7o;)t.pop();return t.length?t.join(","):void 0}var Snu="unknown";function FUe(e,t,r,n){return typeof e=="string"&&e.trim()?e.length>r?e.slice(0,r):e:(n?.debug(`${t} must be a non-empty string; using "${Snu}"`),Snu)}function Glt(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(!(typeof t!="number"||!Number.isFinite(t))&&!(t<0||t>9223372036854))return t}function wnu(e,t,r){let n=Glt(e);return n===void 0?(e!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),t):(t-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>t&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function Z$r(e,t){return e<t?t:e}function iqt(e,t,r,n){let i=Glt(e);return i===void 0?(e!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):i}function een(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var qlt=class{constructor(t,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=t.traceId,this._spanId=t.spanId,this._parentSpanId=t.parentSpanId,this._traceState=t.traceState,this._traceFlags=t.traceFlags??Y$r,this._parentIsRemote=t.parentIsRemote??!1,this._name=t.name,this._kind=t.kind,this._autoKeys=new Set(t.autoAttributeKeys),this._maxAttributes=t.maxAttributes,this._maxEvents=t.maxEvents,this._maxAttributesPerEvent=t.maxAttributesPerEvent,this._maxAttributeValueLength=t.maxAttributeValueLength,this._attributes=Object.create(null);for(let i of Object.keys(t.attributes))this._writeAttribute(i,t.attributes[i]);this._startMono=t.backdated?void 0:een(),this._startTime=t.clockAnchor&&this._startMono!==void 0?t.clockAnchor.wall+(this._startMono-t.clockAnchor.mono):t.startTime,this._startMono!==void 0&&(this._clockAnchor=t.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let t=een();if(t!==void 0)return this._startTime+Math.max(0,t-this._startMono)}return Date.now()}_mutable(t){return this._ended?(this._logger?.debug(`Ignoring ${t} on a span that has already ended`),!1):!0}_writeAttribute(t,r){if(VK(r)){t in this._attributes&&!this._autoKeys.has(t)&&this._userAttributeCount--,delete this._attributes[t];return}if(!this._autoKeys.has(t)&&!(t in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[t]=ren(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=Pme({},t);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(t,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=r&&Bnu(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:FUe(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:iqt(n,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(t,r){if(this._mutable("setStatus")){if(t!=="ok"&&t!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(t)}"; expected "ok" or "error"`),this;this._status={code:t,...r&&{message:J7o(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(t){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:i}=Y7o(t);return this.addEvent(Ich,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=FUe(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return xnu(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(t){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=iqt(t,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:Z$r(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Ich="exception",vch=4294967295;function Cch(e){try{return typeof e=="string"?e:String(e)}catch{return Z5}}function NUe(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),vch)}function xch(e,t){if(!t.length)return Object.keys(e);let r=t.filter(i=>Object.prototype.propertyIsEnumerable.call(e,i)),n=new Set(r);return[...r,...Object.keys(e).filter(i=>!n.has(i))]}function Onu(e,t,r,n,i,o,s=[]){let a=0,c=0,l={};for(let f of xch(e.attributes,s)){let m=e.attributes[f];if(!VK(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(l,f,{value:ren(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=l,c&&(e.droppedAttributesCount=NUe(e.droppedAttributesCount)+c);let u=0,p=0,d=[];for(let f of e.events){if(u>=n){p++;continue}if(u++,f.attributes){let m=Bnu(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=NUe(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=NUe(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:J7o(Cch(e.status.message),o)})}var ten=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},Pnu=new ten,oqt=class extends ten{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Sch(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function HSe(e,t){let r=J$r(e?.parent)??t,n=typeof r=="string"||r==null?r:Tnu(r,"traceparent"),i=Cnu(n);if(!i)return Pnu;let o=typeof r=="string"||r==null?e?.tracestate:Tnu(r,"tracestate");return new oqt(i,X$r(o))}function Tnu(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function J7o(e,t){return e.length>t?e.slice(0,t):e}function ren(e,t){return $$r(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function $$r(e,t,r,n){if(e===null||typeof e!="object")return VK(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?J7o(e,t):e);if(r.ancestors.has(e))return F$r;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=wch(e);if(i.selfDescribed)return VK(i.value)?String(i.value):$$r(i.value,t,r,n+1);if(e_(e)){let a=Math.min(e.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push($$r(e[l],t,r,n+1))}catch{c.push(Z5)}return e.length>a&&(c.length=e.length),c}let o={},s=0;for(let a of Object.keys(e)){if(s>=1e3)break;let c;try{c=$$r(e[a],t,r,n+1)}catch{c=Z5}a&&!VK(c)&&s++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return e}finally{r.ancestors.delete(e)}}function wch(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Bnu(e,t,r){let n;try{n=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},o=0,s=0;for(let a of n){if(o>=t){s++;continue}let c;try{c=ren(e[a],r)}catch{c=Z5}VK(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function Dnu(e,t){for(let r of Object.keys(e))e[r]=ren(e[r],t);return e}function sqt(e,t,r){return t===Pnu?r(t):e.with(t,()=>r(t))}function Y7o(e){try{let t=Sch(e);if(qSe(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var X7o={internal:1,server:2,client:3,producer:4,consumer:5},Tch={ok:1,error:2},Och=1,Pch=256,Bch=512;function Dch(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:Och)|Pch|(e.parentIsRemote?Bch:0)}function nen(e){if(typeof e=="string")return ire(e);try{return ire(String(e))}catch{return Z5}}function Rch(e){return e&&Object.prototype.hasOwnProperty.call(X7o,e)?X7o[e]:X7o.internal}function Z7o(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function kch(e,t){let r={name:nen(e.name),timeUnixNano:Z7o(e.timestamp)};if(e.attributes){let i=sre(e.attributes,t);i.length&&(r.attributes=i)}let n=NUe(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function Rnu(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:nen(e.name),kind:Rch(e.kind),startTimeUnixNano:Z7o(e.startTime),endTimeUnixNano:Z7o(e.endTime),flags:Dch(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=nen(e.traceState));let n=sre(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>kch(s,t)));let i=NUe(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=NUe(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:Tch[e.status.code],...e.status.message&&{message:nen(e.status.message)}}),r}function knu(e,t,r){return Z9t(e,t,r)}function Fnu(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:$9t(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var Nnu=8;function ien(){return een()??Date.now()}function $7o(e){try{return e instanceof qlt}catch{return!1}}function jnu(e,t){let r=Inu(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:X$r(t),traceFlags:r.flags,isRemote:!0}}function Fch(e){try{return typeof e.traceparent=="function"}catch{return!1}}function Nch(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function oen(e,t,r){e[t]!==r&&(e[t]=r)}function jch(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:t[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}var aqt=class{constructor(t,r,n,i,o,s){this._instance=t,this._config=r,this._logger=n,this._getContext=i,this._contextManager=o,this._onSpanQueued=s,this._queue=[],this._flushTimer=new kUe(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=r8,this._retryAfter=new DUe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(t,r){if(this._instance.isDisabled||this._instance.optedOut)return HSe(r,this._contextManager.active());let n=J$r(r?.parent);if(n&&typeof n!="string"&&!$7o(n)){if(Fch(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),HSe(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let i=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),HSe(r,this._contextManager.active());let o=Date.now(),s=wnu(r?.startTime,o,this._logger),a=Anu();this._liveSpans.set(a,ien());let c=this._autoContextAttributes();return new qlt({traceId:i?.traceId??gnu(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:FUe(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:Pme({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:s,backdated:s!==o,clockAnchor:Glt(r?.startTime)===void 0?i?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this.startSpan(t,i);try{let a=sqt(this._contextManager,s,o);return Fru(a)?a.then(c=>(s.end(),c),c=>{throw this._recordCallbackError(s,c),s.end(),c}):(s.end(),a)}catch(a){throw this._recordCallbackError(s,a),s.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let t=this._generation,r=Promise.resolve().then(()=>t===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=r8,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=jnu(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if($7o(t))return t.childContext();let n=this._contextManager.active();if($7o(n))return n.childContext();if(n instanceof oqt)return jnu(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let t;try{t=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return t.distinctId&&(r.posthogDistinctId=t.distinctId),t.sessionId&&(r.sessionId=t.sessionId),t.currentUrl&&(r["url.full"]=t.currentUrl),t.screenName&&(r["screen.name"]=t.screenName),t.appState&&(r["app.state"]=t.appState),r}_recordCallbackError(t,r){if(!(t instanceof qlt))return;let{type:n,message:i,stack:o}=Y7o(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=ien()-this._config.maxSpanAgeMs,r=0;for(let[n,i]of this._liveSpans){if(i>t)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(t,r){if(!this._liveSpans.delete(t.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(t,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(i){this._logger.debug("Span queue notification failed",i)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(t){let r=t.droppedAttributesCount??0,n=t.droppedEventsCount??0,i=0;for(let o of t.events)i+=o.droppedAttributesCount??0;(r||n||i)&&this._logger.debug(`Span limits discarded data from "${t.name}": ${r} attributes, ${n} events, ${i} event attributes`)}_runBeforeSpanSend(t,r){if(!this._config.beforeSpanSend.length)return t;let n={traceId:t.traceId,spanId:t.spanId,parentSpanId:t.parentSpanId,traceState:t.traceState},i={startTime:t.startTime,endTime:t.endTime},o={attributes:t.droppedAttributesCount,events:t.droppedEventsCount},s=Object.keys(t.attributes),a={traceFlags:t.traceFlags,parentIsRemote:t.parentIsRemote},c=t.status&&{...t.status},l=t,u=t;try{for(let f of this._config.beforeSpanSend){let m=f(l);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(m,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!Nch(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=FUe(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=Glt(u.startTime)??i.startTime,u.endTime=Z$r(Glt(u.endTime)??i.endTime,u.startTime);let d=[];for(let f of u.events)try{d.push({...f,name:FUe(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:iqt(f.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=d,Onu(u,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),u}catch(p){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",p),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(t,r){(t.traceId!==r.traceId||t.spanId!==r.spanId||t.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{oen(t,"traceId",r.traceId),oen(t,"spanId",r.spanId),oen(t,"parentSpanId",r.parentSpanId),oen(t,"traceState",r.traceState)}catch{return jch(t,r)}return t}_recordDrop(t,r){this._droppedSinceWarning+=t,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(t){let r=[];for(let n of t)try{r.push(Rnu(n,this._logger))}catch(i){this._logger.debug("Failed to encode a span; dropping it",i),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let t=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(t,"the user has opted out"),this._warnAboutDrops(),t}async _flushInner(){if(!this._queue.length)return 0;let t=this._discardQueueIfConsentWithdrawn();if(t)return t;let r=Dnu(knu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),o=this._queue.length,s=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return s+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(u,a,o,this._queue.length)),d=this._queue.slice(0,p),f=this._encodeBatch(d);if(!f.length){this._queue.splice(0,p),o-=p,s+=p,this._resetHeadBatchBudget();continue}let m=ien()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(Fnu(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=r8,this._resetHeadBatchBudget(),this._queue.splice(0,p),o-=p,s+=p,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(g.kind==="too-large"){if(p===1){this._queue.splice(0,1),o-=1,s+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=r8,this._resetHeadBatchBudget();continue}let A=Math.max(1,Math.floor(p/2));g.measuredLocally?a=A:this._maxExportBatchSize=A,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${A}`);continue}if(g.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=eqt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=ien()+this._nextFlushDelay()),this._headBatchFailures<Nnu)return this._logger.debug("Span export failed; retrying on the next flush",g.error),s;if(this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=r8,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${Nnu} times in a row`),this._retryAfter.isOpen())return s;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=r8,this._resetHeadBatchBudget(),this._recordDrop(p,"the ingestion endpoint rejected the batch")}return s}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(t=>{this._logger.debug("Background span flush failed",t)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(tqt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var cqt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var zch=5e3,Qch=512,Mch=2048,Lch=128,_ch=128,Uch=128,Vch=8192,Gch=1e4,qch=36e5;function KSe(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var znu=["service.name","service.version","deployment.environment"];function Wch(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(znu.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of znu)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function Hch(e,t){if(!e)return[];let r=[e].flat().filter(i=>!!i),n=r.filter(i=>typeof i=="function");return n.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function eHo(e,t,r){let n=Pme({...t},Wch(e?.resourceAttributes)),i=KSe(e?.maxExportBatchSize,Qch);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:Hch(e?.beforeSpanSend,r),maxAttributesPerSpan:KSe(e?.maxAttributesPerSpan,Lch),maxEventsPerSpan:KSe(e?.maxEventsPerSpan,_ch),maxAttributesPerEvent:Uch,maxAttributeValueLength:KSe(e?.maxAttributeValueLength,Vch),flushIntervalMs:KSe(e?.flushIntervalMs,zch),maxExportBatchSize:i,maxQueueSize:Math.max(KSe(e?.maxQueueSize,Mch),i),maxLiveSpans:KSe(e?.maxLiveSpans,Gch),maxSpanAgeMs:KSe(e?.maxSpanAgeMs,qch)}}var tHo=require("fs"),Lnu=require("fs/promises"),nHo=require("path"),_nu=require("readline"),sen=new ST.ReduceableCache(25),lqt=new ST.ReduceableCache(20),iHo=7,Kch=1e3,Jch=1e4,rHo=10485760;async function Unu(e,t=Lnu.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||elh(l)||tlh(c)||!(0,nHo.isAbsolute)(l)&&i===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=Vnu(a,i);if(c===void 0||lqt.get(c))continue;let l=n[a];if(!l)continue;l.sort((d,f)=>d-f);let u=nlh(l);if(u.every(d=>rlh(c,d)))continue;let p=ilh(sen,c,{});s.push(Xch(a,u,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&Zch(e,sen,i),sen.reduce(),e}async function Ych(e,t,r){let n,i=!1;try{n=await t(e,tHo.constants.O_RDONLY|tHo.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>rHo?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${rHo}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function Xch(e,t,r,n,i,o){let s=await Ych(e,i,o);if(s===void 0)return void lqt.set(n,1);let a=s;return new Promise(c=>{let l=!1;function u(C){l||(l=!0,C?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:rHo-1})}catch{lqt.set(n,1),u();return}let d;try{d=(0,_nu.createInterface)({input:p})}catch{lqt.set(n,1),u(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void u(p);let A=g[0],b=g[1];function I(){lqt.set(n,1),d.close(),d.removeAllListeners(),u(p)}p.on("error",I),d.on("error",I),d.on("close",()=>u(p)),d.on("line",C=>{if(f++,!(f<A)&&(r[f]=olh(C,0),f>=b)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let x=t[m];if(x===void 0){d.close(),d.removeAllListeners();return}A=x[0],b=x[1]}})})}function Zch(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=Vnu(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;$ch(n.lineno,n,o)}}function $ch(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Gnu(e);i<e;i++){let o=r[i];if(o===void 0)return void Qnu(t);t.pre_context.push(o)}if(r[e]===void 0)return void Qnu(t);t.context_line=r[e];let n=qnu(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function Qnu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function elh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function tlh(e){return e.lineno!==void 0&&e.lineno>Jch||e.colno!==void 0&&e.colno>Kch}function Vnu(e,t){return(0,nHo.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function rlh(e,t){let r=sen.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function nlh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=Mnu(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+iHo:(i.push(n),n=Mnu(o)),t++}return i}function Mnu(e){return[Gnu(e),qnu(e)]}function Gnu(e){return Math.max(1,e-iHo)}function qnu(e){return e+iHo}function ilh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function olh(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}var Wlt=require("path");function Wnu(e=process.cwd()){let t=Wlt.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,Wlt.isAbsolute)(o.filename)&&(o.filename=r((0,Wlt.relative)(n,r(o.filename))));return i}}var Hnu="5.55.0";var Dme={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var JSe=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t,r={}){let n=this._flags[t];return this._recordAccess(t),n?.enabled??r.defaultValue??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(Dme.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Dme.QUOTA_LIMITED),r===void 0&&o.push(Dme.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};var slh=6e4;function Knu(e){return e==="client"||e==="server"?e:"all"}function alh(e,t){return e===t||e==="all"||t==="all"}var Hlt=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function clh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var are=class e extends Error{constructor(t){super(t),clh(this,e)}},aen=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}withEvaluationSnapshot(t){return t.definitions?t:{...t,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(l){l instanceof are||l instanceof Ul?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${t}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${l}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...t,definitions:void 0});return await Promise.all(s.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=l,u&&(i[c.key]=u)}catch(l){l instanceof are||l instanceof Ul?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),t=r.definitions.featureFlagsByKey[t.key]??t;let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=M7o(t.filters?.payloads,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new Ul("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let l=r.definitions.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Ul("Flag has unknown group type index");if(!(l in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let u=s[l];return await this.matchFeatureFlagProperties(t,i[l],u,r)}{let l=this.getBucketingValueForFlag(t,n,o);if(l===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new Ul(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,l,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!n.definitions.featureFlagsByKey)throw new Ul("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Ul(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Ul(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Ul(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let u=n.definitions.featureFlagsByKey[c];if(u)if(u.active)try{let p=await this.computeFlagValueLocally(u,n);i[c]=p}catch(p){throw new Ul(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))i[c]=!1;else throw new Ul(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Ul(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){i=this.withEvaluationSnapshot(i);let o=t.filters||{},s=await z7o(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,l=o.early_exit??!1,{groups:u,groupProperties:p}=i,d=!1,f;for(let m of a)try{let g=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,A=n,b=r;if(g!==c&&g!=null){let C=i.definitions.groupTypeMapping[String(g)];if(!C||!(C in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(C in p)){d=!0;continue}A=p[C],b=u[C]}let I=await this.isConditionMatch(t,b,m,A,i);if(I==="match"){let C=m.variant,x=o.multivariate?.variants||[];f=C&&x.some(S=>S.key===C)?C:await this.getMatchingVariant(t,b)||!0;break}if(l&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof are)throw g;if(g instanceof Ul)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new Ul("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){o=this.withEvaluationSnapshot(o);let s=o.definitions,a=n.rollout_percentage,c=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((n.properties||[]).length>0){for(let l of n.properties){let u=l.type,p=!1;if(u==="cohort"){let d=await Ynu(l,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=l.operator==="not_in"?!d:d}else p=u==="flag"?await this.evaluateFlagDependency(l,i,o):Jnu(l,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await Y9t(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return Q7o(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return W$r(t.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(t){if(!this.evaluationContexts||this.evaluationContexts.length===0)return t;let r=new Set(this.evaluationContexts);return t.filter(n=>{let i=n.evaluation_contexts??n.evaluation_tags;return!i||i.length===0?!0:i.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(t){let r=this.featureFlagsByKey[t];return r?Knu(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>alh(Knu(r.evaluation_runtime),t)).map(r=>r.key)}updateFlagState(t){let r=this.filterFlagsByEvaluationContexts(t.flags);this.featureFlags=r,this.featureFlagsByKey=r.reduce((i,o)=>(i[o.key]=o,i),{});let n=new Set(r.map(i=>i.key));this.filteredOutFlagKeys=new Set(t.flags.filter(i=>!n.has(i.key)).map(i=>i.key)),this.groupTypeMapping=t.group_type_mapping??t.groupTypeMapping??{},this.cohorts=t.cohorts,this.propertyMatchingVersion=t.property_matching_version??t.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((t.minimal_flag_called_events??t.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let t=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(slh,t*2**this.backOffCount):t}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Hlt(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Hlt(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Hlt(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,s={flags:n.flags??[],group_type_mapping:i,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:o};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(t){t instanceof Hlt&&this.onError?.(t)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=N2(()=>{o.abort()},this.timeout),r.signal=o.signal}let i=()=>clearTimeout(n);try{let o=this.fetch,s=await o(t,r);return s.status!==200?(i(),s):{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{i()}},json:async()=>{try{return await s.json()}finally{i()}}}}catch(o){throw i(),o}}async stopPoller(t=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await WSe(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function Jnu(e,t,r,n){return j7o(e,t,{warnFunction:r,propertyMatchingVersion:n})}function llh(e,t){if(!(e in t))throw new are(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Ynu(e,t,r,n=!1,i,o){let s=String(e.value);llh(s,r);let a=r[s];return Xnu(a,t,r,n,i,o)}async function Xnu(e,t,r,n=!1,i,o){if(!e)return!0;let s=e.type,a=e.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let l of a)try{let u=await Xnu(l,t,r,n,i,o);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof are)throw u;if(u instanceof Ul)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Ul("Can't match cohort without a given cohort property value");return s==="AND"}for(let l of a)try{let u;if(l.type==="cohort")u=await Ynu(l,t,r,n,i,o);else if(l.type==="flag"){if(!i)throw new Ul(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(l)}else u=Jnu(l,t,void 0,o);let p=l.negation||!1;if(s==="AND"){if(!u&&!p||u&&p)return!1}else if(u&&!p||!u&&p)return!0}catch(u){if(u instanceof are)throw u;if(u instanceof Ul)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Ul("can't match cohort without a given cohort property value");return s==="AND"}var ulh=["--unhandled-rejections","--unhandled_rejections"],plh=new Set(["throw","strict","warn","warn-with-error-code","none"]),flh=[...globalThis.process?.execArgv??[]],dlh=globalThis.process?.env?.NODE_OPTIONS;function mlh(e){let t=[],r="",n=!1;for(let i=0;i<e.length;i++){let o=e[i];o==="\\"&&n&&i+1<e.length?r+=e[++i]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(t.push(r),r="")}return r&&t.push(r),t}function Znu(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=ulh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);plh.has(o)&&(t=o)}return t}function hlh(e=flh,t=dlh){return Znu(e)??Znu(mlh(t??""))??"throw"}var $nu=hlh();function eiu(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function glh(e,t){let r=!1;return Object.assign((n,i)=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length;eiu(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function tiu(e,t,r=$nu){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>eiu(e,i,o));n.on("uncaughtException",glh(e,t))}}function riu(e,t=$nu){let r=globalThis.process;!r||t==="throw"||t==="strict"||t==="warn-with-error-code"||r.on("unhandledRejection",n=>{e(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var Alh=2e3,oHo=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new w$r({...dru(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return F9t(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i,o){let s={...o},a=t.buildFromUnknown(r,n);a.$exception_list=await t.modifyFrames(a.$exception_list);let c=ST.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(tiu(this.onException.bind(this),this.onFatalError.bind(this)),riu(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Alh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},jUe=oHo;var cen=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function ylh(e){return e==="v0"||e==="v1"}function niu(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return ylh(e)?e:"v0"}var blh="$ai_",uqt="analytics";function iiu(e){return typeof e.event=="string"&&e.event.startsWith(blh)}var Klt=class e extends Error{constructor({requestId:t,drops:r,retryExhausted:n,cause:i}){super(e.buildMessage(t,r,n,i)),this.name="CaptureV1Error",this.requestId=t,this.drops=r,this.retryExhausted=n,this.cause=i}static buildMessage(t,r,n,i){let o=`Capture V1 batch ${t} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function sHo(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Elh(e){return typeof e=="string"?e:void 0}var Ilh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:sHo},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:sHo},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:sHo},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Elh}],vlh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function Clh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xlh(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function oiu(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function Slh(e){let r={...Clh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of Ilh)if(o in r){let c=a(r[o]);c!==void 0&&(n[s]=c),delete r[o]}let i={};for(let{property:o,field:s}of vlh)if(o in r){let a=r[o];typeof a=="string"&&(i[s]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,oiu(r,"$set",e.$set),oiu(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:xlh(e.timestamp),...i,options:n,properties:r}}function siu(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(Slh)};return r&&(n.historical_migration=!0),n}var wlh="/i/v1/analytics/events",Tlh=3e4,Olh=new Set([408,500,502,503,504]),len=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??Tlh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>N2(i,n))),this.generateRequestId=r.generateRequestId??F2,this.compress=r.compress??H9t}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=siu(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${wlh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,p=GSe({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,l,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!u&&Olh.has(A)){let b=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(l,b)}else{let b=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,b)}else{let b;try{b=await d.waitFor(this.parseResponse(m))}catch(x){if(g.aborted)throw x;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,b,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(u)return void this.onError(new Klt({requestId:r,drops:s,retryExhausted:I.map(x=>x.uuid)}));a=I;let C=this.parseRetryAfter(m);f=this.backoffDelay(l,C)}}catch(m){if(d&&!d.signal.aborted)throw m;if(u)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(l)}finally{d?.cleanup()}f!==void 0&&await this.sleep(f)}}async sendOnce(t,r,n,i){let o=this.buildHeaders(n,i),s=r;if(this.config.compressionEnabled){let p=await this.compress(r,this.config.isDebug);p!==null&&(s=p,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((p,d)=>{l=N2(()=>{let f=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);f.name="AbortError",d(f),a.abort(f)},this.config.requestTimeoutMs)});try{let p=this.fetchFn(t,{method:"POST",headers:o,body:s,signal:a.signal}),d=!1;p.then(b=>{a.signal.aborted&&!d&&this.cancelBody(b)}).catch(()=>{});let f=await Promise.race([p,u]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:b=>Promise.race([b,u]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(l),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(l),p}}buildHeaders(t,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(t),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(t,r,n){let i=r.results??{},o=[];for(let s of t){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(t,r){let n=Math.min(this.config.initialRetryDelayMs*2**(t-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(t){let r=t.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(t){let r=await t.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(t,r,n){let i="";try{i=(await n(t.text())).slice(0,512)}catch{}let o=i?`: ${i}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(t,r,n,i){this.onError(new Klt({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new Klt({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var zUe="ai-capture",uen="/i/v0/ai/batch/";var Blh=new TextEncoder;function cHo(e){return Blh.encode(GSe(e)).length}function aiu(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=cHo(a);if(c>t){i.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&s+c>r&&(n.push(o),o=[],s=0),o.push(a),s+=c}return o.length>0&&n.push(o),{batches:n,dropped:i}}var Dlh=100,ciu=3e4,Rlh=5e4,klh=50,Flh=500,Nlh="https://us.i.posthog.com",liu=new Set;function fen(e,t){liu.has(e)||(liu.add(e),console.warn(`[PostHog] ${t}`))}function jlh(e){return typeof e=="string"?e.trim():""}function zlh(e){return(typeof e=="string"?e.trim():"")||void 0}function Qlh(e){return(typeof e=="string"?e.trim():"")||Nlh}function Mlh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function Llh(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var den=class extends K9t{constructor(t,r={}){let n=jlh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:Qlh(r.host),personalApiKey:zlh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new cen,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=niu(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,Dlh):i.featureFlagsPollingInterval===null?null:ciu,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new aen({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new jUe(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||Rlh}enqueue(t,r,n,i){super.enqueue(t,r,n,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(t=!1){let r=this.flushWithPendingPromises();return!this._traces||t&&this._traces.throttled?r:z9t([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(t){let r=this._flushEventsAndSpans(t),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??Flh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??klh;this._waitUntilCycle.timer=N2(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getQueueRouteKey(t){return this.captureMode==="v1"&&iiu(t)?"ai":uqt}persistedQueueKeyForRoute(t){return t===zUe?jQ.AiCaptureQueue:t==="ai"?jQ.AiQueue:jQ.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[uqt,"ai"]:[uqt];return this._aiCaptureRouteActive&&t.push(zUe),t}getBatchEndpointPath(t){return t===zUe?uen:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=uqt){if(n===zUe)return this.sendAiCaptureBatch(t,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(t,r,n);let i=t.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(t,r){let{batches:n,dropped:i}=aiu(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${uen}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(t,r){try{await super.sendBatch(t,r,zUe)}catch(n){if(!Vlt(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${cHo(o)} bytes) was rejected with 413 by ${uen} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let i=Math.ceil(t.length/2);await this.sendAiSubBatch(t.slice(0,i),r),await this.sendAiSubBatch(t.slice(i),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new len({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(t,r)=>this.fetch(t,r),onError:t=>this._events.emit("error",t),compress:t=>this.compressPayload(t)})),this._v1Sender}getLibraryVersion(){return Hnu}get metrics(){return this._metrics||(this._metrics=new nqt(this,K$r(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new cqt}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new aqt(this,eHo(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let t=this.context?.get();return{distinctId:t?.distinctId,sessionId:t?.sessionId}}startSpan(t,r){return this._tracesPipeline?.startSpan(t,r)??HSe(r,this._spanContextManager.active())}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this._tracesPipeline;return s?i?s.withSpan(t,i,o):s.withSpan(t,o):sqt(this._spanContextManager,HSe(i,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let t=super.getCommonEventProperties();return(this.options.isServer??!0)&&(t.$is_server=!0),t}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}_warnIfInvalidCapture(t,r,n){typeof t=="string"&&this._logger.warn(r),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(t,r,n,i,o){return this.addPendingPromise(this._prepareEventMessage(r,i).then(({distinctId:s,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,u,o):this.enqueue(t,p,u,o)}).catch(s=>{s&&console.error(s)}))}_capturePreparedEvent(t,r){return this._sendPreparedEvent("capture",t,r)}capture(t){this._warnIfInvalidCapture(t,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(t,!1)}async captureImmediate(t){return this._warnIfInvalidCapture(t,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(t,!0)}captureAi(t){if(this.disabled)return;let r=RUe(t.uuid,F2);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=RUe(t.uuid,F2);return await this._sendPreparedAiEvent({...t,uuid:r},!0),r}_sendPreparedAiEvent(t,r){return typeof t?.event=="string"&&!t.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${t.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",t,r,void 0,zUe)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:t,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(r).length>0&&(i.$set=r),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:t,event:"$set",properties:i})}unsetPersonProperties({distinctId:t,properties:r}){let n=Mlh(r);n.length!==0&&this.capture({distinctId:t,event:"$set",properties:{$unset:n}})}alias(t){this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(t){await this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(t){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(t)}getFeatureFlagKeysByEvaluationRuntime(t){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(t)??[]}async waitForLocalEvaluationReady(t=ciu){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let D=this._flagOverrides[t];if(D===void 0)return;let R=this._payloadOverrides?.[t];return{key:t,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:R}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,p=this.addLocalPersonAndGroupProperties(r,s,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,b,I,C,x,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let D=this.featureFlagsPoller?.featureFlagsByKey[t];if(D)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(D,d,{matchValue:i});if(R){m=!0;let O=R.value;I=D.id,x="Evaluated locally",S=D.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:R.payload??void 0,reason:x,reasonCode:D.active===!1?"flag_disabled":void 0}}}catch(R){if(R instanceof are||R instanceof Ul)this._logger?.info(`${R.name} when computing flag locally: ${t}: ${R.message}`);else throw R}}if(!m&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,a,[t]);if(D===void 0)b=Dme.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt;let R=[];D.errorsWhileComputingFlags&&R.push(Dme.ERRORS_WHILE_COMPUTING),D.quotaLimited?.includes("feature_flags")&&R.push(Dme.QUOTA_LIMITED);let O=D.flags[t];if(O===void 0)R.push(Dme.FLAG_MISSING);else{I=O.metadata?.id,C=O.metadata?.version,x=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:z,reason:x,reasonCode:O.reason?.code}}R.length>0&&(b=R.join(","))}}if(o){let D=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,R={$feature_flag:t,$feature_flag_response:D,$feature_flag_id:I,$feature_flag_version:C,$feature_flag_reason:x,locally_evaluated:m,[`$feature/${t}`]:D,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(R.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(R.$feature_flag_definitions_loaded_at=O)}b&&(R.$feature_flag_error=b),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:D,groups:s,disableGeoip:a,properties:R})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){fen("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(fen("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){fen("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let b=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,l,u,s,a);m={...m,...b.flags||{}},g={...g,...b.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new JSe({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new JSe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new JSe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,b=!1,I=!1,C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),x=new Set;if(C)for(let[D,R]of Object.entries(C.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:C.payloads[D],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},x.add(D)}let S=f!==void 0&&Array.from(f).some(D=>this.featureFlagsPoller?.featureFlagsByKey[D]===void 0);if((C?C.fallbackToFlags||S:!0)&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,s,a);if(D){this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt,b=!!D.errorsWhileComputingFlags,I=Array.isArray(D.quotaLimited)&&D.quotaLimited.includes("feature_flags");for(let[R,O]of Object.entries(D.flags)){if(x.has(R))continue;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}m[R]={key:R,enabled:O.enabled,variant:O.variant,payload:z,id:O.metadata?.id,version:O.metadata?.version,reason:O.reason?.description??O.reason?.code,locallyEvaluated:!1,hasExperiment:O.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[D,R]of Object.entries(this._flagOverrides)){if(R===void 0){delete m[D];continue}let O=m[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:O?.payload,id:O?.id,version:O?.version,reason:O?.reason,locallyEvaluated:O?.locallyEvaluated??!1,hasExperiment:O?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[D,R]of Object.entries(this._payloadOverrides)){let O=m[D];O&&(m[D]={...O,payload:R})}if(f!==void 0)for(let D of Object.keys(m))f.has(D)||delete m[D];return new JSe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:b,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(t,r){return t==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([u],[p])=>u<p?-1:u>p?1:0))}`:"",l=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(l):this.distinctIdHasSentFlagCalls[r]=new Set([l]),this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){let r=Date.now()+(t??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),this._metrics&&(await WSe(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await WSe(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(t){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=N2(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(uru(s)&&r&&o in r){let a={};for(let[c,l]of Object.entries(s))a[String(c)]=String(l);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(t,r){return{distinct_id:t,...r||{}}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!jUe.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(jUe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:s},r,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(t,r,n,i){if(!jUe.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(jUe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){return this._prepareEventMessage(t)}async _prepareEventMessage(t,r={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p}=t,d=this.context?.get(),f=r.includeContextProperties??!0,m=n||d?.distinctId,g=f?{...this.props,...d?.properties||{},...o||{}}:{...o||{}};m||(m=F2(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?q9t(g):g,b=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p});if(!b)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){fen("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let C=typeof c=="object"?c:void 0,x=await this.getFeatureFlagsForEvent(b.distinctId,s,u,C);return Llh(x)}return{}}).catch(()=>({})).then(C=>{let x=b.groups||s;return{...C,...b.properties||{},...x!==void 0&&Object.keys(x).length>0?{$groups:x}:{}}});return b.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&fru(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(b.event="$bot_pageview",I.$browser_type="bot"),{distinctId:b.distinctId,event:b.event,properties:I,options:{timestamp:b.timestamp,disableGeoip:b.disableGeoip,uuid:b.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n)try{if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}catch(s){return this._logger.error(`Error in before_send function for event '${t.event}':`,s),null}return i}};var uiu=require("async_hooks"),men=class{constructor(){this.storage=new uiu.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var piu=require("async_hooks"),hen=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new piu.AsyncLocalStorage}};var fiu=require("zlib"),diu=require("util"),_lh=(0,diu.promisify)(fiu.gzip);async function miu(e,t=!0){try{let r=await _lh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var gen=require("os");function hiu(){let e,t;try{e=(0,gen.platform)(),t=(0,gen.release)()}catch{}return V7o(e,t)}var giu="posthog-node";function Ulh(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[lHo.POSTHOG_ID_TAG];if(c===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,l).toString();s.tags["PostHog Person URL"]=u;let p=s.exception?.values||[],d=p.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(A=>({...A,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags},m=ST.getInjectedReleaseId();return m&&(f.$release_id=m),t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var lHo=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=giu,this.name=giu,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Ulh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var cre=class extends den{getLibraryId(){return"posthog-node"}compressPayload(t){return miu(t,this.isDebug)}initializeContext(){return new men}initializeSpanContextManager(){return new hen}hostResourceAttributes(){return hiu()}createErrorPropertiesBuilder(){return new ST.ErrorPropertiesBuilder([new ST.EventCoercer,new ST.ErrorCoercer,new ST.ObjectCoercer,new ST.StringCoercer,new ST.PrimitiveCoercer],ST.createStackParser("node:javascript",ST.nodeStackLineParser),[oru(),t=>Unu(t,void 0,this._logger),Wnu()])}};function Aiu(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var Aen=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},Vlh="feature_flag_evaluated",Glh=3e3,qlh=3e3,yen=class{evaluator;environment;sendFeatureFlagEvents;pending=new Map;resolved=new Map;constructor({environment:t,sendFeatureFlagEvents:r,posthogApiKey:n,evaluator:i}){this.environment=t,this.sendFeatureFlagEvents=r,this.evaluator=i??new cre(n??"",{featureFlagsRequestTimeoutMs:Glh,isServer:!1})}isEnabled(t,r){let n=yiu(t,r),i=this.pending.get(n);if(i!=null)return i;let o=this.evaluateAndRemember(t,r,n);return this.pending.set(n,o),o}async evaluateAndRemember(t,r,n){let i=await this.evaluate(t,r);return this.resolved.set(n,i),i}getCachedValue(t,r){return this.resolved.get(yiu(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,qlh),t.unref()})])}catch{}finally{clearTimeout(t)}}async flushAfterPendingEvaluations(){await Promise.allSettled(this.pending.values()),await this.evaluator.flush()}async evaluate(t,r){let{org:n}=r,i=Hlh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,uHo(n),{personProperties:i,groups:{organization:n},groupProperties:{organization:i},sendFeatureFlagEvents:!1})}catch{return!1}return this.sendFeatureFlagEvents&&this.captureFlagUsage({flag:t,org:n,result:o,properties:i}),Aiu(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=Wlh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.217.0"};this.tryCapture({distinctId:uHo(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:uHo(r),event:Vlh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:Aiu(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function Wlh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function uHo(e){return`org:${e}`}function Hlh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function yiu(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var ben;function Een(){return ben==null&&(ben=Klh()),ben}async function pHo(){await ben?.flush()}function Klh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new Aen:new yen({posthogApiKey:e,environment:UK(),sendFeatureFlagEvents:v$r()})}var Ien=class{posthog;constructor({posthogApiKey:t}){this.posthog=new cre(t,{isServer:!1})}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.217.0",usingAccessToken:!0,cliReleaseEnvironment:UK(),...Wpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:UK()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var pqt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};nf();rr();var Jlt=require("fs/promises"),biu=require("os"),Eiu=require("path");F4e();var Jlh="id",Ylh=".fern",fqt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new cre(r,{isServer:!1}),this.userId=t==null?void 0:j7i(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"5.217.0",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:UK(),agent:Olr(),...r!=null?{userEmail:r}:{},...Wpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:UK()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Pl({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ew(),r=ke(Xt.of((0,biu.homedir)()),Ee.of(Ylh),Ee.of(Jlh));try{await Gt(r)?this.persistedDistinctId=(await(0,Jlt.readFile)(r)).toString():(await(0,Jlt.mkdir)((0,Eiu.dirname)(r),{recursive:!0}),await(0,Jlt.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var fHo;async function dqt(){return fHo==null&&(fHo=await Xlh()),fHo}async function Xlh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!v$r())return new pqt;let t=await cXe();return t!=null?new fqt({token:t,posthogApiKey:e}):await Az()!=null?new Ien({posthogApiKey:e}):new fqt({token:void 0,posthogApiKey:e})}catch{return new pqt}}ln();gt();Pt();vQ();var mqt=Ae(require("process"),1);gHe();var Ciu=Ae(HJi(),1),xiu=Ae(viu(),1);function wT(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=XW(e),e.length===0))return 0;e=e.replace((0,xiu.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(Ciu.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}ln();function ven(e){let t=0;for(let r of e.split(`
3482
+ at ${r.filename}:${n}:${i}`}};var Cah=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,L9t=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(Cah);return i&&(r=i[1],n=i[2]),[r,n]}};var Kru=["fatal","error","warning","log","info","debug"];function M$r(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var _9t=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:this.getStack(t)??r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(Qlt(t))return t.constructor.name;let r="name"in t?t.name:void 0;return pR(r)&&!s7o(r)?r:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=M$r(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return pR(t)&&!s7o(t)&&Kru.indexOf(t)>=0}getStack(t){try{return pR(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:pR(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(qSe(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var x7o=class{match(t){return Qlt(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${M$r(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var U9t=class{match(t){return x$r(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var S7o=class{match(t){return BUe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Qlt(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return x$r(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var w7o=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var V9t={MESSAGE:"$message",TIMESTAMP:"$timestamp"},xah=new Set([V9t.MESSAGE,V9t.TIMESTAMP]),L$r={enabled:!0,max_bytes:32768};function T7o(e){return e?{enabled:e.enabled??L$r.enabled,max_bytes:wah(e.max_bytes,L$r.max_bytes)}:{...L$r}}function Sah(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>xah.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var O7o=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=T7o(t)}setConfig(t){this._config=T7o(t),this._trimToMaxBytes()}add(t){let r=Tah(t);if(!r)return;let n=Jru(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function wah(e,t){if(!zlt(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function Tah(e){let t;try{t=GSe(e)}catch{return}try{let r=JSON.parse(t);if(!F9t(r))return;let n=r,i=n[V9t.MESSAGE],o=n[V9t.TIMESTAMP];return!pR(i)||i.trim().length===0||!pR(o)&&!zlt(o)?void 0:{step:n,json:t}}catch{return}}function Jru(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}function Oah(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var P7o=e=>{if("flags"in e){let t=Yru(e.flags),r=Xru(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,Ult(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Pah(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function Pah(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var Yru=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,G9t(r)]).filter(([,t])=>t!==void 0)),Xru=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?Ult(n):void 0]}))},G9t=e=>e===void 0?void 0:e.variant??e.enabled,Ult=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Zru=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],Bah=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...Zru,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],q9t=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return Bah.forEach(n),t.forEach(n),r};var _$r=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}};function B7o(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var Rah="NativeGzipValidationError",kah=31,Fah=139,Nah=8,jah=e=>e.length>=2&&e[0]===kah&&e[1]===Fah;var W9t,zah=()=>{if(W9t)return W9t;W9t=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;W9t[e]=t>>>0}return W9t},Qah=e=>{let t=zah(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},U$r=e=>{throw _lt(Rah,`Native gzip produced invalid output: ${e}`)},Mah=async(e,t)=>{e.size<18&&U$r("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!jah(r)||r[2]!==Nah)&&U$r("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==Qah(t)&&U$r("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&U$r("invalid-size")};async function H9t(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async l=>{try{await o.abort(l)}catch{}throw l}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await Mah(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var $5=class extends Error{constructor(t,r,n,i){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return h7o(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let t=_lt("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=N2(()=>{this._bodyReadTimedOut=!0;let o=_lt("AbortError","Response body read timed out");i(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(t=>JSON.parse(t))}cancelResponseBody(t){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(t),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},Bme=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var nnu=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function $ru(e){if(e instanceof $5){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function Lah(e){return typeof e=="object"&&(e instanceof $5||inu(e))}function inu(e){return e instanceof Bme}function _ah(e){if(e instanceof $5)return e.status===502||e.status===504;if(!(e instanceof Bme))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var enu=10485760;function tnu(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,Dru):new TextEncoder().encode(e).length}catch{return 0}}function Vlt(e){return typeof e=="object"&&e instanceof $5&&e.status===413}function V$r(e){return e instanceof $5?e.status===408||e.status===429||e.status>=500:inu(e)}function rnu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var D7o="default",K9t=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Q9t([new M9t,new _9t,new L9t,new U9t],I7o())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new P$r,this._events=new _$r,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=gru("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Rru(i||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:V$r},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!B7o()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(jQ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(jQ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(jQ.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){let r=t.properties||{},n={...r,...this.getCommonEventProperties()};return nnu(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=q9t(n)),{distinct_id:t.distinct_id,event:t.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(t,r,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{type:"required",consume:i=>i.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,l={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:_ah},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:P7o(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof $5)return{type:"api_error",statusCode:t.status};if(t instanceof Bme){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(t,r,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let c=G9t(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,i,o,s,[t]);return a===void 0?void 0:{response:a.flags[t],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,i,o,s,[t]);if(!a)return;let c=a[t];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let l=c.response;return l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r,{type:"required",consume:o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);return this._logger.error(a),this._events.emit("error",new Error(s)),Promise.resolve(void 0)}return o.json()}}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(jQ.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(jQ.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(jQ.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return D7o}persistedQueueKeyForRoute(t){return jQ.Queue}getActiveQueueRoutes(){return[D7o]}getRouteQueue(t){return this.getPersistedProperty(this.persistedQueueKeyForRoute(t))||[]}enqueue(t,r,n,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let s=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(o)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(s,a),this._events.emit(t,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=N2(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,i??this.getQueueRouteKey(o))}catch(s){this._events.emit("error",s)}}}normalizeMessage(t){let{type:r,library:n,library_version:i,...o}=t,s=rnu(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=RUe(o.uuid,F2),o}normalizeTimestampForWire(t){let r=t instanceof Date?t:typeof t=="string"?new Date(t):null;if(!r||Number.isNaN(r.getTime()))return t;let n=r.toISOString(),i=typeof t=="string"?t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}prepareMessage(t,r){let n={...t,timestamp:r?.timestamp?r?.timestamp:g7o(),uuid:RUe(r?.uuid,F2)};return(r?.disableGeoip??this.disableGeoip)&&(rnu(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async t=>{await $ru(t)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(t,r=[]){let n=r.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],t);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(t){if(this.disabled)return Promise.resolve();if(!t&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(t)return this.waitForPendingPromises(n,[r,i])}).then(()=>z9t([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),z9t([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}compressPayload(t){return H9t(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=D7o){let i={api_key:this.apiKey,batch:t.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:g7o()};this.historicalMigration&&(i.historical_migration=!0);let o=GSe(i),s=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(s,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(i=>this.getRouteQueue(i).length>0))return;let r=[],n;for(let i of t)try{await this._flushRoute(i,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(t,r){let n=this.persistedQueueKeyForRoute(t),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),c=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),l=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(b=>b===m||typeof g=="string"&&g.length>0&&b.message?.uuid===g);return A===-1?!0:(d.splice(A,1),!1)});this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:p=>Vlt(p)?!1:V$r(p)};try{await this.sendBatch(c,u,t)}catch(p){if(Vlt(p)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof Bme||await l(),this._events.emit("error",p),p}await l(),r.push(...c),s+=c.length}}async _sendOtlpBatch({path:t,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let i;try{i=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let o=tnu(i);if(o>enu)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${enu}`)),{kind:"too-large",measuredLocally:!0};let s=r==="bearer"?`${this.host}/i/v1/${t}`:`${this.host}/i/v1/${t}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),c=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(s,l,{type:"successful-write"},{retryCheck:u=>Vlt(u)||u instanceof $5&&u.retryAfterMs!==void 0?!1:V$r(u)}),{kind:"ok"}}catch(u){if(Vlt(u))return{kind:"too-large"};if(V$r(u)){let p=u instanceof $5?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:u}}}async _sendLogsBatch(t){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:t})}async _sendMetricsBatch(t){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:t})}async _sendTracesBatch(t){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:t})}async fetchWithRetry(t,r,n,i,o){let s=r.body?r.body:"",a=tnu(s),c={...this._retryOptions,...i},l=0;return await kru(async()=>{l++;let u=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((C,x)=>{f=N2(()=>{let S=_lt("AbortError",`Request timed out after ${p}ms`);x(S),u.abort(S)},p)}),g,A=!1,b,I=()=>b??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let C;try{C=this.fetch(t,{signal:u.signal,...r})}catch(B){throw new Bme(B)}C.then(B=>{u.signal.aborted&&!A&&Promise.resolve(B.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([C,m]),A=!0}catch(B){throw new Bme(B)}let x=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!x&&(g.status<200||g.status>=S))throw new $5(g,a,d,u);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(B){throw u.signal.aborted?new Bme(B):B}}finally{clearTimeout(f),u.signal.aborted&&g&&I()}},{...c,retryCheck:u=>{let p=c.retryCheck(u);return p&&l<=c.retryCount&&u instanceof $5&&u.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:WSe((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(s=>this.getRouteQueue(s).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!Lah(i))throw i;await $ru(i)}})(),t,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:t}),r=!0})}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var Wah=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var lYv=new RegExp(Wah.source,"i"),onu=/[a-z][a-z0-9+.-]{0,63}:\/\//i,uYv=new RegExp(`^${onu.source}`,"i"),pYv=new RegExp(onu.source,"gi");var Hah=["is_not","is_set"],Kah=1152921504606847e3,Ul=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function R7o(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!R7o(t in e?e[t]:null))return!1;return!0}function k7o(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!k7o(t in e?e[t]:null))return!1;return!0}function J9t(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Ul("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new Ul("Cannot stringify an unpaired surrogate like the flags service")}}function q$r(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void J9t(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Ul(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new Ul("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&q$r(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Ul("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new Ul("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))J9t(n),q$r(e[n],t)}finally{t.delete(e)}return}throw new Ul(`Cannot represent ${typeof e} like the flags service`)}}function Jah(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let i=e.charCodeAt(r),o=t.charCodeAt(n),s=i>=55296&&i<=56319,a=o>=55296&&o<=56319,c=s?e.charCodeAt(r+1):0,l=a?t.charCodeAt(n+1):0,u=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+l-56320+65536:o;if(u!==p)return u-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function F7o(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return J9t(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new Ul(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new Ul(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new Ul("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let n=0;n<e.length;n++)r.push(n in e?F7o(e[n],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Ul("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new Ul("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(J9t),`{${n.sort(Jah).map(i=>`${JSON.stringify(i)}:${F7o(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new Ul(`Cannot stringify ${typeof e} like the flags service`)}function G$r(e){return typeof e=="string"?(J9t(e),e):F7o(e)}function snu(e){try{return new RegExp(e),!0}catch{return!1}}function e8(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function cnu(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new Ul(`Invalid semver: ${t}`);return parseInt(e,10)}function Cw(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new Ul(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:cnu(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function t8(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function Yah(e,t){let r=Cw(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Xah(e,t){let[r,n,i]=Cw(e,t),o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function Zah(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new Ul(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return cnu(c,e,t)}catch{}throw new Ul(`Invalid wildcard semver: ${e}`)},s=o(i[0]);if(i.length===1)return{lower:[s,0,0],upper:[s+1,0,0]};let a=o(i[1]);return{lower:[s,a,0],upper:[s,a+1,0]}}function anu(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Ul(`${e} is in an invalid date format`)}throw new Ul(`The date provided ${e} must be a string, number, or date object`)}function N7o(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r||!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o==="h")n.setUTCHours(n.getUTCHours()-i);else if(o==="d")n.setUTCDate(n.getUTCDate()-i);else if(o==="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o==="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}function j7o(e,t,r={}){let n=e.key,i=e.value,o=e.operator||"exact",s=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new Ul(`Property ${n} not found in propertyValues`);let c=t[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!Hah.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let l=(p,d)=>{if(r.propertyMatchingVersion!==2&&R7o(p)||Array.isArray(p)&&p.length===0)return q$r(d),k7o(p)===k7o(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&R7o(p))return q$r(d),!1;if(Array.isArray(p)){let f=G$r(d).toLowerCase();return p.some(m=>G$r(m).toLowerCase()===f)}return G$r(p).toLowerCase()===G$r(d).toLowerCase()},u=(p,d,f)=>{if(f==="gt")return p>d;if(f==="gte")return p>=d;if(f==="lt")return p<d;if(f==="lte")return p<=d;throw new Error(`Invalid operator: ${f}`)};switch(o){case"exact":return l(i,c);case"is_not":return!l(i,c);case"is_set":return!0;case"icontains":return e8(c).includes(e8(i));case"not_icontains":return!e8(c).includes(e8(i));case"starts_with":return e8(c).startsWith(e8(i));case"not_starts_with":return!e8(c).startsWith(e8(i));case"ends_with":return e8(c).endsWith(e8(i));case"not_ends_with":return!e8(c).endsWith(e8(i));case"regex":return snu(String(i))&&String(c).match(String(i))!==null;case"not_regex":return snu(String(i))&&String(c).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let p=typeof i=="number"?i:parseFloat(String(i)),d=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(p)&&Number.isFinite(d)?u(d,p,o):u(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Ul("Date operations cannot be performed on boolean values");let p=N7o(String(i));p==null&&(p=anu(i));let d=anu(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return t8(Cw(String(c),s),Cw(String(i),s))===0;case"semver_neq":return t8(Cw(String(c),s),Cw(String(i),s))!==0;case"semver_gt":return t8(Cw(String(c),s),Cw(String(i),s))>0;case"semver_gte":return t8(Cw(String(c),s),Cw(String(i),s))>=0;case"semver_lt":return t8(Cw(String(c),s),Cw(String(i),s))<0;case"semver_lte":return t8(Cw(String(c),s),Cw(String(i),s))<=0;case"semver_tilde":{let p=Cw(String(c),s),{lower:d,upper:f}=Yah(String(i),s);return t8(p,d)>=0&&t8(p,f)<0}case"semver_caret":{let p=Cw(String(c),s),{lower:d,upper:f}=Xah(String(i),s);return t8(p,d)>=0&&t8(p,f)<0}case"semver_wildcard":{let p=Cw(String(c),s),{lower:d,upper:f}=Zah(String(i),s);return t8(p,d)>=0&&t8(p,f)<0}default:throw new Ul(`Unknown operator: ${o}`)}}async function lnu(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function Y9t(e,t,r="",n="."){let i=await lnu(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/Kah}async function z7o(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await Y9t("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function W$r(e){let t=[],r=0;for(let n of e){let i=r+n.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:n.key}),r=i}return t}async function Q7o(e,t,r){let n=await Y9t(e,t,"variant");return W$r(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function M7o(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,n=e[r]||null;return n==null?null:Ult(n)}var unu=9223372036854776e3,$ah="9223372036854775808",ech=Object.prototype.propertyIsEnumerable;function tch(){return{ancestors:new WeakSet,remainingNodes:1e4}}function sre(e,t){try{return pnu(e,t,tch(),0)}catch{return[]}}function rch(e,t){let r=e.toString(),n=BigInt($ah);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function U7o(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:N$r};if(r.remainingNodes--,cru(e))return{boolValue:e};if(typeof e=="bigint")return rch(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();return e>=unu||e<-unu?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:ire(e)};if(typeof e=="function")return{stringValue:Bru};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:F$r};if(n>=20)return{stringValue:N$r};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?ire(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return U7o(i.call(e),t,r,n+1)}catch{}return e_(e)?{arrayValue:{values:nch(e,t,r,n+1)}}:{kvlistValue:{values:pnu(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:ire(String(e))}}function nch(e,t,r,n){let i=[],o=Math.min(e.length,1e3),s=0;for(;s<o&&r.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(VK(a))continue;i.push(U7o(a,t,r,n))}catch{i.push({stringValue:Z5})}return e.length>s&&i.push({stringValue:N$r}),i}function pnu(e,t,r,n){let i=[];for(let o in e)if(ech.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if(a7o(s)||Ome(s))continue;i.push({key:ire(o),value:U7o(s,t,r,n)})}catch{i.push({key:ire(o),value:{stringValue:Z5}})}}return i}function Z9t(e,t,r){return{...Pme({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var ich=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function $9t(e,t){let r=Pme({},e),n={};for(let i of ich)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...sre(r,t),...sre(n,t)]}var fnu={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function och(e){if(e)return Object.prototype.hasOwnProperty.call(fnu,e)?fnu[e]:e}function V7o(e,t){let r=och(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var sch={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},TYv=sch.info;var kUe=class{constructor(t){this._onFire=t,this._firesAt=0}get pending(){return!!this._timer}arm(t){this.clear(),this._firesAt=Date.now()+t,this._timer=N2(()=>{this._timer=void 0,this._onFire()},t)}armNoEarlierThan(t){this._timer&&Date.now()+t<=this._firesAt||this.arm(t)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function eqt(){return 1-.25+Math.random()*.25*2}var r8=1;function tqt(e,t,r,n){let i=Math.min(Math.max(0,t-1),6),o=e*2**i,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*r)}var rqt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function G7o(e){return String(e)+"000000"}function q7o(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}function dnu(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function W7o(e,t,r){return Z9t(e,t,r)}function H7o(e,t,r,n){return{resourceMetrics:[{resource:{attributes:$9t(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function K$r(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}}var mnu=1,nqt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new kUe(()=>this.flush().catch(i=>{this._logger.error("Metrics flush failed:",i)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new DUe,this._consecutiveFlushFailures=0,this._flushJitter=r8,this._generation=0}count(t,r=1,n){this._capture({name:t,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(t,r,n){this._capture({name:t,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(t,r,n){this._capture({name:t,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let t=this._flushPromise,n=(async()=>{t&&await t.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let t=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(t)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=r8,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(t){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(t);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=r.attributes?{...r.attributes}:void 0,i=q7o(r.type,r.name,r.unit,n)}catch(a){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(r.name);s===void 0?this._typeByName.set(r.name,r.type):s!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${s}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(t,r){switch(t.type){case"count":t.total=(t.total??0)+r;break;case"gauge":t.last=r;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(rqt.length+1).fill(0)});let n=t.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[dnu(r,rqt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=e_(r)?r:[r],i=t;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(tqt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let t=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(t));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=eqt()):(this._consecutiveFlushFailures=0,this._flushJitter=r8),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(t),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(t){return H7o(this._buildMetrics(t),W7o(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=G7o(Date.now()),n=new Map;for(let i of t.values()){let o=q7o(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:mnu,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:mnu,dataPoints:[]},n.set(o,s));let a=sre(i.attributes??{},this._logger),c=G7o(i.windowStartMs);if(i.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(l)}else if(i.type==="gauge"){let l={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(l)}else if(i.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:rqt};s.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(t){for(let[r,n]of t){let i=this._series.get(r);if(!i){this._admitNewSeries()&&this._series.set(r,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var uch="0".repeat(32),pch="0".repeat(16),fch=/^[0-9a-f]+$/;function dch(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());return t}function mch(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function hnu(e){let t=mch(dch(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function gnu(){return hnu(16)}function Anu(){return hnu(8)}function ynu(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&fch.test(e)}function bnu(e){return ynu(e,32,uch)}function Enu(e){return ynu(e,16,pch)}var hch=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Inu(e){let t=vnu(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:gch(t.flags)}}function gch(e){return 1&parseInt(e,16)?Y$r:Ach}function vnu(e){if(typeof e!="string")return;let t=hch.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!bnu(n)||!Enu(i)))return{version:r,traceId:n,spanId:i,flags:o}}function Cnu(e){return vnu(e)&&e.trim()}function J$r(e){return Array.isArray(e)&&e.length===1?e[0]:e}var Y$r="01",Ach="00";function xnu(e,t,r=Y$r){return`00-${e}-${t}-${r}`}var ych=32,K7o=512;function X$r(e){if(typeof e!="string")return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>ych)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=K7o?t:Ech(r)}}var bch=128;function Ech(e){let t=[...e],r=()=>t.reduce((n,i)=>n+i.length,0)+t.length-1;for(let n=t.length-1;n>=0&&r()>K7o;n--)t[n].length>bch&&t.splice(n,1);for(;t.length&&r()>K7o;)t.pop();return t.length?t.join(","):void 0}var Snu="unknown";function FUe(e,t,r,n){return typeof e=="string"&&e.trim()?e.length>r?e.slice(0,r):e:(n?.debug(`${t} must be a non-empty string; using "${Snu}"`),Snu)}function Glt(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(!(typeof t!="number"||!Number.isFinite(t))&&!(t<0||t>9223372036854))return t}function wnu(e,t,r){let n=Glt(e);return n===void 0?(e!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),t):(t-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>t&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function Z$r(e,t){return e<t?t:e}function iqt(e,t,r,n){let i=Glt(e);return i===void 0?(e!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):i}function een(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var qlt=class{constructor(t,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=t.traceId,this._spanId=t.spanId,this._parentSpanId=t.parentSpanId,this._traceState=t.traceState,this._traceFlags=t.traceFlags??Y$r,this._parentIsRemote=t.parentIsRemote??!1,this._name=t.name,this._kind=t.kind,this._autoKeys=new Set(t.autoAttributeKeys),this._maxAttributes=t.maxAttributes,this._maxEvents=t.maxEvents,this._maxAttributesPerEvent=t.maxAttributesPerEvent,this._maxAttributeValueLength=t.maxAttributeValueLength,this._attributes=Object.create(null);for(let i of Object.keys(t.attributes))this._writeAttribute(i,t.attributes[i]);this._startMono=t.backdated?void 0:een(),this._startTime=t.clockAnchor&&this._startMono!==void 0?t.clockAnchor.wall+(this._startMono-t.clockAnchor.mono):t.startTime,this._startMono!==void 0&&(this._clockAnchor=t.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let t=een();if(t!==void 0)return this._startTime+Math.max(0,t-this._startMono)}return Date.now()}_mutable(t){return this._ended?(this._logger?.debug(`Ignoring ${t} on a span that has already ended`),!1):!0}_writeAttribute(t,r){if(VK(r)){t in this._attributes&&!this._autoKeys.has(t)&&this._userAttributeCount--,delete this._attributes[t];return}if(!this._autoKeys.has(t)&&!(t in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[t]=ren(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=Pme({},t);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(t,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=r&&Bnu(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:FUe(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:iqt(n,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(t,r){if(this._mutable("setStatus")){if(t!=="ok"&&t!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(t)}"; expected "ok" or "error"`),this;this._status={code:t,...r&&{message:J7o(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(t){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:i}=Y7o(t);return this.addEvent(Ich,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=FUe(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return xnu(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(t){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=iqt(t,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:Z$r(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Ich="exception",vch=4294967295;function Cch(e){try{return typeof e=="string"?e:String(e)}catch{return Z5}}function NUe(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),vch)}function xch(e,t){if(!t.length)return Object.keys(e);let r=t.filter(i=>Object.prototype.propertyIsEnumerable.call(e,i)),n=new Set(r);return[...r,...Object.keys(e).filter(i=>!n.has(i))]}function Onu(e,t,r,n,i,o,s=[]){let a=0,c=0,l={};for(let f of xch(e.attributes,s)){let m=e.attributes[f];if(!VK(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(l,f,{value:ren(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=l,c&&(e.droppedAttributesCount=NUe(e.droppedAttributesCount)+c);let u=0,p=0,d=[];for(let f of e.events){if(u>=n){p++;continue}if(u++,f.attributes){let m=Bnu(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=NUe(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=NUe(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:J7o(Cch(e.status.message),o)})}var ten=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},Pnu=new ten,oqt=class extends ten{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Sch(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function HSe(e,t){let r=J$r(e?.parent)??t,n=typeof r=="string"||r==null?r:Tnu(r,"traceparent"),i=Cnu(n);if(!i)return Pnu;let o=typeof r=="string"||r==null?e?.tracestate:Tnu(r,"tracestate");return new oqt(i,X$r(o))}function Tnu(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function J7o(e,t){return e.length>t?e.slice(0,t):e}function ren(e,t){return $$r(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function $$r(e,t,r,n){if(e===null||typeof e!="object")return VK(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?J7o(e,t):e);if(r.ancestors.has(e))return F$r;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=wch(e);if(i.selfDescribed)return VK(i.value)?String(i.value):$$r(i.value,t,r,n+1);if(e_(e)){let a=Math.min(e.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push($$r(e[l],t,r,n+1))}catch{c.push(Z5)}return e.length>a&&(c.length=e.length),c}let o={},s=0;for(let a of Object.keys(e)){if(s>=1e3)break;let c;try{c=$$r(e[a],t,r,n+1)}catch{c=Z5}a&&!VK(c)&&s++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return e}finally{r.ancestors.delete(e)}}function wch(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Bnu(e,t,r){let n;try{n=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},o=0,s=0;for(let a of n){if(o>=t){s++;continue}let c;try{c=ren(e[a],r)}catch{c=Z5}VK(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function Dnu(e,t){for(let r of Object.keys(e))e[r]=ren(e[r],t);return e}function sqt(e,t,r){return t===Pnu?r(t):e.with(t,()=>r(t))}function Y7o(e){try{let t=Sch(e);if(qSe(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var X7o={internal:1,server:2,client:3,producer:4,consumer:5},Tch={ok:1,error:2},Och=1,Pch=256,Bch=512;function Dch(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:Och)|Pch|(e.parentIsRemote?Bch:0)}function nen(e){if(typeof e=="string")return ire(e);try{return ire(String(e))}catch{return Z5}}function Rch(e){return e&&Object.prototype.hasOwnProperty.call(X7o,e)?X7o[e]:X7o.internal}function Z7o(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function kch(e,t){let r={name:nen(e.name),timeUnixNano:Z7o(e.timestamp)};if(e.attributes){let i=sre(e.attributes,t);i.length&&(r.attributes=i)}let n=NUe(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function Rnu(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:nen(e.name),kind:Rch(e.kind),startTimeUnixNano:Z7o(e.startTime),endTimeUnixNano:Z7o(e.endTime),flags:Dch(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=nen(e.traceState));let n=sre(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>kch(s,t)));let i=NUe(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=NUe(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:Tch[e.status.code],...e.status.message&&{message:nen(e.status.message)}}),r}function knu(e,t,r){return Z9t(e,t,r)}function Fnu(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:$9t(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var Nnu=8;function ien(){return een()??Date.now()}function $7o(e){try{return e instanceof qlt}catch{return!1}}function jnu(e,t){let r=Inu(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:X$r(t),traceFlags:r.flags,isRemote:!0}}function Fch(e){try{return typeof e.traceparent=="function"}catch{return!1}}function Nch(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function oen(e,t,r){e[t]!==r&&(e[t]=r)}function jch(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:t[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}var aqt=class{constructor(t,r,n,i,o,s){this._instance=t,this._config=r,this._logger=n,this._getContext=i,this._contextManager=o,this._onSpanQueued=s,this._queue=[],this._flushTimer=new kUe(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=r8,this._retryAfter=new DUe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(t,r){if(this._instance.isDisabled||this._instance.optedOut)return HSe(r,this._contextManager.active());let n=J$r(r?.parent);if(n&&typeof n!="string"&&!$7o(n)){if(Fch(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),HSe(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let i=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),HSe(r,this._contextManager.active());let o=Date.now(),s=wnu(r?.startTime,o,this._logger),a=Anu();this._liveSpans.set(a,ien());let c=this._autoContextAttributes();return new qlt({traceId:i?.traceId??gnu(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:FUe(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:Pme({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:s,backdated:s!==o,clockAnchor:Glt(r?.startTime)===void 0?i?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this.startSpan(t,i);try{let a=sqt(this._contextManager,s,o);return Fru(a)?a.then(c=>(s.end(),c),c=>{throw this._recordCallbackError(s,c),s.end(),c}):(s.end(),a)}catch(a){throw this._recordCallbackError(s,a),s.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let t=this._generation,r=Promise.resolve().then(()=>t===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=r8,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=jnu(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if($7o(t))return t.childContext();let n=this._contextManager.active();if($7o(n))return n.childContext();if(n instanceof oqt)return jnu(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let t;try{t=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return t.distinctId&&(r.posthogDistinctId=t.distinctId),t.sessionId&&(r.sessionId=t.sessionId),t.currentUrl&&(r["url.full"]=t.currentUrl),t.screenName&&(r["screen.name"]=t.screenName),t.appState&&(r["app.state"]=t.appState),r}_recordCallbackError(t,r){if(!(t instanceof qlt))return;let{type:n,message:i,stack:o}=Y7o(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=ien()-this._config.maxSpanAgeMs,r=0;for(let[n,i]of this._liveSpans){if(i>t)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(t,r){if(!this._liveSpans.delete(t.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(t,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(i){this._logger.debug("Span queue notification failed",i)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(t){let r=t.droppedAttributesCount??0,n=t.droppedEventsCount??0,i=0;for(let o of t.events)i+=o.droppedAttributesCount??0;(r||n||i)&&this._logger.debug(`Span limits discarded data from "${t.name}": ${r} attributes, ${n} events, ${i} event attributes`)}_runBeforeSpanSend(t,r){if(!this._config.beforeSpanSend.length)return t;let n={traceId:t.traceId,spanId:t.spanId,parentSpanId:t.parentSpanId,traceState:t.traceState},i={startTime:t.startTime,endTime:t.endTime},o={attributes:t.droppedAttributesCount,events:t.droppedEventsCount},s=Object.keys(t.attributes),a={traceFlags:t.traceFlags,parentIsRemote:t.parentIsRemote},c=t.status&&{...t.status},l=t,u=t;try{for(let f of this._config.beforeSpanSend){let m=f(l);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(m,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!Nch(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=FUe(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=Glt(u.startTime)??i.startTime,u.endTime=Z$r(Glt(u.endTime)??i.endTime,u.startTime);let d=[];for(let f of u.events)try{d.push({...f,name:FUe(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:iqt(f.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=d,Onu(u,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),u}catch(p){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",p),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(t,r){(t.traceId!==r.traceId||t.spanId!==r.spanId||t.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{oen(t,"traceId",r.traceId),oen(t,"spanId",r.spanId),oen(t,"parentSpanId",r.parentSpanId),oen(t,"traceState",r.traceState)}catch{return jch(t,r)}return t}_recordDrop(t,r){this._droppedSinceWarning+=t,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(t){let r=[];for(let n of t)try{r.push(Rnu(n,this._logger))}catch(i){this._logger.debug("Failed to encode a span; dropping it",i),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let t=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(t,"the user has opted out"),this._warnAboutDrops(),t}async _flushInner(){if(!this._queue.length)return 0;let t=this._discardQueueIfConsentWithdrawn();if(t)return t;let r=Dnu(knu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),o=this._queue.length,s=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return s+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(u,a,o,this._queue.length)),d=this._queue.slice(0,p),f=this._encodeBatch(d);if(!f.length){this._queue.splice(0,p),o-=p,s+=p,this._resetHeadBatchBudget();continue}let m=ien()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(Fnu(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=r8,this._resetHeadBatchBudget(),this._queue.splice(0,p),o-=p,s+=p,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(g.kind==="too-large"){if(p===1){this._queue.splice(0,1),o-=1,s+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=r8,this._resetHeadBatchBudget();continue}let A=Math.max(1,Math.floor(p/2));g.measuredLocally?a=A:this._maxExportBatchSize=A,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${A}`);continue}if(g.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=eqt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=ien()+this._nextFlushDelay()),this._headBatchFailures<Nnu)return this._logger.debug("Span export failed; retrying on the next flush",g.error),s;if(this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=r8,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${Nnu} times in a row`),this._retryAfter.isOpen())return s;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=r8,this._resetHeadBatchBudget(),this._recordDrop(p,"the ingestion endpoint rejected the batch")}return s}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(t=>{this._logger.debug("Background span flush failed",t)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(tqt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var cqt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var zch=5e3,Qch=512,Mch=2048,Lch=128,_ch=128,Uch=128,Vch=8192,Gch=1e4,qch=36e5;function KSe(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var znu=["service.name","service.version","deployment.environment"];function Wch(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(znu.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of znu)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function Hch(e,t){if(!e)return[];let r=[e].flat().filter(i=>!!i),n=r.filter(i=>typeof i=="function");return n.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function eHo(e,t,r){let n=Pme({...t},Wch(e?.resourceAttributes)),i=KSe(e?.maxExportBatchSize,Qch);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:Hch(e?.beforeSpanSend,r),maxAttributesPerSpan:KSe(e?.maxAttributesPerSpan,Lch),maxEventsPerSpan:KSe(e?.maxEventsPerSpan,_ch),maxAttributesPerEvent:Uch,maxAttributeValueLength:KSe(e?.maxAttributeValueLength,Vch),flushIntervalMs:KSe(e?.flushIntervalMs,zch),maxExportBatchSize:i,maxQueueSize:Math.max(KSe(e?.maxQueueSize,Mch),i),maxLiveSpans:KSe(e?.maxLiveSpans,Gch),maxSpanAgeMs:KSe(e?.maxSpanAgeMs,qch)}}var tHo=require("fs"),Lnu=require("fs/promises"),nHo=require("path"),_nu=require("readline"),sen=new ST.ReduceableCache(25),lqt=new ST.ReduceableCache(20),iHo=7,Kch=1e3,Jch=1e4,rHo=10485760;async function Unu(e,t=Lnu.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||elh(l)||tlh(c)||!(0,nHo.isAbsolute)(l)&&i===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=Vnu(a,i);if(c===void 0||lqt.get(c))continue;let l=n[a];if(!l)continue;l.sort((d,f)=>d-f);let u=nlh(l);if(u.every(d=>rlh(c,d)))continue;let p=ilh(sen,c,{});s.push(Xch(a,u,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&Zch(e,sen,i),sen.reduce(),e}async function Ych(e,t,r){let n,i=!1;try{n=await t(e,tHo.constants.O_RDONLY|tHo.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>rHo?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${rHo}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function Xch(e,t,r,n,i,o){let s=await Ych(e,i,o);if(s===void 0)return void lqt.set(n,1);let a=s;return new Promise(c=>{let l=!1;function u(C){l||(l=!0,C?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:rHo-1})}catch{lqt.set(n,1),u();return}let d;try{d=(0,_nu.createInterface)({input:p})}catch{lqt.set(n,1),u(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void u(p);let A=g[0],b=g[1];function I(){lqt.set(n,1),d.close(),d.removeAllListeners(),u(p)}p.on("error",I),d.on("error",I),d.on("close",()=>u(p)),d.on("line",C=>{if(f++,!(f<A)&&(r[f]=olh(C,0),f>=b)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let x=t[m];if(x===void 0){d.close(),d.removeAllListeners();return}A=x[0],b=x[1]}})})}function Zch(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=Vnu(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;$ch(n.lineno,n,o)}}function $ch(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Gnu(e);i<e;i++){let o=r[i];if(o===void 0)return void Qnu(t);t.pre_context.push(o)}if(r[e]===void 0)return void Qnu(t);t.context_line=r[e];let n=qnu(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function Qnu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function elh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function tlh(e){return e.lineno!==void 0&&e.lineno>Jch||e.colno!==void 0&&e.colno>Kch}function Vnu(e,t){return(0,nHo.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function rlh(e,t){let r=sen.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function nlh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=Mnu(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+iHo:(i.push(n),n=Mnu(o)),t++}return i}function Mnu(e){return[Gnu(e),qnu(e)]}function Gnu(e){return Math.max(1,e-iHo)}function qnu(e){return e+iHo}function ilh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function olh(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}var Wlt=require("path");function Wnu(e=process.cwd()){let t=Wlt.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,Wlt.isAbsolute)(o.filename)&&(o.filename=r((0,Wlt.relative)(n,r(o.filename))));return i}}var Hnu="5.55.0";var Dme={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var JSe=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t,r={}){let n=this._flags[t];return this._recordAccess(t),n?.enabled??r.defaultValue??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(Dme.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Dme.QUOTA_LIMITED),r===void 0&&o.push(Dme.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};var slh=6e4;function Knu(e){return e==="client"||e==="server"?e:"all"}function alh(e,t){return e===t||e==="all"||t==="all"}var Hlt=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function clh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var are=class e extends Error{constructor(t){super(t),clh(this,e)}},aen=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}withEvaluationSnapshot(t){return t.definitions?t:{...t,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(l){l instanceof are||l instanceof Ul?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${t}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${l}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...t,definitions:void 0});return await Promise.all(s.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=l,u&&(i[c.key]=u)}catch(l){l instanceof are||l instanceof Ul?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),t=r.definitions.featureFlagsByKey[t.key]??t;let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=M7o(t.filters?.payloads,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new Ul("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let l=r.definitions.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Ul("Flag has unknown group type index");if(!(l in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let u=s[l];return await this.matchFeatureFlagProperties(t,i[l],u,r)}{let l=this.getBucketingValueForFlag(t,n,o);if(l===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new Ul(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,l,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!n.definitions.featureFlagsByKey)throw new Ul("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Ul(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Ul(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Ul(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let u=n.definitions.featureFlagsByKey[c];if(u)if(u.active)try{let p=await this.computeFlagValueLocally(u,n);i[c]=p}catch(p){throw new Ul(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))i[c]=!1;else throw new Ul(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Ul(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){i=this.withEvaluationSnapshot(i);let o=t.filters||{},s=await z7o(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,l=o.early_exit??!1,{groups:u,groupProperties:p}=i,d=!1,f;for(let m of a)try{let g=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,A=n,b=r;if(g!==c&&g!=null){let C=i.definitions.groupTypeMapping[String(g)];if(!C||!(C in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(C in p)){d=!0;continue}A=p[C],b=u[C]}let I=await this.isConditionMatch(t,b,m,A,i);if(I==="match"){let C=m.variant,x=o.multivariate?.variants||[];f=C&&x.some(S=>S.key===C)?C:await this.getMatchingVariant(t,b)||!0;break}if(l&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof are)throw g;if(g instanceof Ul)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new Ul("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){o=this.withEvaluationSnapshot(o);let s=o.definitions,a=n.rollout_percentage,c=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((n.properties||[]).length>0){for(let l of n.properties){let u=l.type,p=!1;if(u==="cohort"){let d=await Ynu(l,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=l.operator==="not_in"?!d:d}else p=u==="flag"?await this.evaluateFlagDependency(l,i,o):Jnu(l,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await Y9t(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return Q7o(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return W$r(t.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(t){if(!this.evaluationContexts||this.evaluationContexts.length===0)return t;let r=new Set(this.evaluationContexts);return t.filter(n=>{let i=n.evaluation_contexts??n.evaluation_tags;return!i||i.length===0?!0:i.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(t){let r=this.featureFlagsByKey[t];return r?Knu(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>alh(Knu(r.evaluation_runtime),t)).map(r=>r.key)}updateFlagState(t){let r=this.filterFlagsByEvaluationContexts(t.flags);this.featureFlags=r,this.featureFlagsByKey=r.reduce((i,o)=>(i[o.key]=o,i),{});let n=new Set(r.map(i=>i.key));this.filteredOutFlagKeys=new Set(t.flags.filter(i=>!n.has(i.key)).map(i=>i.key)),this.groupTypeMapping=t.group_type_mapping??t.groupTypeMapping??{},this.cohorts=t.cohorts,this.propertyMatchingVersion=t.property_matching_version??t.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((t.minimal_flag_called_events??t.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let t=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(slh,t*2**this.backOffCount):t}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Hlt(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Hlt(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Hlt(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,s={flags:n.flags??[],group_type_mapping:i,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:o};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(t){t instanceof Hlt&&this.onError?.(t)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=N2(()=>{o.abort()},this.timeout),r.signal=o.signal}let i=()=>clearTimeout(n);try{let o=this.fetch,s=await o(t,r);return s.status!==200?(i(),s):{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{i()}},json:async()=>{try{return await s.json()}finally{i()}}}}catch(o){throw i(),o}}async stopPoller(t=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await WSe(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function Jnu(e,t,r,n){return j7o(e,t,{warnFunction:r,propertyMatchingVersion:n})}function llh(e,t){if(!(e in t))throw new are(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Ynu(e,t,r,n=!1,i,o){let s=String(e.value);llh(s,r);let a=r[s];return Xnu(a,t,r,n,i,o)}async function Xnu(e,t,r,n=!1,i,o){if(!e)return!0;let s=e.type,a=e.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let l of a)try{let u=await Xnu(l,t,r,n,i,o);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof are)throw u;if(u instanceof Ul)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Ul("Can't match cohort without a given cohort property value");return s==="AND"}for(let l of a)try{let u;if(l.type==="cohort")u=await Ynu(l,t,r,n,i,o);else if(l.type==="flag"){if(!i)throw new Ul(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(l)}else u=Jnu(l,t,void 0,o);let p=l.negation||!1;if(s==="AND"){if(!u&&!p||u&&p)return!1}else if(u&&!p||!u&&p)return!0}catch(u){if(u instanceof are)throw u;if(u instanceof Ul)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Ul("can't match cohort without a given cohort property value");return s==="AND"}var ulh=["--unhandled-rejections","--unhandled_rejections"],plh=new Set(["throw","strict","warn","warn-with-error-code","none"]),flh=[...globalThis.process?.execArgv??[]],dlh=globalThis.process?.env?.NODE_OPTIONS;function mlh(e){let t=[],r="",n=!1;for(let i=0;i<e.length;i++){let o=e[i];o==="\\"&&n&&i+1<e.length?r+=e[++i]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(t.push(r),r="")}return r&&t.push(r),t}function Znu(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=ulh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);plh.has(o)&&(t=o)}return t}function hlh(e=flh,t=dlh){return Znu(e)??Znu(mlh(t??""))??"throw"}var $nu=hlh();function eiu(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function glh(e,t){let r=!1;return Object.assign((n,i)=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length;eiu(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function tiu(e,t,r=$nu){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>eiu(e,i,o));n.on("uncaughtException",glh(e,t))}}function riu(e,t=$nu){let r=globalThis.process;!r||t==="throw"||t==="strict"||t==="warn-with-error-code"||r.on("unhandledRejection",n=>{e(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var Alh=2e3,oHo=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new w$r({...dru(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return F9t(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i,o){let s={...o},a=t.buildFromUnknown(r,n);a.$exception_list=await t.modifyFrames(a.$exception_list);let c=ST.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(tiu(this.onException.bind(this),this.onFatalError.bind(this)),riu(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Alh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},jUe=oHo;var cen=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function ylh(e){return e==="v0"||e==="v1"}function niu(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return ylh(e)?e:"v0"}var blh="$ai_",uqt="analytics";function iiu(e){return typeof e.event=="string"&&e.event.startsWith(blh)}var Klt=class e extends Error{constructor({requestId:t,drops:r,retryExhausted:n,cause:i}){super(e.buildMessage(t,r,n,i)),this.name="CaptureV1Error",this.requestId=t,this.drops=r,this.retryExhausted=n,this.cause=i}static buildMessage(t,r,n,i){let o=`Capture V1 batch ${t} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function sHo(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Elh(e){return typeof e=="string"?e:void 0}var Ilh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:sHo},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:sHo},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:sHo},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Elh}],vlh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function Clh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xlh(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function oiu(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function Slh(e){let r={...Clh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of Ilh)if(o in r){let c=a(r[o]);c!==void 0&&(n[s]=c),delete r[o]}let i={};for(let{property:o,field:s}of vlh)if(o in r){let a=r[o];typeof a=="string"&&(i[s]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,oiu(r,"$set",e.$set),oiu(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:xlh(e.timestamp),...i,options:n,properties:r}}function siu(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(Slh)};return r&&(n.historical_migration=!0),n}var wlh="/i/v1/analytics/events",Tlh=3e4,Olh=new Set([408,500,502,503,504]),len=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??Tlh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>N2(i,n))),this.generateRequestId=r.generateRequestId??F2,this.compress=r.compress??H9t}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=siu(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${wlh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,p=GSe({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,l,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!u&&Olh.has(A)){let b=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(l,b)}else{let b=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,b)}else{let b;try{b=await d.waitFor(this.parseResponse(m))}catch(x){if(g.aborted)throw x;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,b,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(u)return void this.onError(new Klt({requestId:r,drops:s,retryExhausted:I.map(x=>x.uuid)}));a=I;let C=this.parseRetryAfter(m);f=this.backoffDelay(l,C)}}catch(m){if(d&&!d.signal.aborted)throw m;if(u)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(l)}finally{d?.cleanup()}f!==void 0&&await this.sleep(f)}}async sendOnce(t,r,n,i){let o=this.buildHeaders(n,i),s=r;if(this.config.compressionEnabled){let p=await this.compress(r,this.config.isDebug);p!==null&&(s=p,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((p,d)=>{l=N2(()=>{let f=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);f.name="AbortError",d(f),a.abort(f)},this.config.requestTimeoutMs)});try{let p=this.fetchFn(t,{method:"POST",headers:o,body:s,signal:a.signal}),d=!1;p.then(b=>{a.signal.aborted&&!d&&this.cancelBody(b)}).catch(()=>{});let f=await Promise.race([p,u]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:b=>Promise.race([b,u]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(l),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(l),p}}buildHeaders(t,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(t),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(t,r,n){let i=r.results??{},o=[];for(let s of t){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(t,r){let n=Math.min(this.config.initialRetryDelayMs*2**(t-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(t){let r=t.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(t){let r=await t.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(t,r,n){let i="";try{i=(await n(t.text())).slice(0,512)}catch{}let o=i?`: ${i}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(t,r,n,i){this.onError(new Klt({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new Klt({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var zUe="ai-capture",uen="/i/v0/ai/batch/";var Blh=new TextEncoder;function cHo(e){return Blh.encode(GSe(e)).length}function aiu(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=cHo(a);if(c>t){i.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&s+c>r&&(n.push(o),o=[],s=0),o.push(a),s+=c}return o.length>0&&n.push(o),{batches:n,dropped:i}}var Dlh=100,ciu=3e4,Rlh=5e4,klh=50,Flh=500,Nlh="https://us.i.posthog.com",liu=new Set;function fen(e,t){liu.has(e)||(liu.add(e),console.warn(`[PostHog] ${t}`))}function jlh(e){return typeof e=="string"?e.trim():""}function zlh(e){return(typeof e=="string"?e.trim():"")||void 0}function Qlh(e){return(typeof e=="string"?e.trim():"")||Nlh}function Mlh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function Llh(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var den=class extends K9t{constructor(t,r={}){let n=jlh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:Qlh(r.host),personalApiKey:zlh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new cen,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=niu(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,Dlh):i.featureFlagsPollingInterval===null?null:ciu,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new aen({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new jUe(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||Rlh}enqueue(t,r,n,i){super.enqueue(t,r,n,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(t=!1){let r=this.flushWithPendingPromises();return!this._traces||t&&this._traces.throttled?r:z9t([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(t){let r=this._flushEventsAndSpans(t),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??Flh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??klh;this._waitUntilCycle.timer=N2(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getQueueRouteKey(t){return this.captureMode==="v1"&&iiu(t)?"ai":uqt}persistedQueueKeyForRoute(t){return t===zUe?jQ.AiCaptureQueue:t==="ai"?jQ.AiQueue:jQ.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[uqt,"ai"]:[uqt];return this._aiCaptureRouteActive&&t.push(zUe),t}getBatchEndpointPath(t){return t===zUe?uen:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=uqt){if(n===zUe)return this.sendAiCaptureBatch(t,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(t,r,n);let i=t.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(t,r){let{batches:n,dropped:i}=aiu(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${uen}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(t,r){try{await super.sendBatch(t,r,zUe)}catch(n){if(!Vlt(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${cHo(o)} bytes) was rejected with 413 by ${uen} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let i=Math.ceil(t.length/2);await this.sendAiSubBatch(t.slice(0,i),r),await this.sendAiSubBatch(t.slice(i),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new len({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(t,r)=>this.fetch(t,r),onError:t=>this._events.emit("error",t),compress:t=>this.compressPayload(t)})),this._v1Sender}getLibraryVersion(){return Hnu}get metrics(){return this._metrics||(this._metrics=new nqt(this,K$r(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new cqt}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new aqt(this,eHo(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let t=this.context?.get();return{distinctId:t?.distinctId,sessionId:t?.sessionId}}startSpan(t,r){return this._tracesPipeline?.startSpan(t,r)??HSe(r,this._spanContextManager.active())}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this._tracesPipeline;return s?i?s.withSpan(t,i,o):s.withSpan(t,o):sqt(this._spanContextManager,HSe(i,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let t=super.getCommonEventProperties();return(this.options.isServer??!0)&&(t.$is_server=!0),t}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}_warnIfInvalidCapture(t,r,n){typeof t=="string"&&this._logger.warn(r),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(t,r,n,i,o){return this.addPendingPromise(this._prepareEventMessage(r,i).then(({distinctId:s,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,u,o):this.enqueue(t,p,u,o)}).catch(s=>{s&&console.error(s)}))}_capturePreparedEvent(t,r){return this._sendPreparedEvent("capture",t,r)}capture(t){this._warnIfInvalidCapture(t,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(t,!1)}async captureImmediate(t){return this._warnIfInvalidCapture(t,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(t,!0)}captureAi(t){if(this.disabled)return;let r=RUe(t.uuid,F2);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=RUe(t.uuid,F2);return await this._sendPreparedAiEvent({...t,uuid:r},!0),r}_sendPreparedAiEvent(t,r){return typeof t?.event=="string"&&!t.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${t.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",t,r,void 0,zUe)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:t,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(r).length>0&&(i.$set=r),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:t,event:"$set",properties:i})}unsetPersonProperties({distinctId:t,properties:r}){let n=Mlh(r);n.length!==0&&this.capture({distinctId:t,event:"$set",properties:{$unset:n}})}alias(t){this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(t){await this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(t){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(t)}getFeatureFlagKeysByEvaluationRuntime(t){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(t)??[]}async waitForLocalEvaluationReady(t=ciu){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let D=this._flagOverrides[t];if(D===void 0)return;let R=this._payloadOverrides?.[t];return{key:t,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:R}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,p=this.addLocalPersonAndGroupProperties(r,s,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,b,I,C,x,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let D=this.featureFlagsPoller?.featureFlagsByKey[t];if(D)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(D,d,{matchValue:i});if(R){m=!0;let O=R.value;I=D.id,x="Evaluated locally",S=D.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:R.payload??void 0,reason:x,reasonCode:D.active===!1?"flag_disabled":void 0}}}catch(R){if(R instanceof are||R instanceof Ul)this._logger?.info(`${R.name} when computing flag locally: ${t}: ${R.message}`);else throw R}}if(!m&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,a,[t]);if(D===void 0)b=Dme.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt;let R=[];D.errorsWhileComputingFlags&&R.push(Dme.ERRORS_WHILE_COMPUTING),D.quotaLimited?.includes("feature_flags")&&R.push(Dme.QUOTA_LIMITED);let O=D.flags[t];if(O===void 0)R.push(Dme.FLAG_MISSING);else{I=O.metadata?.id,C=O.metadata?.version,x=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:z,reason:x,reasonCode:O.reason?.code}}R.length>0&&(b=R.join(","))}}if(o){let D=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,R={$feature_flag:t,$feature_flag_response:D,$feature_flag_id:I,$feature_flag_version:C,$feature_flag_reason:x,locally_evaluated:m,[`$feature/${t}`]:D,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(R.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(R.$feature_flag_definitions_loaded_at=O)}b&&(R.$feature_flag_error=b),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:D,groups:s,disableGeoip:a,properties:R})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){fen("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(fen("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){fen("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let b=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,l,u,s,a);m={...m,...b.flags||{}},g={...g,...b.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new JSe({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new JSe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new JSe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,b=!1,I=!1,C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),x=new Set;if(C)for(let[D,R]of Object.entries(C.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:C.payloads[D],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},x.add(D)}let S=f!==void 0&&Array.from(f).some(D=>this.featureFlagsPoller?.featureFlagsByKey[D]===void 0);if((C?C.fallbackToFlags||S:!0)&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,s,a);if(D){this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt,b=!!D.errorsWhileComputingFlags,I=Array.isArray(D.quotaLimited)&&D.quotaLimited.includes("feature_flags");for(let[R,O]of Object.entries(D.flags)){if(x.has(R))continue;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}m[R]={key:R,enabled:O.enabled,variant:O.variant,payload:z,id:O.metadata?.id,version:O.metadata?.version,reason:O.reason?.description??O.reason?.code,locallyEvaluated:!1,hasExperiment:O.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[D,R]of Object.entries(this._flagOverrides)){if(R===void 0){delete m[D];continue}let O=m[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:O?.payload,id:O?.id,version:O?.version,reason:O?.reason,locallyEvaluated:O?.locallyEvaluated??!1,hasExperiment:O?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[D,R]of Object.entries(this._payloadOverrides)){let O=m[D];O&&(m[D]={...O,payload:R})}if(f!==void 0)for(let D of Object.keys(m))f.has(D)||delete m[D];return new JSe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:b,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(t,r){return t==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([u],[p])=>u<p?-1:u>p?1:0))}`:"",l=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(l):this.distinctIdHasSentFlagCalls[r]=new Set([l]),this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){let r=Date.now()+(t??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),this._metrics&&(await WSe(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await WSe(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(t){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=N2(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(uru(s)&&r&&o in r){let a={};for(let[c,l]of Object.entries(s))a[String(c)]=String(l);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(t,r){return{distinct_id:t,...r||{}}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!jUe.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(jUe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:s},r,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(t,r,n,i){if(!jUe.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(jUe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){return this._prepareEventMessage(t)}async _prepareEventMessage(t,r={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p}=t,d=this.context?.get(),f=r.includeContextProperties??!0,m=n||d?.distinctId,g=f?{...this.props,...d?.properties||{},...o||{}}:{...o||{}};m||(m=F2(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?q9t(g):g,b=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p});if(!b)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){fen("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let C=typeof c=="object"?c:void 0,x=await this.getFeatureFlagsForEvent(b.distinctId,s,u,C);return Llh(x)}return{}}).catch(()=>({})).then(C=>{let x=b.groups||s;return{...C,...b.properties||{},...x!==void 0&&Object.keys(x).length>0?{$groups:x}:{}}});return b.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&fru(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(b.event="$bot_pageview",I.$browser_type="bot"),{distinctId:b.distinctId,event:b.event,properties:I,options:{timestamp:b.timestamp,disableGeoip:b.disableGeoip,uuid:b.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n)try{if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}catch(s){return this._logger.error(`Error in before_send function for event '${t.event}':`,s),null}return i}};var uiu=require("async_hooks"),men=class{constructor(){this.storage=new uiu.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var piu=require("async_hooks"),hen=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new piu.AsyncLocalStorage}};var fiu=require("zlib"),diu=require("util"),_lh=(0,diu.promisify)(fiu.gzip);async function miu(e,t=!0){try{let r=await _lh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var gen=require("os");function hiu(){let e,t;try{e=(0,gen.platform)(),t=(0,gen.release)()}catch{}return V7o(e,t)}var giu="posthog-node";function Ulh(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[lHo.POSTHOG_ID_TAG];if(c===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,l).toString();s.tags["PostHog Person URL"]=u;let p=s.exception?.values||[],d=p.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(A=>({...A,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags},m=ST.getInjectedReleaseId();return m&&(f.$release_id=m),t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var lHo=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=giu,this.name=giu,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Ulh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var cre=class extends den{getLibraryId(){return"posthog-node"}compressPayload(t){return miu(t,this.isDebug)}initializeContext(){return new men}initializeSpanContextManager(){return new hen}hostResourceAttributes(){return hiu()}createErrorPropertiesBuilder(){return new ST.ErrorPropertiesBuilder([new ST.EventCoercer,new ST.ErrorCoercer,new ST.ObjectCoercer,new ST.StringCoercer,new ST.PrimitiveCoercer],ST.createStackParser("node:javascript",ST.nodeStackLineParser),[oru(),t=>Unu(t,void 0,this._logger),Wnu()])}};function Aiu(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var Aen=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},Vlh="feature_flag_evaluated",Glh=3e3,qlh=3e3,yen=class{evaluator;environment;sendFeatureFlagEvents;pending=new Map;resolved=new Map;constructor({environment:t,sendFeatureFlagEvents:r,posthogApiKey:n,evaluator:i}){this.environment=t,this.sendFeatureFlagEvents=r,this.evaluator=i??new cre(n??"",{featureFlagsRequestTimeoutMs:Glh,isServer:!1})}isEnabled(t,r){let n=yiu(t,r),i=this.pending.get(n);if(i!=null)return i;let o=this.evaluateAndRemember(t,r,n);return this.pending.set(n,o),o}async evaluateAndRemember(t,r,n){let i=await this.evaluate(t,r);return this.resolved.set(n,i),i}getCachedValue(t,r){return this.resolved.get(yiu(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,qlh),t.unref()})])}catch{}finally{clearTimeout(t)}}async flushAfterPendingEvaluations(){await Promise.allSettled(this.pending.values()),await this.evaluator.flush()}async evaluate(t,r){let{org:n}=r,i=Hlh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,uHo(n),{personProperties:i,groups:{organization:n},groupProperties:{organization:i},sendFeatureFlagEvents:!1})}catch{return!1}return this.sendFeatureFlagEvents&&this.captureFlagUsage({flag:t,org:n,result:o,properties:i}),Aiu(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=Wlh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.217.1"};this.tryCapture({distinctId:uHo(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:uHo(r),event:Vlh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:Aiu(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function Wlh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function uHo(e){return`org:${e}`}function Hlh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function yiu(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var ben;function Een(){return ben==null&&(ben=Klh()),ben}async function pHo(){await ben?.flush()}function Klh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new Aen:new yen({posthogApiKey:e,environment:UK(),sendFeatureFlagEvents:v$r()})}var Ien=class{posthog;constructor({posthogApiKey:t}){this.posthog=new cre(t,{isServer:!1})}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.217.1",usingAccessToken:!0,cliReleaseEnvironment:UK(),...Wpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:UK()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var pqt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};nf();rr();var Jlt=require("fs/promises"),biu=require("os"),Eiu=require("path");F4e();var Jlh="id",Ylh=".fern",fqt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new cre(r,{isServer:!1}),this.userId=t==null?void 0:j7i(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"5.217.1",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:UK(),agent:Olr(),...r!=null?{userEmail:r}:{},...Wpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:UK()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Pl({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ew(),r=ke(Xt.of((0,biu.homedir)()),Ee.of(Ylh),Ee.of(Jlh));try{await Gt(r)?this.persistedDistinctId=(await(0,Jlt.readFile)(r)).toString():(await(0,Jlt.mkdir)((0,Eiu.dirname)(r),{recursive:!0}),await(0,Jlt.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var fHo;async function dqt(){return fHo==null&&(fHo=await Xlh()),fHo}async function Xlh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!v$r())return new pqt;let t=await cXe();return t!=null?new fqt({token:t,posthogApiKey:e}):await Az()!=null?new Ien({posthogApiKey:e}):new fqt({token:void 0,posthogApiKey:e})}catch{return new pqt}}ln();gt();Pt();vQ();var mqt=Ae(require("process"),1);gHe();var Ciu=Ae(HJi(),1),xiu=Ae(viu(),1);function wT(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=XW(e),e.length===0))return 0;e=e.replace((0,xiu.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(Ciu.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}ln();function ven(e){let t=0;for(let r of e.split(`
3483
3483
  `))t=Math.max(t,wT(r));return t}var Giu=Ae(mHo(),1);var $lh=/[\p{Lu}]/u,euh=/[\p{Ll}]/u,Tiu=/^[\p{Lu}](?![\p{Lu}])/gu,Biu=/([\p{Alpha}\p{N}_]|$)/u,hHo=/[_.\- ]+/,tuh=new RegExp("^"+hHo.source),Oiu=new RegExp(hHo.source+Biu.source,"gu"),Piu=new RegExp("\\d+"+Biu.source,"gu"),ruh=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let c=0;c<e.length;c++){let l=e[c];a=c>2?e[c-3]==="-":!0,i&&$lh.test(l)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&euh.test(l)&&(!a||n)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),s=o,o=!1,i=!0):(i=t(l)===l&&r(l)!==l,s=o,o=r(l)===l&&t(l)!==l)}return e},nuh=(e,t)=>(Tiu.lastIndex=0,e.replace(Tiu,r=>t(r))),iuh=(e,t)=>(Oiu.lastIndex=0,Piu.lastIndex=0,e.replace(Oiu,(r,n)=>t(n)).replace(Piu,r=>t(r)));function gHo(e,t){if(!(typeof e=="string"||Array.isArray(e)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(e)?e=e.map(o=>o.trim()).filter(o=>o.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?o=>o.toLowerCase():o=>o.toLocaleLowerCase(t.locale),n=t.locale===!1?o=>o.toUpperCase():o=>o.toLocaleUpperCase(t.locale);return e.length===1?hHo.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=ruh(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(tuh,""),e=t.preserveConsecutiveUppercase?nuh(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),iuh(e,n))}var EHo=Ae(Riu(),1);gHe();var kiu=(e=0)=>t=>`\x1B[${t+e}m`,Fiu=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Niu=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,HE={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},yeC=Object.keys(HE.modifier),cuh=Object.keys(HE.color),luh=Object.keys(HE.bgColor),beC=[...cuh,...luh];function uuh(){let e=new Map;for(let[t,r]of Object.entries(HE)){for(let[n,i]of Object.entries(r))HE[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=HE[n],e.set(i[0],i[1]);Object.defineProperty(HE,t,{value:r,enumerable:!1})}return Object.defineProperty(HE,"codes",{value:e,enumerable:!1}),HE.color.close="\x1B[39m",HE.bgColor.close="\x1B[49m",HE.color.ansi=kiu(),HE.color.ansi256=Fiu(),HE.color.ansi16m=Niu(),HE.bgColor.ansi=kiu(10),HE.bgColor.ansi256=Fiu(10),HE.bgColor.ansi16m=Niu(10),Object.defineProperties(HE,{rgbToAnsi256:{value(t,r,n){return t===r&&r===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(o=>o+o).join(""));let i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:t=>HE.rgbToAnsi256(...HE.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,n,i;if(t>=232)r=((t-232)*10+8)/255,n=r,i=r;else{t-=16;let a=t%36;r=Math.floor(t/36)/5,n=Math.floor(a/6)/5,i=a%6/5}let o=Math.max(r,n,i)*2;if(o===0)return 30;let s=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(r));return o===2&&(s+=60),s},enumerable:!1},rgbToAnsi:{value:(t,r,n)=>HE.ansi256ToAnsi(HE.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>HE.ansi256ToAnsi(HE.hexToAnsi256(t)),enumerable:!1}}),HE}var puh=uuh(),jiu=puh;var Cen=new Set(["\x1B","\x9B"]),fuh=39,yHo="\x07",Miu="[",duh="]",Liu="m",bHo=`${duh}8;;`,ziu=e=>`${Cen.values().next().value}${Miu}${e}${Liu}`,Qiu=e=>`${Cen.values().next().value}${bHo}${e}${yHo}`,muh=e=>e.split(" ").map(t=>wT(t)),AHo=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=wT(XW(e[e.length-1]));for(let[a,c]of n.entries()){let l=wT(c);if(s+l<=r?e[e.length-1]+=c:(e.push(c),s=0),Cen.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(bHo)),i){o?c===yHo&&(i=!1,o=!1):c===Liu&&(i=!1);continue}s+=l,s===r&&a<n.length-1&&(e.push(""),s=0)}!s&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},huh=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(wT(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},guh=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=muh(e),a=[""];for(let[l,u]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=wT(a[a.length-1]);if(l!==0&&(p>=t&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),p=0),(p>0||r.trim===!1)&&(a[a.length-1]+=" ",p++)),r.hard&&s[l]>t){let d=t-p,f=1+Math.floor((s[l]-d-1)/t);Math.floor((s[l]-1)/t)<f&&a.push(""),AHo(a,u,t);continue}if(p+s[l]>t&&p>0&&s[l]>0){if(r.wordWrap===!1&&p<t){AHo(a,u,t);continue}a.push("")}if(p+s[l]>t&&r.wordWrap===!1){AHo(a,u,t);continue}a[a.length-1]+=u}r.trim!==!1&&(a=a.map(l=>huh(l)));let c=[...a.join(`
3484
3484
  `)];for(let[l,u]of c.entries()){if(n+=u,Cen.has(u)){let{groups:d}=new RegExp(`(?:\\${Miu}(?<code>\\d+)m|\\${bHo}(?<uri>.*)${yHo})`).exec(c.slice(l).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===fuh?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=jiu.codes.get(Number(i));c[l+1]===`
3485
3485
  `?(o&&(n+=Qiu("")),i&&p&&(n+=ziu(p))):u===`
@@ -4112,7 +4112,7 @@ ${r}</${e.name}>`}function tAs(e,t){let r=e.replaceAll("&","&amp;").replaceAll("
4112
4112
  `)),Object.keys(u).length>0&&(s.css=u)}let c;if(i!=null){let{inline:l,...u}=i;l!=null&&l.length>0&&(c=l.join(`
4113
4113
  `)),Object.keys(u).length>0&&(s.js=u)}return{stripped:s,header:t!=null&&t.length>0?t:void 0,footer:r!=null&&r.length>0?r:void 0,cssInline:a,jsInline:c}}var O8u=require("fs/promises");function OGe(e){return e.outputMode._visit({downloadFiles:()=>{},github:t=>`https://github.com/${t.owner}/${t.repo}`,githubV2:t=>t._visit({commitAndRelease:r=>`https://github.com/${r.owner}/${r.repo}`,pullRequest:r=>`https://github.com/${r.owner}/${r.repo}`,push:r=>`https://github.com/${r.owner}/${r.repo}`,_other:()=>{}}),publish:()=>{},publishV2:()=>{},_other:()=>{}})}async function PGe(e,t,r){let n;try{n=await(0,O8u.readFile)(e,"utf8")}catch{return}let i=new Set([t]),o="fernapi/";t.startsWith(o)&&i.add(t.slice(o.length));let s=n.split(`
4114
4114
  `),a=0,c=/^\s*-\s+name:\s*["']?([A-Za-z0-9/_.\-@]+)["']?\s*(#.*)?$/;for(let l=0;l<s.length;l++){let u=s[l];if(u==null)continue;let p=u.match(c);if(!(p==null||p[1]==null)&&i.has(p[1])){if(a===r)return l+1;a++}}}var TGe=class{#e=new WeakMap;#t=new Map;recordOccurrences(t){for(let r of t){let n=this.#t.get(r.name)??0;this.#e.set(r,n),this.#t.set(r.name,n+1)}}lookup(t){return this.#e.get(t)??0}};yo();gt();c0();rr();var gGu=require("crypto"),AGu=require("fs/promises"),kbs=Ae(WX(),1),yGu=require("path"),bGu=require("util");gt();function ASt(e,t){if(e==null)return;let r=t?.get(e);return r??e}function Oag(e,t,r){let n=ASt(e,r);if(n==null)return;let i=t?.[n];if(!(i?.width==null||i?.height==null))return{path:n,width:i.width,height:i.height}}function FXt(e,t){if(e==null)return;if(e.type==="url")return{type:"url",value:e.value};let r=ASt(e.value,t);if(r!=null)return{type:"path",value:r}}function fbs(e,t,r){let n=e.background!=null?{type:"solid",...e.background}:void 0,i=ASt(e.backgroundImage,r);return{logo:Oag(e.logo,t,r),backgroundImage:i,accentPrimary:e.accentPrimary,background:n,border:e.border,sidebarBackground:e.sidebarBackground,headerBackground:e.headerBackground,cardBackground:e.cardBackground}}function Pag(e,t,r){if(e!=null)switch(e.type){case"dark":case"light":return{type:e.type,...fbs(e,t,r)};case"darkAndLight":return{type:"darkAndLight",dark:fbs(e.dark,t,r),light:fbs(e.light,t,r)};default:Ze(e)}}function Bag(e,t){if(e==null)return;let{"og:image":r,"og:logo":n,"twitter:image":i,"og:background-image":o,"og:dynamic:background-image":s,...a}=e;return{...a,"og:image":FXt(r,t)??void 0,"og:logo":FXt(n,t)??void 0,"twitter:image":FXt(i,t)??void 0,"og:background-image":FXt(o,t)??void 0,"og:dynamic:background-image":FXt(s,t)??void 0}}function Dag(e,t){if(e==null)return;let r=[];for(let n of e.files){let i=ASt(n.fileId,t);i!=null&&r.push({path:i,strategy:n.strategy})}return{remote:e.remote?.map(n=>({url:n.url,strategy:n.strategy,disableSri:n.disableSri})),files:r,inline:e.inline}}function Rag(e,t){if(e==null)return;let r=n=>{if(n!=null)return{type:"custom",name:n.name,variants:n.variants.map(i=>({fontFile:ASt(i.fontFile,t)??i.fontFile,weight:i.weight,style:i.style})),display:n.display,fallback:n.fallback,fontVariationSettings:n.fontVariationSettings}};return{headingsFont:r(e.headingsFont),bodyFont:r(e.bodyFont),codeFont:r(e.codeFont)}}function kag(e){if(e==null)return;let t={pageDirective:e.pageDirective,pageDescriptionSource:e.pageDescriptionSource,siteDescription:e.siteDescription},{robotsTxtOnInstanceUrl:r}=e;return r!=null?Object.assign(t,{robotsTxtOnInstanceUrl:r}):t}function Fag(e){if(e!=null)return{intercom:e.intercom}}function NXt({docsConfig:e,fileManifest:t,fileIdToPath:r,editThisPage:n}){return{title:e.title,defaultLanguage:e.defaultLanguage,translations:e.translations,announcement:e.announcement,navbarLinks:e.navbarLinks,footerLinks:e.footerLinks,logoHeight:e.logoHeight,logoHref:e.logoHref,logoRightText:e.logoRightText,favicon:ASt(e.favicon,r),agents:kag(e.agents),metadata:Bag(e.metadata,r),redirects:e.redirects,remotePaths:e.remotePaths,colorsV3:Pag(e.colorsV3,t,r),layout:e.layout,theme:e.theme,settings:e.settings,typographyV2:Rag(e.typographyV2,r),analyticsConfig:e.analyticsConfig,css:e.css,js:Dag(e.js,r),aiChatConfig:e.aiChatConfig,pageActions:e.pageActions,editThisPageLaunch:e.editThisPageLaunch,embedding:e.embedding,editThisPageGithub:n?.github!=null?{owner:n.github.owner,repo:n.github.repo,branch:n.github.branch??"main",host:n.github.host??"https://github.com"}:void 0,integrations:Fag(e.integrations),header:e.header,footer:e.footer}}gt();var mGu=Ae(dGu(),1);Co();var hGu=require("util"),Ilg=(0,hGu.promisify)(mGu.default);async function DGe(e,t,r){let n=IRt(e,t),i=[];for(let o of n){let s=await Promise.all(o.map(async a=>{try{let c=await Ilg(a);return c==null||c.height==null||c.width==null?void 0:{filePath:a,width:c.width,height:c.height,blurDataUrl:void 0}}catch(c){r.logger.error(`Failed to measure image size for ${a}. ${c?.message}`);return}}));i.push(...s.filter(ms))}return new Map(i.map(o=>[o.filePath,o]))}var vlg="_theme/",Clg=10,xlg={logo:["logoHeight","logoHref","logoRightText"],favicon:["favicon"],backgroundImage:[],colors:[],typography:["typographyV2"],layout:["layout"],settings:["settings","embedding"],theme:["theme","layout"],integrations:["integrations"],css:["css"],js:["js"],header:[],footer:[],navbarLinks:["navbarLinks"],footerLinks:["footerLinks"],aiSearch:["aiChatConfig"],announcement:["announcement"],metadata:["metadata"]},Slg=["header","footer"];function xgi(e){return!Slg.some(t=>EGu(e,t))}function EGu(e,t){return e[QXt(t)]!=null||e[t]!=null}function Fbs(e){let t=[],r=s=>{typeof s=="string"?t.push(s):hr(s)&&t.push(s.dark,s.light)};r(e.logo),r(e["background-image"]??e.backgroundImage),t.push(e.favicon);let n=e.css;t.push(...Array.isArray(n)?n:[n]);let i=e.js;for(let s of Array.isArray(i)?i:[i])t.push(hr(s)?s.path??s.url:s);let o=e.typography;if(hr(o))for(let s of Object.values(o))hr(s)&&Array.isArray(s.paths)&&t.push(...s.paths.map(a=>hr(a)?a.path:a));return t.some(s=>typeof s=="string"&&kI(s))}function Nbs({deployMode:e,theme:t}){return e==="ledger"&&t?.hasLedger===!0&&xgi(t.config)}async function jbs({rawTheme:e,themeDirectory:t,taskContext:r,cliVersion:n}){let i=si.THEME_ELIGIBLE_FIELDS.filter(m=>EGu(e,m)),o={},s=new Map,a=new Map,l=await IGu({theme:e,themeDirectory:t,taskContext:r,cliVersion:n,uploadFiles:async m=>{let g=await DGe(m.filter(A=>fp.parse(kbs.lookup(A.absoluteFilePath)||"")?.isImage()??!1).map(A=>A.absoluteFilePath),Clg,r);return Promise.all(m.map(async A=>{let b=`${vlg}${A.relativeFilePath}`,I=await(0,AGu.readFile)(A.absoluteFilePath),C=(0,gGu.createHash)("sha256").update(new Uint8Array(I)).digest("hex"),x=g.get(A.absoluteFilePath);return o[b]={hash:C,contentType:kbs.lookup(A.absoluteFilePath)||"application/octet-stream",contentLength:I.byteLength,filename:(0,yGu.basename)(A.relativeFilePath),...x!=null&&{width:x.width,height:x.height}},s.set(C,A.absoluteFilePath),a.set(b,b),{...A,fileId:b}}))}}).resolve(),u=NXt({docsConfig:l.config,fileManifest:o,fileIdToPath:a,editThisPage:void 0}),p=await wlg({rawTheme:e,themeKeys:i,themeDirectory:t,taskContext:r,cliVersion:n}),d={};for(let m of i)for(let g of xlg[m]){let A=g===m?e[QXt(m)]??e[m]:void 0,b=vGu(u[g],p[g],A);b!==void 0&&(d[g]=b)}let f=Tlg(u.colorsV3,i,e);return f!=null&&(d.colorsV3=f),{config:d,fileManifest:o,files:s}}function IGu({theme:e,themeDirectory:t,taskContext:r,cliVersion:n,uploadFiles:i}){let o={instances:[],navigation:[]};return new kN({domain:"theme.invalid",docsWorkspace:{type:"docs",workspaceName:void 0,absoluteFilePath:t,absoluteFilepathToDocsConfig:ke(t,Ee.of("theme.yml")),config:lui(o,e)},ossWorkspaces:[],apiWorkspaces:[],taskContext:r,cliVersion:n,uploadFiles:i})}async function wlg({rawTheme:e,themeKeys:t,themeDirectory:r,taskContext:n,cliVersion:i}){let o={};for(let c of t)c!=="colors"&&hr(e[QXt(c)]??e[c])&&(o[c]={});if(Object.keys(o).length===0)return{};let a=await IGu({theme:o,themeDirectory:r,taskContext:n,cliVersion:i,uploadFiles:async c=>c.map(l=>({...l,fileId:l.relativeFilePath}))}).resolve();return NXt({docsConfig:a.config,fileManifest:{},fileIdToPath:new Map,editThisPage:void 0})}function vGu(e,t,r){if(e===void 0||t===void 0)return e;if(!hr(e)||!hr(t))return r===void 0&&(0,bGu.isDeepStrictEqual)(e,t)?void 0:e;let n={};for(let[i,o]of Object.entries(e)){let s=hr(r)?r[QXt(i)]??r[i]:void 0,a=vGu(o,t[i],s);a!==void 0&&(n[i]=a)}return Object.keys(n).length>0?n:void 0}function Tlg(e,t,r){if(e==null)return;let n=hr(r.colors)?r.colors:{},i=(a,c)=>{let l=n[QXt(a)]??n[a];return typeof l=="string"||hr(l)&&l[c]!=null},o=(a,c)=>{let l={};for(let[u,p]of Object.entries(a)){if(p==null)continue;(u==="logo"?t.includes("logo"):u==="backgroundImage"?t.includes("backgroundImage"):i(u,c))&&(l[u]=p)}return l};if(e.type==="darkAndLight"){let a=o(e.dark,"dark"),c=o(e.light,"light");return Object.keys(a).length>0||Object.keys(c).length>0?{type:e.type,dark:a,light:c}:void 0}let s=o(e,e.type);return Object.keys(s).length>0?{type:e.type,...s}:void 0}function QXt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}gt();Pt();var SGu=Ae(FA(),1),Sgi=new Map;async function wGu({origin:e,organization:t,token:r,generatorId:n,language:i}){let o=JSON.stringify([e,t,r.value,n,i]),s=Sgi.get(o);if(s!=null)return s;let a=zbs({origin:e,organization:t,token:r,generatorId:n,language:i,currentVersion:"latest",includeMajor:!0});Sgi.set(o,a);try{return await a}finally{Sgi.get(o)===a&&Sgi.delete(o)}}async function zbs({origin:e,organization:t,token:r,generatorId:n,language:i,currentVersion:o,includeMajor:s}){let a=new URL("v1/fern/generator-versions/discover",`${iA(e)}/`),c=`${n}@${o}`,l;try{l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${r.value}`,"X-Fern-Organization-Id":t,"content-type":"application/json"},body:JSON.stringify({targets:[{targetId:"generator",generatorId:n,language:i,currentVersion:o,includeMajor:s}]})})}catch(u){throw new Error(`SDK Gen API version discovery failed for ${c} because the API could not be reached. Verify FERN_SDK_GEN_API_ORIGIN and the selected environment.`,{cause:u})}if(!l.ok)throw new Error(`SDK Gen API version discovery failed for ${c} with HTTP ${l.status}. Verify FERN_SDK_GEN_API_ORIGIN and the selected environment.`);return Olg(await l.json())}function Olg(e){if(!xGu(e,["targets"])||!Array.isArray(e.targets)||e.targets.length!==1)throw new Error("SDK Gen API returned an invalid generator version discovery response");let t=e.targets[0];if(!hr(t)||t.targetId!=="generator")throw new Error("SDK Gen API returned an invalid generator version discovery target");if(t.state==="UNAVAILABLE"){if(!xGu(t,["targetId","state","reason"])||t.reason!=="IDENTITY_UNAVAILABLE"&&t.reason!=="LANGUAGE_MISMATCH"&&t.reason!=="VERSION_UNAVAILABLE")throw new Error("SDK Gen API returned an invalid unavailable generator version result");return{targetId:"generator",state:"UNAVAILABLE",reason:t.reason}}if(t.state!=="RESOLVED")throw new Error("SDK Gen API returned an unknown generator version discovery state");if(!TGu(t,["targetId","state","compatibleVersion","withheldMajorVersion"]))throw new Error("SDK Gen API returned an invalid resolved generator version result");let r=CGu(t,"compatibleVersion"),n=CGu(t,"withheldMajorVersion");if(r==null&&n==null)throw new Error("SDK Gen API returned an empty generator version discovery result");return{targetId:"generator",state:"RESOLVED",...r==null?{}:{compatibleVersion:r},...n==null?{}:{withheldMajorVersion:n}}}function CGu(e,t){if(!Object.hasOwn(e,t))return;let r=e[t];if(typeof r!="string"||SGu.default.valid(r)!==r)throw new T({message:`SDK Gen API returned invalid ${t} ${JSON.stringify(r)}. Expected an exact semantic version such as 1.2.3.`,code:T.Code.VersionError});return r}function xGu(e,t){return hr(e)&&Object.keys(e).length===t.length&&TGu(e,t)}function TGu(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}var MXt=require("os"),OGu=require("v8"),OFe=require("worker_threads"),Pgi=require("zlib");hy();Pt();C_();z2();ip();function wgi({workspace:e,generators:t,context:r}){return t.map(n=>{let i=Gg({workspace:e,generationLanguage:n.language,keywords:void 0,smartCasing:n.smartCasing,smartCasingDigitWordBoundary:n.smartCasingDigitWordBoundary,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:n.packageName,version:void 0,context:r,sourceResolver:new Nh(r,e),dynamicGeneratorConfig:n.dynamicGeneratorConfig}),o=Z_e({ir:i,disableExamples:!0,smartCasing:n.smartCasing,smartCasingDigitWordBoundary:n.smartCasingDigitWordBoundary,generationLanguage:n.language,generatorConfig:n.dynamicGeneratorConfig});return[n.language,o]})}var PGu="fernDynamicIrWorker",BGu;function Qbs(e){BGu=e}function Mbs(){return!OFe.isMainThread&&OFe.workerData?.[PGu]===!0}function DGu(e){return JSON.parse((0,Pgi.gunzipSync)(e).toString("utf8"))}function Lbs(){let e=OFe.parentPort;e?.on("message",t=>{let r=[],n=x0e({logger:k0((o,...s)=>r.push([o,s]))}),i;try{let o=Blg(t.workspace),s=wgi({workspace:o,generators:t.generators,context:n});i={id:t.id,ok:!0,results:s.map(([a,c])=>[a,c==null?void 0:(0,Pgi.gzipSync)(JSON.stringify(c),{level:1})]),logs:r}}catch(o){i={id:t.id,ok:!1,error:o instanceof Error?o.stack??o.message:String(o)}}e.postMessage(i)})}function Plg(e){return{args:Tgi({generatorsConfiguration:e.generatorsConfiguration,workspaceName:e.workspaceName,cliVersion:e.cliVersion,absoluteFilePath:e.absoluteFilePath,changelog:e.changelog,dependenciesConfiguration:{dependencies:{}},sources:e.sources}),definition:e.definition,sourceDerivedGlobalHeaderNames:e.definition.sourceDerivedGlobalHeaderNames}}function Blg({args:e,definition:t,sourceDerivedGlobalHeaderNames:r}){return r!=null&&Object.defineProperty(t,"sourceDerivedGlobalHeaderNames",{configurable:!0,enumerable:!1,value:r,writable:!0}),new VD({...e,definition:t})}function Tgi(e,t=new Map){if(e==null||typeof e!="object")return e;if(t.has(e))return t.get(e);if(Array.isArray(e)){let n=[];t.set(e,n);for(let i of e)n.push(typeof i=="function"?void 0:Tgi(i,t));return n}let r={};t.set(e,r);for(let[n,i]of Object.entries(e))typeof i!="function"&&(r[n]=Tgi(i,t));return r}var RGu=1024**3,Dlg=1536,Rlg=8*RGu,klg=1.5*RGu;function Flg(){let e=process.constrainedMemory?.()??0;return e>0?Math.min(e,(0,MXt.totalmem)()):(0,MXt.totalmem)()}function Nlg({registrationConcurrency:e,cores:t=(0,MXt.availableParallelism)(),memoryBytes:r=Flg()}){if(e<=1)return 0;let n=Math.floor((r-Rlg)/klg);return Math.max(0,Math.min(e,t-1,n))}var Ogi=class e{size;createWorker;idle=[];running=new Map;queue=[];workerCount=0;nextId=0;terminated=!1;constructor(t,r){this.size=t,this.createWorker=r}static create({registrationConcurrency:t,context:r}){let n=Nlg({registrationConcurrency:t}),i=BGu;if(n===0||i==null)return;r.logger.debug(`Generating dynamic snippet IRs on up to ${n} worker thread(s)`);let o=Math.min(Dlg,Math.floor((0,OGu.getHeapStatistics)().heap_size_limit/1024/1024));return new e(n,()=>new OFe.Worker(i,{workerData:{[PGu]:!0},execArgv:process.execArgv.filter(s=>s==="--enable-source-maps"),resourceLimits:{maxOldGenerationSizeMb:o},stdout:!1,stderr:!1}))}get threadCount(){return this.workerCount}get isTerminated(){return this.terminated}run(t,r){if(this.terminated)return Promise.reject(new Error("Dynamic IR worker pool was terminated"));let n;try{n={id:this.nextId++,workspace:Plg(t),generators:Tgi(r)}}catch(i){return Promise.reject(i)}return new Promise((i,o)=>{this.queue.push({request:n,resolve:i,reject:o}),this.dispatch()})}async terminate(){this.terminated=!0;for(let r of this.queue.splice(0))r.reject(new Error("Dynamic IR worker pool was terminated"));let t=[...this.idle.splice(0),...this.running.keys()];await Promise.all(t.map(r=>r.terminate()))}dispatch(){for(;this.queue.length>0;){let t=this.idle.pop()??(this.workerCount<this.size?this.spawn():void 0);if(t==null)return;let r=this.queue.shift();if(r==null){this.idle.push(t);return}try{t.postMessage(r.request),this.running.set(t,r),t.ref()}catch(n){this.idle.push(t),r.reject(n instanceof Error?n:new Error(String(n)))}}}spawn(){let t=this.createWorker();this.workerCount++,t.unref();let r=!1;t.on("message",i=>{if(r)return;let o=this.running.get(t);this.running.delete(t),t.unref(),this.idle.push(t),o!=null&&(i.ok?o.resolve({results:i.results,logs:i.logs}):o.reject(new Error(i.error))),this.dispatch()});let n=i=>{r||(r=!0,this.removeWorker(t),this.running.get(t)?.reject(i),this.running.delete(t),this.terminated||this.dispatch())};return t.on("error",n),t.on("exit",i=>n(new Error(`Dynamic IR worker exited with code ${i}`))),t}removeWorker(t){let r=this.idle.indexOf(t);r!==-1&&this.idle.splice(r,1),this.workerCount--}};Ec();gt();rr();var NZt=Ae(nAe(),1);Pt();vQ();var Hse=require("crypto"),TXu=Ae(rYe(),1),OXu=require("zlib");var BCs="Direct RubyGems publishing is not supported. Use output.delivery: github with publish.registry: rubygems so the gem is published by the GitHub Actions workflow generated in that repository.",qyg=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;function yAi(e){return e==null?void 0:qyg.exec(e)?.[1]}function DCs(e,t,r){if(r!=null&&e.registry!==r)throw new Error(`Direct publication credential registry ${e.registry} does not match requested registry ${r}`);switch(t!=null&&vqu(t),e.registry){case"npm":case"crates":return RFe(e.registry,"token",e.token),{registry:e.registry,token:e.token};case"pypi":return RFe("pypi","username",e.username),RFe("pypi","password",e.password),{registry:"pypi",username:e.username,password:e.password};case"maven":{RFe("maven","username",e.username),RFe("maven","password",e.password);let n=Wyg(e.signature);return{registry:"maven",username:e.username,password:e.password,...n==null?{}:{signature:n}}}case"rubygems":throw new Error(BCs);case"nuget":case"go":case"composer":case"postman":throw new Error(`sdk-gen-api does not support direct ${e.registry} registry publication`)}}function Iqu(e){vqu(e)}function bAi(e){let t=e.flatMap(n=>{if(!n.publicationRequested)return[];if(n.publishCredential==null){if(n.credentialsRequired)throw new Error("SDK Config direct publication is missing its credential configuration");return[]}return[DCs(n.publishCredential,n.publishUrl,n.publishRegistry)]});if(t.length>64)throw new Error("sdk-gen-api supports at most 64 direct publish credential targets");let r=Buffer.from(JSON.stringify({schemaVersion:"fern-publish-credentials/v1",credentialSetId:"00000000-0000-8000-8000-000000000000",targets:t.map(n=>({targetId:"0".repeat(20),...n}))}));if(r.length>65536)throw new Error(`sdk-gen-api publish credentials file is ${Hyg(r.length)}, exceeding the 64 KiB limit`)}function Wyg(e){if(e!=null)return RFe("maven","signature.keyId",e.keyId),RFe("maven","signature.password",e.password),RFe("maven","signature.secretKey",e.secretKey),{keyId:e.keyId,password:e.password,secretKey:e.secretKey}}function RFe(e,t,r){if(r==null||r.trim().length===0)throw new Error(`Direct ${e} publication through sdk-gen-api requires ${t}`);if(r.trim()==="OIDC"||r.trim()==="<USE_OIDC>")throw new Error(`Direct ${e} publication through sdk-gen-api does not support OIDC credentials`);if(Buffer.byteLength(r,"utf8")>16384)throw new Error(`Direct ${e} publication through sdk-gen-api ${t} exceeds the 16 KiB field limit`)}function vqu(e){try{let t=new URL(e);if(t.protocol==="https:"&&t.username.length===0&&t.password.length===0)return}catch{}throw new Error("Direct registry URL must use HTTPS and must not contain user information")}function Hyg(e){return`${(e/1024).toFixed(2)} KiB`}function Cqu({claimUrl:e,buildId:t}){let r;try{r=new URL(e)}catch{return}return`${r.origin}/sdk/${encodeURIComponent(t)}${r.hash}`}var xqu=Ae(require("path"),1);function Squ(e,t){let r=xqu.default.basename(e);return t==null?r:`${r}-${t}`}yo();gt();rr();var cXu=Ae(Tyi(),1);hy();NE();Pt();vQ();ln();var RZt=require("fs"),WN=require("fs/promises"),_Fe=Ae(require("path"),1),Byi=require("stream/promises");Nyr();var Oyi=Ae(sXu(),1);function aAe(e,t,{target:r="stdout",...n}={}){return Oyi.default[r]?nH.link(e,t):n.fallback===!1?e:typeof n.fallback=="function"?n.fallback(e,t):`${e} (\u200B${t}\u200B)`}aAe.isSupported=Oyi.default.stdout;aAe.stderr=(e,t,r={})=>aAe(e,t,{target:"stderr",...r});aAe.stderr.isSupported=Oyi.default.stderr;var Dyi=Ae(w0(),1),lXu=Ae(kJt(),1);function aXu(e){let t=e[0];if(t!=null)return t.coordinate._visit({npm:r=>({registry:"npm",label:"npm",version:r.version,url:`https://www.npmjs.com/package/${r.name}/v/${r.version}`}),maven:r=>({registry:"maven",label:"Maven Central",version:r.version,url:`https://central.sonatype.com/artifact/${r.group}/${r.artifact}/${r.version}`}),pypi:r=>({registry:"pypi",label:"PyPI",version:r.version,url:`https://pypi.org/project/${r.name}/${r.version}/`}),ruby:r=>({registry:"rubygems",label:"RubyGems",version:r.version,url:`https://rubygems.org/gems/${r.name}/versions/${r.version}`}),nuget:r=>({registry:"nuget",label:"NuGet",version:r.version,url:`https://www.nuget.org/packages/${r.name}/${r.version}`}),crates:r=>({registry:"crates",label:"crates.io",version:r.version,url:`https://crates.io/crates/${r.name}/${r.version}`}),_other:()=>{}})}var QSg=/^Pipeline: raw result \(\d+ bytes\): (\{.*\})$/,Pyi=class{context;generatorInvocation;absolutePathToPreview;telemetryContext;lengthOfLastLogs=0;cachedReplayResult;replayEventEmitted=!1;taskStartedAtMs=Date.now();constructor({interactiveTaskContext:t,generatorInvocation:r,absolutePathToPreview:n,telemetryContext:i}){this.context=t,this.generatorInvocation=r,this.absolutePathToPreview=n,this.telemetryContext=i}async processUpdate(t){t==null&&this.context.failAndThrow("Task is missing on job status",void 0,{code:T.Code.InternalError});let r=t.packages.map(i=>i.coordinate._visit({npm:o=>`${o.name}@${o.version}`,maven:o=>`${o.group}:${o.artifact}:${o.version}`,pypi:o=>`${o.name} ${o.version}`,ruby:o=>`${o.name}:${o.version}`,nuget:o=>`${o.name} ${o.version}`,crates:o=>`${o.name} ${o.version}`,_other:()=>"<unknown package>"}));t.packages.length>0&&this.#n==null&&(this.#n=t.packages[0]?.coordinate._visit({npm:i=>i.version,maven:i=>i.version,pypi:i=>i.version,ruby:i=>i.version,nuget:i=>i.version,crates:i=>i.version,_other:()=>{}})),this.#i==null&&(this.#i=aXu(t.packages)),this.absolutePathToPreview==null&&this.context.setSubtitle(r.length>0?r.map(i=>`\u25E6 ${i}`).join(`
4115
- `):void 0);for(let i of t.logs.slice(this.lengthOfLastLogs))this.context.logger.log(qSg(i.level),i.message),this.#n==null&&(this.#n=LSg(i.message)??this.#n),this.cachedReplayResult==null&&(this.cachedReplayResult=_Sg(i.message));this.lengthOfLastLogs=t.logs.length;let n=i=>{this.context.logger.debug(`Generated files. ${aAe("View here",i,{fallback:(o,s)=>`${o}: ${s}`})}`)};return await t.status._visit({notStarted:St,running:St,failed:({message:i,s3PreSignedReadUrl:o})=>{o!=null&&n(o),this.context.failAndThrow(i,void 0,{code:T.Code.ContainerError})},finished:async i=>{if(i.s3PreSignedReadUrlV2!=null){n(i.s3PreSignedReadUrlV2);let o=this.getAbsolutePathToLocalOutput();o!=null&&await Ryi({s3PreSignedReadUrl:i.s3PreSignedReadUrlV2,absolutePathToLocalOutput:o,context:this.context})}if(this.absolutePathToPreview==null)for(let o of r)this.context.logger.info(`Published ${o}`);this.#e=!0,this.#t=i.createdSnippets!=null?i.createdSnippets:!1,this.#r=i.snippetsS3PreSignedReadUrl,this.#o=i.pullRequestUrl,this.#s=i.noChangesDetected,i.actualVersion!=null&&(this.#n=i.actualVersion),this.emitReplayTelemetryIfReady()},_other:()=>{this.context.logger.warn("Received unknown update type: "+t.status.type)}}),this.#e?{createdSnippets:this.#t,snippetsS3PreSignedReadUrl:this.#r,actualVersion:this.#n,pullRequestUrl:this.#o,noChangesDetected:this.#s,publishTarget:this.#i}:void 0}getAbsolutePathToLocalOutput(){return this.absolutePathToPreview!=null?ke(this.absolutePathToPreview,Ee.of(_Fe.default.basename(this.generatorInvocation.name))):this.generatorInvocation.absolutePathToLocalOutput}emitReplayTelemetryIfReady(){if(!this.replayEventEmitted&&this.cachedReplayResult!=null&&!this.telemetryContext.disableTelemetry)try{let t={success:!0,steps:{replay:this.cachedReplayResult},warnings:[]},n={...(0,cXu.buildReplayTelemetryProps)({pipelineResult:t,generatorName:this.generatorInvocation.name,generatorVersion:this.generatorInvocation.version,cliVersion:this.telemetryContext.cliVersion,repoUri:USg(this.generatorInvocation),automationMode:this.telemetryContext.automationMode,autoMerge:this.telemetryContext.autoMerge,skipIfNoDiff:this.telemetryContext.skipIfNoDiff,hasBreakingChanges:!1,versionArg:this.telemetryContext.versionArg,versionBump:this.telemetryContext.versionBump,replayConfigEnabled:this.telemetryContext.replayConfigEnabled,noReplayFlag:this.telemetryContext.noReplayFlag,githubMode:VSg(this.generatorInvocation),previewMode:this.absolutePathToPreview!=null,durationMs:Date.now()-this.taskStartedAtMs}),surface:"fiddle",org_id:this.telemetryContext.orgId};this.context.instrumentPostHogEvent({command:"replay",properties:n}),this.context.logger.debug(`[telemetry] replay event sent: ${JSON.stringify(n)}`),this.replayEventEmitted=!0}catch(t){this.context.logger.debug(`[telemetry] failed to send replay event: ${String(t)}`)}}#e=!1;get isFinished(){return this.#e}#t=!1;get createdSnippets(){return this.#t}#r=void 0;get snippetsS3PreSignedReadUrl(){return this.#r}#n=void 0;get actualVersion(){return this.#n}#i=void 0;get publishTarget(){return this.#i}#o=void 0;get pullRequestUrl(){return this.#o}#s=void 0;get noChangesDetected(){return this.#s}},MSg=/Tagging release (v?\d+\.\d+\.\d+(?:-[\w.-]+)?)/;function LSg(e){let t=e.match(MSg);if(t?.[1]!=null)return t[1].replace(/^v/,"")}function _Sg(e){let t=e.match(QSg);if(t?.[1]!=null)try{return JSON.parse(t[1])?.steps?.replay}catch{return}}function USg(e){let t=e.raw?.github;return t==null?"":"uri"in t&&typeof t.uri=="string"?t.uri:"repository"in t&&typeof t.repository=="string"?t.repository:""}function VSg(e){let t=e.raw?.github;if(t!=null&&"mode"in t){if(t.mode==="pull-request")return"pull-request";if(t.mode==="commit-and-release")return"commit-and-release"}return"push"}async function Ryi({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r,skipFernignore:n=!1}){try{let i=await WSg(t),o=await HSg(t);!n&&i&&o?await KSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}):!n&&i&&!o?await JSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}):await GSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}),r.logger.info(le.green(`Downloaded to ${t}`))}catch(i){r.failAndThrow("Failed to download files",i,{code:T.Code.NetworkError})}}async function uXu({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){try{let n=await Ld.get(e,{responseType:"stream",timeout:6e4,signal:AbortSignal.timeout(aws)});await(0,WN.mkdir)(_Fe.default.dirname(t),{recursive:!0}),await(0,Byi.pipeline)(n.data,(0,RZt.createWriteStream)(t)),r.logger.info(le.green(`Downloaded to ${t}`))}catch(n){r.failAndThrow("Failed to download archive",n,{code:T.Code.NetworkError})}}var aws=300*1e3;async function GSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await Ld.get(e,{responseType:"stream",timeout:6e4,signal:AbortSignal.timeout(aws)}),n=await Dyi.default.dir({prefix:"fern",unsafeCleanup:!0}),i=_Fe.default.join(n.path,"output.zip");await(0,Byi.pipeline)(r.data,(0,RZt.createWriteStream)(i)),await sws(t),await(0,WN.mkdir)(t,{recursive:!0}),await dXu(i,t)}async function sws(e){await Gt(e)&&(await pXu(e),await(0,WN.rm)(e,{recursive:!0,force:!0}))}async function pXu(e){try{let t=await(0,WN.readdir)(e,{withFileTypes:!0});for(let r of t){let n=Xt.of(_Fe.default.join(e,r.name));r.isDirectory()&&await pXu(n);try{await(0,WN.chmod)(n,493)}catch{}}await(0,WN.chmod)(e,493)}catch{}}function qSg(e){switch(e){case"DEBUG":return Un.Debug;case"INFO":return Un.Info;case"WARN":return Un.Warn;case"ERROR":return Un.Error;default:return Un.Info}}async function WSg(e){let t=ke(e,Ee.of(q1));return await Gt(t)}async function HSg(e){let t=ke(e,Ee.of(".git"));return await Gt(t)}async function nY(e,t,r){return(await Qa(r.logger,"git",e,{cwd:t,doNotPipeOutput:!0})).stdout}async function KSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){let n=ke(t,Ee.of(q1)),i=await Gee({absolutePathToFernignore:n});await nY(["rm","-rf","."],t,r),await fXu({s3PreSignedReadUrl:e,outputPath:t}),await nY(["add","."],t,r),await nY(["reset","--",...i],t,r),await nY(["restore","."],t,r)}async function JSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){let n=Xt.of((await Dyi.default.dir({})).path),i=ke(t,Ee.of(q1)),o=await Gee({absolutePathToFernignore:i});await(0,WN.cp)(t,n,{recursive:!0}),await nY(["init"],n,r),await nY(["add","."],n,r),await nY(["-c","user.name=fern","-c","user.email=hey@buildwithfern.com","-c","commit.gpgsign=false","commit","--allow-empty","--no-verify","-m","init"],n,r),await nY(["rm","-rf","."],n,r),await fXu({s3PreSignedReadUrl:e,outputPath:n}),await nY(["add","."],n,r),await nY(["reset","--",...o],n,r),await nY(["restore","."],n,r),await sws(ke(n,Ee.of(".git"))),await sws(t),await(0,WN.cp)(n,t,{recursive:!0})}async function fXu({s3PreSignedReadUrl:e,outputPath:t}){let r=await Ld.get(e,{responseType:"stream",timeout:6e4,signal:AbortSignal.timeout(aws)}),n=await Dyi.default.dir({prefix:"fern",unsafeCleanup:!0}),i=_Fe.default.join(n.path,"output.zip");await(0,Byi.pipeline)(r.data,(0,RZt.createWriteStream)(i)),await dXu(i,t)}async function dXu(e,t){return new Promise((r,n)=>{lXu.default.open(e,{lazyEntries:!0},(i,o)=>{if(i||!o){n(i??new Error("Failed to open zip file"));return}o.on("error",n),o.on("end",r),o.on("entry",s=>{let a=_Fe.default.join(t,s.fileName);if(s.fileName.endsWith("/")){(0,WN.mkdir)(a,{recursive:!0}).then(()=>o.readEntry()).catch(n);return}(0,WN.mkdir)(_Fe.default.dirname(a),{recursive:!0}).then(()=>{o.openReadStream(s,(c,l)=>{if(c||!l){n(c??new Error("Failed to open read stream"));return}l.pipe((0,RZt.createWriteStream)(a)).on("finish",()=>o.readEntry()).on("error",n)})}).catch(n)}),o.readEntry()})})}function cws(e){return[...new Set(e.filter(t=>t.length>0))].sort((t,r)=>r.length-t.length)}function pq(e,t){return cws(t).reduce((r,n)=>r.replaceAll(n,"[REDACTED]"),e)}function lws(e,t){return pq(e,t)}var YSg=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function GSt(e){let t=YSg.exec(e);return t===null||t[1]===void 0||t[2]===void 0||t[3]===void 0?null:{core:[t[1],t[2],t[3]],prerelease:t[4]?.split(".")??null}}function mXu(e,t){for(let r=0;r<e.core.length;r+=1){let n=hXu(e.core[r]??"",t.core[r]??"");if(n!==0)return n}return XSg(e.prerelease,t.prerelease)}function XSg(e,t){if(e===null||t===null)return e===t?0:e===null?1:-1;let r=Math.max(e.length,t.length);for(let n=0;n<r;n+=1){let i=e[n],o=t[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;let s=ZSg(i,o);if(s!==0)return s}return 0}function ZSg(e,t){let r=/^\d+$/.test(e),n=/^\d+$/.test(t);return r&&n?hXu(e,t):r!==n?r?-1:1:e===t?0:e<t?-1:1}function hXu(e,t){return e.length!==t.length?e.length<t.length?-1:1:e===t?0:e<t?-1:1}var uws=class extends Error{name="GeneratorConfigPolicyInvariantError";code="INVALID_GENERATOR_CUTOVER_POLICY";generatorId;language;cutoverVersion;retryable=!1;recommendedAction="FIX_GENERATOR_CUTOVER_POLICY";constructor(t,r){super(`Generator ${t} has an invalid cutover version: ${r.cutoverVersion}`),this.generatorId=t,this.language=r.language,this.cutoverVersion=r.cutoverVersion}};function $Sg(e){return new Map(e.map(([t,r])=>{let n=GSt(r.cutoverVersion);if(n===null)throw new uws(t,r);return[t,{...r,parsedCutoverVersion:n}]}))}var ewg=$Sg([["fernapi/fern-typescript",{language:"typescript",cutoverVersion:"4.0.0"}],["fernapi/fern-typescript-sdk",{language:"typescript",cutoverVersion:"4.0.0"}],["fernapi/fern-typescript-node-sdk",{language:"typescript",cutoverVersion:"4.0.0"}],["fernapi/fern-typescript-browser-sdk",{language:"typescript",cutoverVersion:"4.0.0"}],["fernapi/fern-python-sdk",{language:"python",cutoverVersion:"6.0.0"}],["fernapi/fern-java-sdk",{language:"java",cutoverVersion:"5.0.0"}],["fernapi/fern-kotlin-sdk",{language:"kotlin",cutoverVersion:"5.0.0"}],["fernapi/fern-go-sdk",{language:"go",cutoverVersion:"2.0.0"}],["fernapi/fern-csharp-sdk",{language:"csharp",cutoverVersion:"3.0.0"}],["fernapi/fern-php-sdk",{language:"php",cutoverVersion:"3.0.0"}],["fernapi/fern-ruby-sdk",{language:"ruby",cutoverVersion:"2.0.0"}],["fernapi/fern-ruby-sdk-v2",{language:"ruby",cutoverVersion:"2.0.0"}],["fernapi/fern-rust-sdk",{language:"rust",cutoverVersion:"1.0.0"}],["fernapi/fern-swift-sdk",{language:"swift",cutoverVersion:"1.0.0"}],["fernapi/fern-cli",{language:"cli",cutoverVersion:"1.0.0"}],["fernapi/fern-cli-generator",{language:"cli",cutoverVersion:"1.0.0"}],["fernapi/fern-mcp-server",{language:"mcp",cutoverVersion:"0.1.0"}]]);function kZt(e){return ewg.get(e)}var Wse=class extends Error{name="GeneratorConfigCompatibilityError";code;generatorId;language;requestedVersion;cutoverVersion;receivedConfigKind;expectedConfigKind;expectedLanguage;retryable=!1;recommendedAction;constructor(t){super(t.message),this.code=t.code,this.generatorId=t.generatorId,this.language=t.language,this.requestedVersion=t.requestedVersion,this.cutoverVersion=t.cutoverVersion,this.receivedConfigKind=t.receivedConfigKind,this.expectedConfigKind=t.expectedConfigKind,this.expectedLanguage=t.expectedLanguage,this.recommendedAction=t.recommendedAction}};function pws(e){return kZt(e)?.language}function XGe(e){let t=cAe(e),r=e.configKind;if(!rwg(r))throw YGe(e,{code:"INVALID_CONFIG_KIND",message:"Configuration kind must be legacy-fern or sdk-config-v1",cutoverVersion:t.cutoverVersion,expectedLanguage:t.language,expectedConfigKind:t.configKind,recommendedAction:"USE_SUPPORTED_CONFIG_KIND"},r);if(r!==t.configKind){let n=kZt(e.generatorId);throw n===void 0?new Error(`Missing validated generator policy for ${e.generatorId}`):twg(e,n,t.configKind,r)}return t}function cAe(e){let t=kZt(e.generatorId);if(t===void 0)throw YGe(e,{code:"UNKNOWN_GENERATOR",message:`Unknown first-party generator: ${e.generatorId}`,cutoverVersion:null,expectedLanguage:null,expectedConfigKind:null,recommendedAction:"USE_KNOWN_GENERATOR_ID"});if(t.language!==e.language)throw YGe(e,{code:"GENERATOR_LANGUAGE_MISMATCH",message:`Generator ${e.generatorId} targets ${t.language}, not ${e.language}`,cutoverVersion:t.cutoverVersion,expectedLanguage:t.language,expectedConfigKind:null,recommendedAction:"USE_GENERATOR_LANGUAGE"});let r=GSt(e.requestedVersion);if(r===null)throw YGe(e,{code:"INVALID_GENERATOR_VERSION",message:`Generator version must be an exact semantic version: ${e.requestedVersion}`,cutoverVersion:t.cutoverVersion,expectedLanguage:t.language,expectedConfigKind:null,recommendedAction:"USE_EXACT_GENERATOR_VERSION"});let n=mXu(r,t.parsedCutoverVersion)<0,i=n?"legacy-fern":"sdk-config-v1";return{generatorId:e.generatorId,language:t.language,requestedVersion:e.requestedVersion,cutoverVersion:t.cutoverVersion,configKind:i,payloadKind:n?"fern-runtime-bundle":"sdk-config-v1"}}function ZGe({generatorId:e,language:t,configKind:r,versionSource:n}){let i=kZt(e);if(i===void 0)throw YGe({generatorId:e,language:t,requestedVersion:"unpinned"},{code:"UNKNOWN_GENERATOR",message:`Unknown first-party generator: ${e}`,cutoverVersion:null,expectedLanguage:null,expectedConfigKind:null,recommendedAction:"USE_KNOWN_GENERATOR_ID"});if(i.language!==t)throw YGe({generatorId:e,language:t,requestedVersion:"unpinned"},{code:"GENERATOR_LANGUAGE_MISMATCH",message:`Generator ${e} targets ${i.language}, not ${t}`,cutoverVersion:i.cutoverVersion,expectedLanguage:i.language,expectedConfigKind:null,recommendedAction:"USE_GENERATOR_LANGUAGE"});let o={generatorId:e,language:t,cutoverVersion:i.cutoverVersion};if(r==="legacy-fern"){if(n!=="fern-latest")throw new Error("Legacy Fern unpinned routes must use fern-latest as their version source");return{...o,versionSource:n,configKind:r,payloadKind:"fern-runtime-bundle"}}return{...o,versionSource:n,configKind:r,payloadKind:"sdk-config-v1"}}function fws(e){return ZGe({...e,configKind:"sdk-config-v1",versionSource:"sdk-config-omitted"})}function YGe(e,t,r=e.configKind){return new Wse({generatorId:e.generatorId,language:e.language,requestedVersion:e.requestedVersion,receivedConfigKind:r,...t})}function twg(e,t,r,n){let i=r==="legacy-fern";return YGe(e,{code:i?"LEGACY_FERN_CONFIG_REQUIRED":"SDK_CONFIG_V1_REQUIRED",message:i?`Generator ${e.generatorId} ${e.requestedVersion} requires legacy Fern configuration`:`Generator ${e.generatorId} ${e.requestedVersion} requires SDK Config v1`,cutoverVersion:t.cutoverVersion,expectedLanguage:t.language,expectedConfigKind:r,recommendedAction:i?"USE_LEGACY_FERN_CONFIG":"USE_SDK_CONFIG_V1"},n)}function rwg(e){return e==="legacy-fern"||e==="sdk-config-v1"}var iY="latest",dws="__fern_sdk_config_unpinned__";function FZt(e){return e===dws}function mws(e){return e??dws}function kyi(e,t){return e.requestedVersion!=null?!1:e.versionSource==="fern-latest"?t===iY:FZt(t)}var iwg=2e3,gXu=1080*1e3,AXu=6e4,WSt=64,owg=25*1024*1024,swg=25*1024*1024,yXu=5*1024*1024,bXu=25*1024*1024,awg=25*1024*1024,PXu=100*1024*1024,cwg=PXu,BXu=50*1024*1024,lwg=1024*1024,DXu=60*1024*1024,hws=20*1024,uwg="unpinned",pwg=new Set(["localhost","127.0.0.1","[::1]","::1"]),fwg=new Intl.Collator("en",{numeric:!0});function RXu(e,t){return t?{type:"download"}:e}var dwg=/^[a-z][a-z0-9_]{0,63}$/,Nyi=class extends Error{status;code;constructor(t,r,n){super(t),this.name="FernSdkGenApiSubmissionError",this.status=r,this.code=n}},jZt="use-sdk-gen-api",HSt="FERN_USE_SDK_GEN_API";function KSt(){let e=process.env[HSt]?.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}function JSt(e){let t=KSt();return t!=null?Promise.resolve(t):Een().isEnabled(jZt,kXu(e))}function Aws(e){let t=KSt();return t??Een().getCachedValue(jZt,kXu(e))}async function zZt({organization:e,generatorNames:t}){let r=[...new Set(t)],n=await Promise.all(r.map(async i=>{try{return await JSt({organization:e,generatorName:i})}catch{return!1}}));return new Map(r.map((i,o)=>[i,n[o]===!0]))}function kXu({organization:e,generatorName:t}){let r=bv(t);return{org:e,generator:t,...r!=null?{language:r}:{}}}var mwg=new Set(["fernapi/fern-mcp-server"]);function $Ge(e){return mwg.has(e)}function QZt({generatorName:e,version:t}){let r=bv(e);return r==null||GSt(t)==null?!1:cAe({generatorId:e,language:r,requestedVersion:t}).configKind==="sdk-config-v1"}function UFe({generatorName:e,version:t,usesSdkConfig:r}){if(!$Ge(e)&&!(!r&&!QZt({generatorName:e,version:t})))return KSt()!==!1}function YSt(e){return $Ge(e)}function Kse(){let e=process.env.FERN_SDK_GEN_API_ORIGIN??"https://sdk-gen.postman.co";if(e==null)return;let t;try{t=new URL(e)}catch{throw new Error("FERN_SDK_GEN_API_ORIGIN must be a valid URL")}if(t.username.length>0||t.password.length>0)throw new Error("FERN_SDK_GEN_API_ORIGIN must not contain credentials");let r=t.protocol==="http:"&&pwg.has(t.hostname);if(t.protocol!=="https:"&&!r)throw new Error("FERN_SDK_GEN_API_ORIGIN must use HTTPS unless it targets localhost");return t.toString().replace(/\/$/,"")}function bv(e){return pws(e)}function FXu(e,t="legacy-fern"){let r=bv(e.name);if(r!=null)return e.version===iY&&t==="legacy-fern"?ZGe({generatorId:e.name,language:e.language??r,configKind:t,versionSource:"fern-latest"}):XGe({generatorId:e.name,language:e.language??r,requestedVersion:e.version,configKind:t})}function XSt(e,t){let r=e.outputMode;switch(r.type){case"downloadFiles":return{requestedOutput:{type:"download"}};case"github":return EXu({owner:r.owner,repo:r.repo,branch:r.branch,mode:r.makePr===!0?"pull-request":"release",license:r.license,publishInfo:r.publishInfo,githubOptions:t});case"githubV2":{let n=r.githubV2;return EXu({owner:n.owner,repo:n.repo,host:n.host,branch:n.branch,mode:n.type==="pullRequest"?"pull-request":n.type==="push"?"push":"release",reviewers:n.type==="pullRequest"?gwg(n.reviewers):void 0,license:n.license,publishInfo:n.publishInfo,workflows:n.workflows,githubOptions:t})}case"publishV2":{let n=Awg(r.publishV2);return{...n.package!=null?{package:n.package}:{},requestedOutput:{type:"publish",publish:n.publish}}}case"publish":{let n=Iwg(e,r.registryOverrides);return{...n.package!=null?{package:n.package}:{},requestedOutput:{type:"publish",publish:n.publish}}}}}function EXu({owner:e,repo:t,host:r,branch:n,mode:i,reviewers:o,license:s,publishInfo:a,workflows:c,githubOptions:l}){let u=a!=null?ywg(a):void 0;return{...u?.package!=null?{package:u.package}:{},requestedOutput:{type:"github",repository:`${e}/${t}`,...r!=null?{host:r}:{},...n!=null?{branch:n}:{},mode:i,...o!=null?{reviewers:o}:{},...s!=null?{license:s}:{},...u!=null?{publish:u.publish}:{},...c===!1?{workflows:!1}:{},...l}}}function hwg(e,t){return e.type==="github"&&t!=null?{...e,...t}:e}function gwg(e){if(e==null)return;let t=e.filter(n=>n.type==="team").map(n=>n.name),r=e.filter(n=>n.type==="user").map(n=>n.name);if(!(t.length===0&&r.length===0))return{...t.length>0?{teams:t}:{},...r.length>0?{users:r}:{}}}function Awg(e){switch(e.type){case"npmOverride":return yws(e.npmOverride);case"mavenOverride":return bws(e.mavenOverride);case"pypiOverride":return NXu(e.pypiOverride);case"rubyGemsOverride":return qSt("rubygems",e.rubyGemsOverride);case"nugetOverride":return qSt("nuget",e.nugetOverride);case"cratesOverride":return qSt("crates",e.cratesOverride);case"postman":throw new Error("sdk-gen-api does not support Postman collection publication as an SDK output")}}function ywg(e){switch(e.type){case"npm":return yws(e);case"maven":return bws(e);case"pypi":return NXu(e);case"rubygems":return qSt("rubygems",e);case"nuget":return qSt("nuget",e);case"crates":return qSt("crates",e);case"postman":throw new Error("sdk-gen-api does not support Postman collection publication as an SDK output")}}function yws(e){return{...e?.packageName?{package:{packageName:e.packageName}}:{},publish:{registry:"npm",...e?.registryUrl?{url:e.registryUrl}:{}}}}function NXu(e){let t=e!=null&&"coordinate"in e?e.coordinate:e?.packageName;return{...t?{package:{packageName:t}}:{},publish:{registry:"pypi",...e?.registryUrl?{url:e.registryUrl}:{}}}}function bws(e){let t=e?.coordinate!=null?Ewg(e.coordinate):void 0;return{...t!=null?{package:t}:{},publish:{registry:"maven",...e?.registryUrl?{url:e.registryUrl}:{}}}}var bwg=new Set(["OIDC","<USE_OIDC>"]);function qSt(e,t){let r=e==="nuget"||e==="rubygems",n=r&&t?.apiKey!=null&&bwg.has(t.apiKey),i=r&&!n?yAi(t?.apiKey):void 0;return{...t?.packageName?{package:{packageName:t.packageName}}:{},publish:{registry:e,...t?.registryUrl?{url:t.registryUrl}:{},...i!=null?{apiKeyEnvironmentVariable:i}:{},...n?{trustedPublishing:!0}:{}}}}function Ewg(e){let[t,r]=e.split(":");if(!t||!r)throw new Error(`Invalid Maven coordinate for sdk-gen-api: ${e}`);return{groupId:t,artifactId:r}}function Iwg(e,t){let r=bv(e.name);if((r==="typescript"||r==="mcp")&&t.npm!=null)return yws(t.npm);if((r==="java"||r==="kotlin")&&t.maven!=null)return bws(t.maven);let n=jXu(r);if(n==null)throw new Error(`sdk-gen-api cannot infer a registry for ${r??e.name}`);return{publish:{registry:n}}}function jXu(e){switch(e){case"typescript":return"npm";case"python":return"pypi";case"java":case"kotlin":return"maven";case"go":return"go";case"csharp":return"nuget";case"php":return"composer";case"ruby":return"rubygems";case"rust":return"crates";case"mcp":return"npm";case"swift":case"cli":case void 0:return}}function zXu(e,t){let r=t.outputMode;if(r.type!=="publish"&&r.type!=="publishV2")return;let n=XSt(t).requestedOutput;if(n.type==="publish"&&n.publish.url!=null&&Iqu(n.publish.url),r.type==="publish"){let o=bv(t.name);if((o==="typescript"||o==="mcp")&&r.registryOverrides.npm!=null)return IXu(e,r.registryOverrides.npm.token);if((o==="java"||o==="kotlin")&&r.registryOverrides.maven!=null)return vXu(e,r.registryOverrides.maven);let s=jXu(o);throw s==null||!Cwg(s)?new Error(`sdk-gen-api does not support direct ${s??"unknown"} registry publication`):new Error(`Direct ${s} publication through sdk-gen-api requires publish credentials`)}let i=r.publishV2;switch(i.type){case"npmOverride":{let o=Fyi("npm",i.npmOverride);return IXu(e,o.token)}case"mavenOverride":{let o=Fyi("maven",i.mavenOverride);return vXu(e,o)}case"pypiOverride":{let o=Fyi("pypi",i.pypiOverride);return vwg(e,o.username,o.password)}case"cratesOverride":{let o=Fyi("crates",i.cratesOverride);return QXu(e,"crates",o.token)}case"rubyGemsOverride":throw new Error("sdk-gen-api does not support direct rubygems registry publication");case"nugetOverride":throw new Error("sdk-gen-api does not support direct nuget registry publication");case"postman":throw new Error("sdk-gen-api does not support Postman collection publication as an SDK output")}}function Myi(e,t,r,n){return{targetId:e,...DCs(t,r,n)}}function Fyi(e,t){if(t==null)throw new Error(`Direct ${e} publication through sdk-gen-api is missing its registry configuration`);return t}function IXu(e,t){return QXu(e,"npm",t)}function QXu(e,t,r){return Myi(e,{registry:t,token:r})}function vwg(e,t,r){return Myi(e,{registry:"pypi",username:t,password:r})}function vXu(e,t){return Myi(e,{registry:"maven",username:t.username,password:t.password,...t.signature==null?{}:{signature:t.signature}})}function Cwg(e){return e==="npm"||e==="maven"||e==="pypi"||e==="crates"}function xwg(e,t,r){let n=e.targets.flatMap((i,o)=>{if(i.requestedOutput.type!=="publish")return[];let s=t[o];if(s==null)throw new Error(`Cannot pair sdk-gen-api target ${i.targetId} with publish credentials`);let a=r?.[o],{publishUrl:c,publishRegistry:l}=LXu(i.requestedOutput),u=a!=null?Myi(i.targetId,a,c,l):zXu(i.targetId,s);return u!=null?[u]:[]});if(n.length!==0){if(n.length>WSt)throw new Error(`sdk-gen-api supports at most ${WSt} direct publish credential targets`);if(e.credentialSetId==null)throw new Error("sdk-gen-api direct registry targets require a credentialSetId");return{schemaVersion:"fern-publish-credentials/v1",credentialSetId:e.credentialSetId,targets:n}}}function MXu(e){zXu("preflight",e)}function Lyi(e){bAi(e.map(t=>({publicationRequested:t.requestedOutput?.type==="publish"||t.requestedOutput?.type==="github"&&t.requestedOutput.publish!=null,credentialsRequired:t.requestedOutput?.type==="publish",...LXu(t.requestedOutput),...t.publishCredential==null?{}:{publishCredential:t.publishCredential}})))}function LXu(e){let t=e?.type==="publish"||e?.type==="github"?e.publish:void 0;return t==null?{}:{publishRegistry:t.registry,...t.url==null?{}:{publishUrl:t.url}}}function _Xu(e){let{generatorInvocation:t,sdkVersion:r,specsTarGzBuffer:n,whitelabel:i}=e,o=bv(t.name),s=r==null||r.trim().length>0&&(!(0,NZt.isAutoVersion)(r)||UXu(e.requestedOutput));return o!=null&&s&&n!=null&&i==null}function UXu(e){return e?.type==="github"}function VXu({candidate:e,isSdkConfigTarget:t,isPreview:r}){let{generatorInvocation:n,sdkVersion:i,specsTarGzBuffer:o,whitelabel:s}=e;return s!=null?"whitelabel generation has not yet moved from Fiddle to the shared pipeline":i!=null&&(0,NZt.isAutoVersion)(i)&&!UXu(e.requestedOutput)?t?r?"preview generation only downloads files, so it cannot use --version AUTO":"automatic SDK versioning (--version AUTO) through sdk-gen-api requires GitHub output":"automatic SDK versioning (--version AUTO) through sdk-gen-api requires GitHub output in generators.yml":o==null?"the source archive is unavailable":`generator language ${n.language??"unknown"} does not match ${bv(n.name)}`}var jyi=class{expectedTargets;participants=[];removedTargetIds=new Set;terminalError;dispatched=!1;constructor(t){if(t<1)throw new Error("A Fern sdk-gen-api batch must expect at least one target");this.expectedTargets=t}run(t){return this.terminalError!=null?Promise.reject(this.terminalError):t.targetIdSeed!=null&&this.removedTargetIds.has(t.targetIdSeed)?Promise.reject(new Error(`Fern sdk-gen-api target ${t.targetIdSeed} was removed`)):this.dispatched?Promise.reject(new Error("The Fern sdk-gen-api batch was already dispatched")):new Promise((r,n)=>{this.participants.push({...t,resolve:r,reject:n}),this.dispatchIfReady()})}skip(){this.dispatched||this.terminalError!=null||(this.expectedTargets-=1,this.dispatchIfReady())}remove(t,r){if(this.dispatched||this.terminalError!=null||this.removedTargetIds.has(t))return!1;this.removedTargetIds.add(t);let n=this.participants.findIndex(o=>o.targetIdSeed===t),[i]=n>=0?this.participants.splice(n,1):[];return i?.reject(r),this.expectedTargets-=1,this.dispatchIfReady(),!0}cancel(t){if(!(this.dispatched||this.terminalError!=null)){this.terminalError=t;for(let r of this.participants)r.reject(t)}}dispatchIfReady(){this.dispatched||this.terminalError!=null||this.expectedTargets===0||this.participants.length!==this.expectedTargets||(this.dispatched=!0,this.dispatch())}async dispatch(){let t=[...this.participants].sort(zwg);try{(await HXu(t)).forEach((n,i)=>{let o=t[i];n.status==="fulfilled"?o?.resolve(n.value):o?.reject(n.reason)})}catch(r){this.terminalError=r;for(let n of this.participants)n.reject(r)}}},zyi=class{expectedTargetIds;settledTargetIds=new Set;waiters=[];preflightParticipants=[];terminalError;didRunPreflight=!1;constructor(t){if(this.expectedTargetIds=new Set(t),this.expectedTargetIds.size!==t.length)throw new Error("Fern sdk-gen-api preparation target IDs must be unique")}ready(t,r){if(this.assertExpected(t),this.settledTargetIds.has(t))throw new Error(`Fern sdk-gen-api target ${t} prepared more than once`);return this.settledTargetIds.add(t),r!=null&&this.preflightParticipants.push(r),new Promise((n,i)=>{this.waiters.push({resolve:n,reject:i}),this.finishIfSettled()})}fail(t,r,n){return this.assertExpected(t),this.settledTargetIds.has(t)?!1:(this.settledTargetIds.add(t),n||(this.terminalError=r),this.finishIfSettled(),!0)}assertExpected(t){if(!this.expectedTargetIds.has(t))throw new Error(`Unexpected Fern sdk-gen-api preparation target ${t}`)}finishIfSettled(){if(this.settledTargetIds.size===this.expectedTargetIds.size){if(!this.didRunPreflight&&this.terminalError==null&&this.preflightParticipants.length>0){this.didRunPreflight=!0;try{WXu(this.preflightParticipants)}catch(t){this.terminalError=t}}for(let t of this.waiters)this.terminalError!=null?t.reject(this.terminalError):t.resolve()}}};async function GXu(e){let[t]=await HXu([e]);if(t?.status==="fulfilled")return t.value;throw t?.reason??new Error("sdk-gen-api did not return the requested target")}function qXu(e){if(e>WSt)throw new Error(`sdk-gen-api supports at most ${WSt} target payloads per build; received ${e}`)}function WXu(e){let t=e[0];if(t==null)throw new Error("Cannot submit an empty Fern sdk-gen-api build");Nwg(e);let r;try{r=Kse()}catch(p){return t.context.failAndThrow(p instanceof Error?p.message:"Invalid sdk-gen-api origin",p,{code:T.Code.ConfigError})}if(!r)return t.context.failAndThrow("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled",void 0,{code:T.Code.ConfigError});Ywg(e),Qwg(e,t);let n=Xwg({apiName:t.apiName,organization:t.organization,cliVersion:t.cliVersion,specsTarGzBuffer:t.specsTarGzBuffer,targets:e.map(p=>({generatorInvocation:p.generatorInvocation,resolvedGeneratorVersion:p.resolvedGeneratorVersion,sdkGenApiRoute:p.sdkGenApiRoute,sdkName:p.sdkName,sdkVersion:p.sdkVersion,apiVersion:p.apiVersion,targetIdSeed:p.targetIdSeed,sourceSpecIndexes:p.sourceSpecIndexes,audiences:p.audiences,payload:p.payload,requestedOutput:p.requestedOutput,autoVersionPreviewOutput:p.autoVersionPreviewOutput,publishCredential:p.publishCredential,githubOptions:p.githubOptions}))}),i=xwg(n,e.map(p=>p.generatorInvocation),e.map(p=>p.publishCredential)),o=i!=null?Buffer.from(JSON.stringify(i)):void 0;if(o!=null&&o.length>65536)return t.context.failAndThrow(`sdk-gen-api publish credentials file is ${Lwg(o.length)}, exceeding the 64 KiB limit`,void 0,{code:T.Code.ConfigError});let s=t.specsTarGzBuffer.length+e.reduce((p,d)=>p+d.payload.body.length,0)+(o?.length??0);if(s>BXu)return t.context.failAndThrow(`sdk-gen-api source archive, target payloads, and publish credentials total ${fq(s)}, exceeding the 50 MiB in-memory upload limit`,void 0,{code:T.Code.ConfigError});let a=JSON.stringify(n),c=Buffer.byteLength(a,"utf8");if(c>lwg)return t.context.failAndThrow(`sdk-gen-api serialized request field is ${fq(c)}, exceeding the 1 MiB UTF-8 field limit; reduce generator customConfig, readme, settings, or API override metadata`,void 0,{code:T.Code.ConfigError});let l=new TXu.default;l.append("request",a),l.append("sources",t.specsTarGzBuffer,{filename:"specs.tar.gz",contentType:"application/gzip"}),e.forEach((p,d)=>{let f=n.targets[d];if(f==null)throw new Error(`Cannot pair sdk-gen-api payload at index ${d} with a target`);let m=p.payload.payloadKind==="fern-runtime-bundle";l.append("payloads",p.payload.body,{filename:`${f.targetId}.json${m?".gz":""}`,contentType:m?"application/gzip":"application/json"})}),o!=null&&l.append("credentials",o,{filename:"publish-credentials.v1.json",contentType:"application/json"});let u=l.getLengthSync();return u>DXu?t.context.failAndThrow(`sdk-gen-api multipart request is ${fq(u)}, exceeding the 60 MiB limit; reduce source or target payload size`,void 0,{code:T.Code.ConfigError}):{first:t,origin:r,request:n,form:l,sensitiveValues:cws([t.token.value,...Dwg(i)])}}async function HXu(e){let{first:t,origin:r,request:n,form:i,sensitiveValues:o}=WXu(e);wwg({first:t,origin:r,request:n,participants:e,sensitiveValues:o});let s;try{s=(await Ld.post(`${r}/v1/fern/build`,i,{headers:{...i.getHeaders(),Authorization:`Bearer ${t.token.value}`,"X-Fern-Organization-Id":t.organization},maxBodyLength:DXu,timeout:AXu})).data.buildId}catch(l){Twg(t.context,l,o);let u=xXu(l,o);return t.context.failAndThrow(`Failed to submit sdk-gen-api build: ${u.message}${Pwg(u,t.token)}`,u,{code:T.Code.NetworkError})}for(let l of e)l.context.logger.debug(`sdk-gen-api build ID: ${s}`);Swg({participants:e,request:n,origin:r,buildId:s});let a=new Map,c=Date.now()+gXu;for(;;){let l=Date.now()>=c,u;try{let f=await Ld.get(`${r}/v1/fern/build/${s}`,{headers:{Authorization:`Bearer ${t.token.value}`,"X-Fern-Organization-Id":t.organization},timeout:AXu});u=Rwg(f.data,o)}catch(f){let m=xXu(f,o);return t.context.failAndThrow("Failed to poll sdk-gen-api build",m,{code:T.Code.NetworkError})}let p=n.targets.find(f=>!u.targets.some(m=>m.targetId===f.targetId));if(p!=null)return t.context.failAndThrow(`sdk-gen-api response did not contain target ${p.targetId}`,void 0,{code:T.Code.InternalError});for(let[f,m]of n.targets.entries()){let g=u.targets.find(I=>I.targetId===m.targetId),A=e[f]?.context;if(g==null||A==null)continue;let b=a.get(g.targetId)??0;for(let I of g.logs.slice(b))Owg(A,I);a.set(g.targetId,g.logs.length)}if(n.targets.every(f=>_wg(u,f.targetId))||u.status==="failed"||u.status==="succeeded"){let f=await Promise.allSettled(e.map((m,g)=>Vwg(m,n.targets[g]?.targetId,u,n.targets[g]?.requestedOutput)));return Uwg({participant:t,status:u,buildId:s}),f}if(l)return t.context.failAndThrow(`Timed out waiting for sdk-gen-api build ${s} after ${gXu/6e4} minutes`,void 0,{code:T.Code.InternalError});await ef(iwg)}}function Swg({participants:e,request:t,origin:r,buildId:n}){for(let[i,o]of e.entries()){let s=t.targets[i];if(s!=null)try{o.context.instrumentPostHogEvent({orgId:o.organization,command:"sdk-gen-api build submitted",properties:{sdkGenApiBuildId:n,sdkGenApiTargetId:s.targetId,sdkGenApiTargetCount:t.targets.length,sdkGenApiHost:new URL(r).host,apiName:t.apiName,generatorName:s.fernGenerator.id,generatorVersion:s.fernGenerator.version??o.generatorInvocation.version,language:s.language,payloadKind:s.payloadKind,outputMode:s.requestedOutput.type,sdkName:s.sdk.name,sdkVersion:s.sdk.version}})}catch(a){o.context.logger.debug(`[telemetry] failed to send sdk-gen-api build event: ${String(a)}`)}}}function wwg({first:e,origin:t,request:r,participants:n,sensitiveValues:i}){let o=new Map(r.targets.map((s,a)=>{let c=n[a];return[s.targetId,{uploadBytes:c?.payload.body.length??0,targetIdSeed:c?.targetIdSeed,sourceSpecIndexes:c?.sourceSpecIndexes}]}));e.context.logger.debug(`Submitting sdk-gen-api build: ${Qyi({origin:t,sourceArchiveBytes:e.specsTarGzBuffer.length,request:{protocolVersion:r.protocolVersion,apiName:r.apiName,cliVersion:r.cliVersion,idempotencyKey:CXu(r.idempotencyKey),credentialSetId:r.credentialSetId==null?void 0:CXu(r.credentialSetId),apiInputs:r.apiInputs,targets:r.targets.map(s=>({targetId:s.targetId,apiInputId:s.apiInputId,language:s.language,sdk:s.sdk,fernGenerator:s.fernGenerator,payloadKind:s.payloadKind,package:s.package,requestedOutput:s.requestedOutput,invocation:{customConfigKeys:Object.keys(s.invocation.customConfig).sort(),keywords:s.invocation.keywords,smartCasing:s.invocation.smartCasing,smartCasingDigitWordBoundary:s.invocation.smartCasingDigitWordBoundary,disableExamples:s.invocation.disableExamples,audiences:s.invocation.audiences,hasReadme:s.invocation.readme!=null,hasSettings:s.invocation.settings!=null,hasApiOverride:s.invocation.apiOverride!=null},payload:o.get(s.targetId)}))}},i)}`)}function Twg(e,t,r){if(!(t instanceof S5t)){e.logger.debug(`sdk-gen-api submission failed before receiving an HTTP response: ${Qyi(t instanceof Error?{name:t.name,message:t.message}:{error:String(t)},r)}`);return}e.logger.debug(`sdk-gen-api submission HTTP failure: ${Qyi({status:t.response?.status??t.status,statusText:t.response?.statusText,code:t.code,responseBody:t.response?.data},r)}`)}function CXu(e){return e.length<=12?e:`${e.slice(0,12)}...`}function Qyi(e,t){let r;try{r=typeof e=="string"?e:JSON.stringify(e)}catch(i){r=i instanceof Error?`Failed to serialize debug value: ${i.message}`:String(e)}let n=pq(r,t);return n.length>hws?`${n.slice(0,hws)}... [truncated ${n.length-hws} bytes]`:n}function Owg(e,t){switch(t.level.toLowerCase()){case"error":e.logger.error(t.message);return;case"warn":case"warning":e.logger.warn(t.message);return;case"debug":case"trace":e.logger.debug(t.message);return;default:e.logger.info(t.message)}}function Pwg(e,t){return t.type!=="guest"||e.status!==409||!/idempotency key/i.test(e.message)?"":" This run is identical to an earlier guest build that has already ended. Change the input (for example --version), or start a fresh guest session with --new-session."}function xXu(e,t){if(!(e instanceof S5t))return new Nyi(pq(e instanceof Error?e.message:"Unknown submission error",t),void 0,void 0);let r=Bwg(e,t);return new Nyi(r??pq(e.message,t),e.response?.status??e.status,e.code)}function Bwg(e,t){let r=e.response?.data;if(typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")return pq(r.message,t);if(r!=null)return`sdk-gen-api response body: ${Qyi(r,t)}`}function Dwg(e){return(e?.targets??[]).flatMap(t=>t.registry==="npm"||t.registry==="crates"?[t.token]:t.registry==="pypi"?[t.username,t.password]:[t.username,t.password,...t.signature!=null?[t.signature.keyId,t.signature.password,t.signature.secretKey]:[]])}function Rwg(e,t){return{...e,targets:e.targets.map(r=>({...r,logs:r.logs.map(n=>({...n,message:pq(n.message,t)})),...r.error==null?{}:{error:{...typeof r.error.code=="string"?{code:pq(r.error.code,t)}:{},message:pq(r.error.message,t)}},...r.publication==null?{}:r.publication.status==="success"?{publication:{...r.publication,publishTarget:{...r.publication.publishTarget,identifier:lws(r.publication.publishTarget.identifier,t)}}}:{publication:{...r.publication,publishTarget:{...r.publication.publishTarget,identifier:lws(r.publication.publishTarget.identifier,t)},error:kwg(r.publication.error,t)}}}))}}function kwg(e,t){let{reason:r,detail:n,...i}=e,o=typeof n=="string"?pq(n,t).trim():void 0,s=typeof r=="string"&&dwg.test(r)&&pq(r,t)===r?r:void 0;return{...i,message:pq(e.message,t),...s!=null?{reason:s}:{},...o!=null&&o.length>0?{detail:o}:{}}}function Fwg(e){let t=`sdk-gen-api publication failed (${e.code}): ${e.message}`;return e.detail==null||e.detail===e.message?t:e.reason!=null?`${t}: ${e.detail} [${e.reason}]`:`${t}: ${e.detail}`}function Nwg(e){for(let t of e){let{generatorInvocation:r}=t,n=r.language??bv(r.name);n==null&&t.context.failAndThrow(`Cannot submit SDK generation to sdk-gen-api: generator language is unknown for ${r.name}`,void 0,{code:T.Code.ConfigError});let i;try{i=jwg(t,n)}catch(o){if(!(o instanceof Wse))throw o;t.context.failAndThrow(MZt(o),void 0,{code:T.Code.ConfigError,instructionsTopic:LZt(o)})}i.payloadKind!==t.payload.payloadKind&&t.context.failAndThrow(`Cannot submit SDK generation to sdk-gen-api: selected route payload ${i.payloadKind} does not match participant payload ${t.payload.payloadKind}`,void 0,{code:T.Code.ConfigError})}}function jwg(e,t){let{generatorInvocation:r,sdkGenApiRoute:n}=e;if(n?.requestedVersion==null){if(n!=null){if(!kyi(n,r.version))throw JXu(n,r.version);return ZGe({generatorId:r.name,language:t,configKind:n.configKind,versionSource:n.versionSource})}return XGe({generatorId:r.name,language:t,requestedVersion:r.version,configKind:e.payload.payloadKind==="fern-runtime-bundle"?"legacy-fern":"sdk-config-v1"})}return XGe({generatorId:r.name,language:t,requestedVersion:n.requestedVersion,configKind:n.configKind})}function MZt(e){let t=[e.code,`generator=${e.generatorId}`,`language=${e.language}`,`requestedVersion=${e.requestedVersion}`,`cutoverVersion=${e.cutoverVersion??"n/a"}`,`receivedConfigKind=${String(e.receivedConfigKind)}`,`expectedConfigKind=${e.expectedConfigKind??"n/a"}`,`expectedLanguage=${e.expectedLanguage??"n/a"}`,`retryable=${e.retryable}`,`recommendedAction=${e.recommendedAction}`].join("; "),r=e.recommendedAction==="USE_SDK_CONFIG_V1"?" Run `fern sdk migrate`, then pass the generated document with `fern generate --sdk-config <path>` before using this generator version.":"";return`Cannot submit SDK generation to sdk-gen-api: ${e.message} [${t}].${r}`}function LZt(e){return e.recommendedAction==="USE_SDK_CONFIG_V1"?eo.SdksMigrate:void 0}function KXu(e,t,r){if(e==null)return t.version;if(e.requestedVersion!=null)return e.requestedVersion;if(!kyi(e,t.version))throw JXu(e,t.version);return r}function JXu(e,t){return new Error(`An unpinned sdk-gen-api route does not match its generator version representation: invocationVersion=${JSON.stringify(t)}; configKind=${e.configKind}; versionSource=${e.requestedVersion==null?e.versionSource:"pinned"}`)}function gws(e,t,r){return KXu(e,t,r)??uwg}function zwg(e,t){let r=fwg.compare(e.targetIdSeed??"",t.targetIdSeed??"");if(r!==0)return r;let n=e.generatorInvocation.name.localeCompare(t.generatorInvocation.name);if(n!==0)return n;let i=gws(e.sdkGenApiRoute,e.generatorInvocation).localeCompare(gws(t.sdkGenApiRoute,t.generatorInvocation));return i!==0?i:(e.sdkVersion??"").localeCompare(t.sdkVersion??"")}function Qwg(e,t){e.length>WSt&&t.context.failAndThrow(`sdk-gen-api supports at most ${WSt} target payloads per build; received ${e.length}`,void 0,{code:T.Code.ConfigError}),t.specsTarGzBuffer.length>owg&&t.context.failAndThrow(`sdk-gen-api source archive is ${fq(t.specsTarGzBuffer.length)}, exceeding the 25 MiB compressed limit`,void 0,{code:T.Code.ConfigError});let r=e.findIndex(s=>s.payload.body.length>(s.payload.payloadKind==="fern-runtime-bundle"?yXu:bXu));if(r>=0){let s=e[r],a=s?.payload.payloadKind==="fern-runtime-bundle"?yXu:bXu;t.context.failAndThrow(`sdk-gen-api ${SXu(s,r)} is ${fq(s?.payload.body.length??0)}, exceeding the ${fq(a)} upload limit`,void 0,{code:T.Code.ConfigError})}let n=e.reduce((s,a)=>s+a.payload.body.length,t.specsTarGzBuffer.length);n>BXu&&t.context.failAndThrow(`sdk-gen-api source archive and target payloads total ${fq(n)}, exceeding the 50 MiB in-memory upload limit; reduce the source archive size, target payload size, or number of targets`,void 0,{code:T.Code.ConfigError});let i=e.reduce((s,a)=>a.payload.payloadKind==="fern-runtime-bundle"?s+a.payload.body.length:s,0);i>awg&&t.context.failAndThrow(`sdk-gen-api runtime bundles total ${fq(i)}, exceeding the 25 MiB compressed limit; reduce the number or size of targets`,void 0,{code:T.Code.ConfigError}),wXu({buffer:t.specsTarGzBuffer,maxBytes:swg,label:"source archive",context:t.context});let o=0;for(let[s,a]of e.entries())o+=a.payload.payloadKind==="fern-runtime-bundle"?wXu({buffer:a.payload.body,maxBytes:cwg,label:SXu(a,s),context:t.context}):a.payload.body.length,o>PXu&&t.context.failAndThrow(`sdk-gen-api target payloads total ${fq(o)}, exceeding the 100 MiB decoded limit; reduce the number or size of targets`,void 0,{code:T.Code.ConfigError})}function SXu(e,t){return`${e?.payload.payloadKind??"target payload"} ${e?.targetIdSeed??t.toString()}`}function wXu({buffer:e,maxBytes:t,label:r,context:n}){let i;try{i=(0,OXu.gunzipSync)(e,{maxOutputLength:t+1})}catch(o){return Mwg(o)?n.failAndThrow(`sdk-gen-api ${r} exceeds the ${fq(t)} decompressed limit`,void 0,{code:T.Code.ConfigError}):n.failAndThrow(`sdk-gen-api ${r} is malformed gzip; regenerate it and retry`,o,{code:T.Code.ConfigError})}return i.length>t?n.failAndThrow(`sdk-gen-api ${r} is ${fq(i.length)} decompressed, exceeding the ${fq(t)} decompressed limit`,void 0,{code:T.Code.ConfigError}):i.length}function Mwg(e){return e instanceof Error&&"code"in e&&e.code==="ERR_BUFFER_TOO_LARGE"}function fq(e){return`${(e/(1024*1024)).toFixed(2)} MiB`}function Lwg(e){return`${(e/1024).toFixed(2)} KiB`}function _wg(e,t){let r=e.targets.find(n=>n.targetId===t);return r?.status==="failed"||r?.status==="succeeded"}function Uwg({participant:e,status:t,buildId:r}){if(e.token.type!=="guest"||!t.targets.some(i=>i.status==="succeeded"&&i.result?.artifactUrl!=null))return;let n=Cqu({claimUrl:e.token.claimUrl,buildId:r});e.context.logger.info(n!=null?`Build ${r} is kept for 7 days: ${n} (claiming the session moves it into your organization)`:`Build ${r} is kept for 7 days (claiming the session moves it into your organization)`)}async function Vwg(e,t,r,n){let i=r.targets.find(u=>u.targetId===t);if(i==null)return e.context.failAndThrow("sdk-gen-api response did not contain the requested target",void 0,{code:T.Code.InternalError});if(i.status==="failed")return i.publication?.status==="failure"?e.context.failAndThrow(Fwg(i.publication.error),void 0,{code:T.Code.ContainerError}):e.context.failAndThrow(Gwg(i.error),void 0,{code:T.Code.ContainerError});if(i.status!=="succeeded")return e.context.failAndThrow(`sdk-gen-api build ended with status ${r.status} while target ${i.targetId} remained ${i.status}`,void 0,{code:T.Code.InternalError});let o=e.sdkVersion!=null&&(0,NZt.isAutoVersion)(e.sdkVersion),s=o&&i.publication?.status==="success"&&i.publication.output.noChangesDetected===!0&&i.result?.actualVersion==null,a=i.result?.artifactUrl;if(a==null&&!s)return e.context.failAndThrow("sdk-gen-api target completed without an artifact URL",void 0,{code:T.Code.InternalError});a==null?e.context.logger.info("No changes detected; there is no SDK preview to download."):e.absolutePathToPreview!=null?await Ryi({s3PreSignedReadUrl:a,absolutePathToLocalOutput:ke(e.absolutePathToPreview,Ee.of(Squ(e.generatorInvocation.name,Kwg(e.generatorInvocation)))),context:e.context,skipFernignore:e.skipFernignore}):e.absolutePathToLocalOutputArchive!=null?await uXu({s3PreSignedReadUrl:a,absolutePathToLocalOutput:e.absolutePathToLocalOutputArchive,context:e.context}):e.generatorInvocation.absolutePathToLocalOutput!=null&&await Ryi({s3PreSignedReadUrl:a,absolutePathToLocalOutput:e.generatorInvocation.absolutePathToLocalOutput,context:e.context,skipFernignore:e.skipFernignore});let c=i.result?.actualVersion??(o?void 0:e.sdkVersion),l=e.autoVersionPreviewOutput!=null?{pullRequestUrl:void 0,noChangesDetected:i.publication?.status==="success"&&i.publication.output.noChangesDetected===!0?!0:void 0}:qwg(e,i,n);return o&&c!=null&&e.context.logger.info(`AUTO versioning picked new version: ${c}`),{createdSnippets:!1,snippetsS3PreSignedReadUrl:void 0,actualVersion:c,...l,publishTarget:c==null||e.autoVersionPreviewOutput!=null?void 0:Jwg(i,c)}}function Gwg(e){let t=e?.message||"sdk-gen-api generation failed";return e?.code!=null&&e.code!==""?`${e.code}: ${t}`:t}function qwg(e,t,r){if(r?.type!=="github")return{pullRequestUrl:void 0,noChangesDetected:void 0};let{publication:n}=t;if(n?.status!=="success"||n.publishTarget.type!=="github")return e.context.failAndThrow(`sdk-gen-api reported the build as succeeded but did not confirm the GitHub delivery to ${r.repository}`,void 0,{code:T.Code.InternalError});let i=Wwg(n.output.pullRequestUrl),o=n.output.noChangesDetected===!0,s={pullRequestUrl:o?void 0:i,noChangesDetected:o?!0:void 0},a=n.output.pullRequestUrl!=null&&i==null;return Hwg(e.context.logger,r,s,a),s}function Wwg(e){let t=e==null?void 0:YXu(e);if(t==null)return;let{origin:r,pathname:n}=new URL(t);return`${r}${n}`}function Hwg(e,{repository:t,mode:r},{pullRequestUrl:n,noChangesDetected:i},o){if(i){e.info(`No changes detected for ${t}; nothing was delivered to GitHub.`);return}if(n!=null){e.info(`Pull request: ${n}`);return}if(o){e.warn(`sdk-gen-api returned a pull request link for ${t} that was not a safe HTTPS URL.`);return}r==="pull-request"&&e.warn(`sdk-gen-api did not return a pull request link for ${t}.`)}function Kwg(e){return e.sdkConfigTargetIndex}function Jwg(e,t){if(e.publication?.status!=="success")return;let r=e.publication.publishTarget.type,n=e.publication.publishTarget.identifier,i=YXu(n);switch(r){case"npm":return{registry:r,label:"npm",version:t,identifier:n,...i!=null?{url:i}:{}};case"pypi":return{registry:r,label:"PyPI",version:t,identifier:n,...i!=null?{url:i}:{}};case"crates":return{registry:r,label:"crates.io",version:t,identifier:n,...i!=null?{url:i}:{}};case"maven":return{registry:r,label:"Maven Central",version:t,identifier:n,...i!=null?{url:i}:{}};case"github":case"unsupported":return}}function YXu(e){try{let t=new URL(e);return t.protocol==="https:"&&t.username.length===0&&t.password.length===0?e:void 0}catch{return}}function Ywg(e){let t=e[0];if(t==null)return;let r=(0,Hse.createHash)("sha256").update(t.specsTarGzBuffer).digest("hex");for(let n of e.slice(1)){let i=(0,Hse.createHash)("sha256").update(n.specsTarGzBuffer).digest("hex");if(n.apiName!==t.apiName||n.organization!==t.organization||n.token.value!==t.token.value||i!==r)throw new Error("Fern sdk-gen-api batch targets must share API, organization, token, and sources")}}function Xwg({apiName:e,organization:t,cliVersion:r,specsTarGzBuffer:n,targets:i}){if(i.length===0)throw new Error("Cannot create an empty Fern sdk-gen-api request");let o=[],s=i.map(({targetIdSeed:f,sourceSpecIndexes:m},g)=>{if(m==null)return o.some(b=>b.id==="default")||o.push({id:"default",specIndexes:"all"}),"default";let A=`target-${f??g.toString()}`;return o.push({id:A,specIndexes:m}),A}),a=i.map(({generatorInvocation:f,resolvedGeneratorVersion:m,sdkGenApiRoute:g,sdkName:A,sdkVersion:b,apiVersion:I,targetIdSeed:C,audiences:x,payload:S,requestedOutput:B,autoVersionPreviewOutput:D,githubOptions:R},O)=>{let z=bv(f.name);if(z==null)throw new Error(`Unsupported Fern SDK generator: ${f.name}`);let X=XSt(f,R),ee=hwg(B??X.requestedOutput,R),te=S.payloadKind==="fern-runtime-bundle"?X.package:S.package,ae=KXu(g,f,m),ce=gws(g,f,m);return{targetId:(0,Hse.createHash)("sha256").update(`${e}:${f.name}:${ce}:${C??O.toString()}`).digest("hex").slice(0,20),apiInputId:s[O]??"default",language:z,sdk:{name:A??e,...b!=null?{version:b}:{},...I!=null?{apiVersion:I}:{}},fernGenerator:{id:f.name,...ae!=null?{version:ae}:{}},payloadKind:S.payloadKind,...te!=null?{package:te}:{},invocation:{customConfig:Kee(f.config)??{},keywords:f.keywords??[],smartCasing:f.smartCasing,smartCasingDigitWordBoundary:f.smartCasingDigitWordBoundary,disableExamples:f.disableExamples,...x!=null?{audiences:x}:{},...f.readme!=null?{readme:f.readme}:{},...f.settings!=null?{settings:f.settings}:{},...f.apiOverride!=null?{apiOverride:f.apiOverride}:{}},requestedOutput:ee,...D!=null?{autoVersionPreview:{github:D}}:{}}}),c=i.map(f=>(0,Hse.createHash)("sha256").update(f.payload.body).digest("hex")),l=JSON.stringify({protocolVersion:2,organization:t,apiName:e,apiInputs:o,targets:a,payloadHashes:c,sourceHash:(0,Hse.createHash)("sha256").update(n).digest("hex")}),u=a.some(f=>f.requestedOutput.type==="publish")?Zwg(l):void 0,p=a.some(f=>f.sdk.version==null||(0,NZt.isAutoVersion)(f.sdk.version))?(0,Hse.randomUUID)():void 0,d=(0,Hse.createHash)("sha256").update(n).update(JSON.stringify({protocolVersion:2,organization:t,apiName:e,credentialSetId:u,apiInputs:o,targets:a,payloadHashes:c,...p!=null?{dynamicVersionRunId:p}:{}})).digest("hex");return{protocolVersion:2,apiName:e,...r?{cliVersion:r}:{},idempotencyKey:d,...u!=null?{credentialSetId:u}:{},apiInputs:o,targets:a}}function Zwg(e){let t=(0,Hse.createHash)("sha256").update(e).digest().subarray(0,16);t[6]=(t[6]??0)&15|128,t[8]=(t[8]??0)&63|128;let r=t.toString("hex");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}Ec();yo();gt();zn();function e9e({apiName:e,organization:t,generatorInvocation:r}){let n=$wg(r);return{apiName:e,organization:t,customConfig:Kee(r.config),outputConfig:n??ar.GeneratorOutputConfig.local()}}function $wg(e){let t=e.outputMode;switch(t.type){case"downloadFiles":return ar.GeneratorOutputConfig.local();case"publishV2":return e1g({publish:t.publishV2,version:e.version});case"githubV2":return t1g({github:t.githubV2,language:e.language,version:e.version});case"publish":case"github":return;default:Ze(t)}}function e1g({publish:e,version:t}){switch(e.type){case"npmOverride":{let r=e.npmOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.npm({version:t,packageName:r.packageName,repoUrl:void 0}))}case"mavenOverride":{let r=e.mavenOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.maven({version:t,coordinate:r.coordinate,repoUrl:void 0}))}case"pypiOverride":{let r=e.pypiOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.pypi({version:t,packageName:r.coordinate,repoUrl:void 0}))}case"rubyGemsOverride":{let r=e.rubyGemsOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.rubygems({version:t,packageName:r.packageName,repoUrl:void 0}))}case"nugetOverride":{let r=e.nugetOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.nuget({version:t,packageName:r.packageName,repoUrl:void 0}))}case"cratesOverride":{let r=e.cratesOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.crates({version:t,packageName:r.packageName,repoUrl:void 0}))}case"postman":return;default:Ze(e)}}function t1g({github:e,version:t,language:r}){let n=r1g({owner:e.owner,repo:e.repo});if(r===Qr.GenerationLanguage.GO)return ar.GeneratorOutputConfig.publish(ar.PublishInfo.go({version:t,repoUrl:n}));if(r===Qr.GenerationLanguage.SWIFT)return ar.GeneratorOutputConfig.publish(ar.PublishInfo.swift({version:t,repoUrl:n}));let i=e.publishInfo;if(i!=null)switch(i.type){case"maven":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.maven({version:t,coordinate:i.coordinate,repoUrl:n}));case"npm":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.npm({version:t,packageName:i.packageName,repoUrl:n}));case"pypi":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.pypi({version:t,packageName:i.packageName,repoUrl:n}));case"rubygems":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.rubygems({version:t,packageName:i.packageName,repoUrl:n}));case"nuget":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.nuget({version:t,packageName:i.packageName,repoUrl:n}));case"crates":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.crates({version:t,packageName:i.packageName,repoUrl:n}));case"postman":return;default:Ze(i)}}function r1g({owner:e,repo:t}){return`https://github.com/${e}/${t}`}Wn();A3();Pt();KU();var iy=Ae(xip(),1),DL=Ae(eA(),1),Tip=Ae(require("path"),1),PFg="0.0.1";function l$t(e){if(e.raw?.github!=null&&typeof e.raw.github=="object"&&"license"in e.raw.github){let t=e.raw.github;if(t.license!=null){if(typeof t.license=="string")return{type:"basic",value:t.license};if(typeof t.license=="object"&&"custom"in t.license)return{type:"custom",value:t.license.custom}}}if(e.raw?.metadata?.license!=null){let t=e.raw.metadata.license;if(typeof t=="string")return{type:"basic",value:t};if(typeof t=="object"&&"custom"in t)return{type:"custom",value:t.custom}}}function BFg(e,t){let r=l$t(e);if(r!=null){if(r.type==="basic"){if(r.value==="MIT"||r.value==="Apache-2.0")return iy.FernGeneratorExec.LicenseConfig.basic({id:r.value==="MIT"?iy.FernGeneratorExec.LicenseId.Mit:iy.FernGeneratorExec.LicenseId.Apache2})}else if(r.type==="custom")return iy.FernGeneratorExec.LicenseConfig.custom({filename:Tip.basename(r.value)})}}function aEi(e,t={}){let r=t.omitPublishCredentials??!1;return e!=null?qr.GithubPublishInfo._visit(e,{npm:n=>{let i=(n.token??"").trim(),o=U1s(i),s=i!=="";return iy.FernGeneratorExec.GithubPublishInfo.npm({registryUrl:n.registryUrl,packageName:n.packageName,tokenEnvironmentVariable:(0,DL.EnvironmentVariable)(r?o!=null?"<USE_OIDC>":"":o!=null?"<USE_OIDC>":i.startsWith("${")&&i.endsWith("}")?i.slice(2,-1).trim():""),shouldGeneratePublishWorkflow:o!=null||s})},maven:n=>iy.FernGeneratorExec.GithubPublishInfo.maven({registryUrl:n.registryUrl,coordinate:n.coordinate,usernameEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.credentials?.username??""),passwordEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.credentials?.password??""),signature:n.signature!=null&&!r?{keyIdEnvironmentVariable:(0,DL.EnvironmentVariable)(n.signature.keyId??""),passwordEnvironmentVariable:(0,DL.EnvironmentVariable)(n.signature.password??""),secretKeyEnvironmentVariable:(0,DL.EnvironmentVariable)(n.signature.secretKey??"")}:void 0}),pypi:n=>{let i=(n.credentials?.password??"").trim(),o=U1s(i),s=n.credentials!=null;return iy.FernGeneratorExec.GithubPublishInfo.pypi({registryUrl:n.registryUrl,packageName:n.packageName,usernameEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":"PYPI_USERNAME"),passwordEnvironmentVariable:(0,DL.EnvironmentVariable)(r?o!=null?"OIDC":"":o!=null?"OIDC":"PYPI_PASSWORD"),shouldGeneratePublishWorkflow:o!=null||s,pypiMetadata:n.pypiMetadata})},rubygems:n=>iy.FernGeneratorExec.GithubPublishInfo.rubygems({registryUrl:n.registryUrl,packageName:n.packageName,apiKeyEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.apiKey??"")}),postman:n=>iy.FernGeneratorExec.GithubPublishInfo.postman({apiKeyEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.apiKey??""),workspaceIdEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.workspaceId??"")}),nuget:n=>{let i=(n.apiKey??"").trim(),o=U1s(i);return iy.FernGeneratorExec.GithubPublishInfo.nuget({registryUrl:n.registryUrl,packageName:n.packageName,apiKeyEnvironmentVariable:(0,DL.EnvironmentVariable)(r?o!=null?"<USE_OIDC>":"":o!=null?"<USE_OIDC>":i.startsWith("${")&&i.endsWith("}")?i.slice(2,-1).trim():""),shouldGeneratePublishWorkflow:o!=null?!0:void 0})},crates:n=>iy.FernGeneratorExec.GithubPublishInfo.crates({registryUrl:n.registryUrl,packageName:n.packageName,tokenEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.token??"")}),_other:()=>{}}):void 0}function U1s(e){if(e==="OIDC"||e==="<USE_OIDC>")return e}function xwt({generatorInvocation:e,customConfig:t,workspaceName:r,organization:n,outputVersion:i=PFg,absolutePathToSnippet:o,absolutePathToSnippetTemplates:s,absolutePathToFernConfig:a,writeUnitTests:c,generateOauthClients:l,generatePaginatedClients:u,whiteLabel:p,publishToRegistry:d,omitPublishCredentials:f,paths:m}){let g=BFg(e,a),{snippetPath:A,snippetTemplatePath:b,irPath:I,outputDirectory:C}=m,x=e.outputMode._visit({publish:B=>{if(d===!0){let D=RFg(B,f===!0);return{...wip(i,D,m),snippetFilepath:A,publishingMetadata:e.publishMetadata}}return{...Sip(i,B,e,m),snippetFilepath:A,publishingMetadata:e.publishMetadata}},publishV2:B=>{if(d===!0){let D=kFg(B,f===!0);return{...wip(i,D,m),snippetFilepath:A,publishingMetadata:e.publishMetadata}}return{...Sip(i,B,e,m),snippetFilepath:A,publishingMetadata:e.publishMetadata}},downloadFiles:()=>({mode:iy.FernGeneratorExec.OutputMode.downloadFiles(),path:C,snippetFilepath:A,publishingMetadata:e.publishMetadata}),github:B=>{let D={mode:iy.FernGeneratorExec.OutputMode.github({repoUrl:`https://github.com/${B.owner}/${B.repo}`,version:i,publishInfo:aEi(B.publishInfo,{omitPublishCredentials:f}),installationToken:void 0}),path:C,publishingMetadata:e.publishMetadata};return o!==void 0&&(D.snippetFilepath=A),s!==void 0&&(D.snippetTemplateFilepath=b),D},githubV2:B=>{let D=B._visit({commitAndRelease:O=>`https://github.com/${O.owner}/${O.repo}`,push:O=>`https://github.com/${O.owner}/${O.repo}`,pullRequest:O=>`https://github.com/${O.owner}/${O.repo}`,_other:()=>{throw new T({message:"Encountered unknown github mode",code:T.Code.InternalError})}}),R={mode:iy.FernGeneratorExec.OutputMode.github({repoUrl:D,version:i,publishInfo:aEi(B.publishInfo,{omitPublishCredentials:f})}),path:C,publishingMetadata:e.publishMetadata};return o!==void 0&&(R.snippetFilepath=A),s!==void 0&&(R.snippetTemplateFilepath=b),R},_other:()=>{throw new T({message:"Output type did not match any of the types supported by Fern",code:T.Code.InternalError})}}),S=FFg(e,i);return{irFilepath:I,output:x,publish:S,customConfig:t,workspaceName:r,organization:n,environment:iy.FernGeneratorExec.GeneratorEnvironment.local(),dryRun:!1,whitelabel:p??!1,writeUnitTests:c,generateOauthClients:l,generatePaginatedClients:u,license:g}}function Sip(e,t,r,n){let{outputDirectory:i}=n,o;"registryOverrides"in t?o=t.registryOverrides.maven??t.registryOverrides.npm:o!=null&&(o=t._visit({mavenOverride:a=>a,npmOverride:a=>a,pypiOverride:a=>a,rubyGemsOverride:a=>a,postman:a=>a,nugetOverride:a=>a,cratesOverride:a=>a,_other:()=>{}}));let s="";return r.raw?.github!=null&&(gxe(r.raw.github)?s=Px(r.raw.github.uri).repoUrl:s=r.raw?.github.repository),{mode:iy.FernGeneratorExec.OutputMode.github({repoUrl:s,version:e}),path:i}}function wip(e,t,r){let{outputDirectory:n}=r,{registries:i,registriesV2:o}=DFg(t);return{mode:iy.FernGeneratorExec.OutputMode.publish({registries:i,registriesV2:o,publishTarget:t,version:e}),path:n}}function DFg(e){let t=structuredClone(Oip),r=structuredClone(Pip);if(e==null)return{registries:t,registriesV2:r};switch(e.type){case"npm":t.npm={registryUrl:e.registryUrl,token:e.token,scope:""},r.npm={registryUrl:e.registryUrl,token:e.token,packageName:e.packageName};break;case"maven":t.maven={registryUrl:e.registryUrl,username:e.username,password:e.password,group:"",signature:e.signature},r.maven={registryUrl:e.registryUrl,username:e.username,password:e.password,coordinate:e.coordinate,signature:e.signature};break;case"pypi":r.pypi={registryUrl:e.registryUrl,username:e.username,password:e.password,packageName:e.packageName,pypiMetadata:e.pypiMetadata};break;case"rubygems":r.rubygems={registryUrl:e.registryUrl,apiKey:e.apiKey,packageName:e.packageName};break;case"nuget":r.nuget={registryUrl:e.registryUrl,apiKey:e.apiKey,packageName:e.packageName};break;case"crates":r.crates={registryUrl:e.registryUrl,token:e.token,packageName:e.packageName};break;default:break}return{registries:t,registriesV2:r}}function RFg(e,t){if("registryOverrides"in e){let r=e.registryOverrides;if(r.npm!=null)return iy.FernGeneratorExec.GeneratorPublishTarget.npm({registryUrl:r.npm.registryUrl,token:t?"":r.npm.token,packageName:r.npm.packageName});if(r.maven!=null)return iy.FernGeneratorExec.GeneratorPublishTarget.maven({registryUrl:r.maven.registryUrl,username:t?"":r.maven.username??"",password:t?"":r.maven.password??"",coordinate:r.maven.coordinate??"",signature:void 0})}}function kFg(e,t){return e._visit({npmOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.npm({registryUrl:r.registryUrl,token:t?"":r.token,packageName:r.packageName}):void 0,mavenOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.maven({registryUrl:r.registryUrl,username:t?"":r.username,password:t?"":r.password,coordinate:r.coordinate,signature:t?void 0:r.signature??void 0}):void 0,pypiOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.pypi({registryUrl:r.registryUrl,username:t?"":r.username,password:t?"":r.password,packageName:r.coordinate,pypiMetadata:r.pypiMetadata??void 0}):void 0,rubyGemsOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.rubygems({registryUrl:r.registryUrl,apiKey:t?"":r.apiKey,packageName:r.packageName}):void 0,nugetOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.nuget({registryUrl:r.registryUrl,apiKey:t?"":r.apiKey,packageName:r.packageName}):void 0,cratesOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.crates({registryUrl:r.registryUrl,token:t?"":r.token,packageName:r.packageName}):void 0,postman:r=>iy.FernGeneratorExec.GeneratorPublishTarget.postman({apiKey:t?"":r.apiKey,workspaceId:t?"":r.workspaceId}),_other:()=>{}})}function FFg(e,t){let r=e.outputMode._visit({publish:()=>{},publishV2:()=>{},downloadFiles:()=>{},github:o=>o.publishInfo,githubV2:o=>o._visit({push:s=>s.publishInfo,commitAndRelease:s=>s.publishInfo,pullRequest:s=>s.publishInfo,_other:()=>{}}),_other:()=>{}});if(r==null||r.type!=="pypi")return;let n=(r.credentials?.password??"").trim();if(n!=="OIDC"&&n!=="<USE_OIDC>")return;let i=structuredClone(Pip);return i.pypi={registryUrl:r.registryUrl,username:"__token__",password:"OIDC",packageName:r.packageName,pypiMetadata:r.pypiMetadata},{registries:structuredClone(Oip),registriesV2:i,publishTarget:void 0,version:t}}var Oip={maven:{registryUrl:"",username:"",password:"",group:"",signature:void 0},npm:{registryUrl:"",token:"",scope:""}},Pip={maven:{registryUrl:"",username:"",password:"",coordinate:"",signature:void 0},npm:{registryUrl:"",token:"",packageName:""},pypi:{registryUrl:"",username:"",password:"",packageName:"",pypiMetadata:void 0},rubygems:{registryUrl:"",apiKey:"",packageName:""},nuget:{registryUrl:"",apiKey:"",packageName:""},crates:{registryUrl:"",token:"",packageName:""}};gt();function u$t(e,t){if(Hh(e))return e;switch(t){case"github":return`https://github.com/${e}`;case"gitlab":return`https://gitlab.com/${e}`;case"bitbucket":return`https://bitbucket.org/${e}`;default:Ze(t)}}function p$t(e){return e.language==="mcp"&&e.output?.delivery==="hosted"?{...e,output:{delivery:"zip"}}:e}function V1s(e){let t=e.sdkConfigPath==null?"":`; SDK Config: ${e.sdkConfigPath.join(".")}`;return`[${e.severity}] [${e.code}] ${e.path.join(".")}: ${e.reason}${t}; ${e.suggestedAction}`}function Bip({workspace:e,generatorInvocation:t,audiences:r,replay:n,sourceArchive:i,mapFernGroupToSdkConfig:o}){let s=o({fernWorkspace:e,replay:n,group:{groupName:"sdk-gen-api",audiences:r,generators:[t],reviewers:void 0},source:NFg(i)}),a={...s.sdkConfig,targets:s.sdkConfig.targets.map(p$t)};return{payloadKind:"sdk-config-v1",body:Buffer.from(JSON.stringify(a),"utf8"),diagnostics:s.diagnostics}}function NFg(e){return{specs:e.specIndexes.map((r,n)=>{let i=e.manifest.specs[r];if(i==null)throw new Error(`Fern source manifest does not contain selected index ${r}`);if(!jFg(i))throw new Error(`SDK Config generation does not support Fern source type ${i.type} (${i.specPath})`);return{id:`source-${n}`,type:i.type,path:i.specPath.replace(/^\/+/,""),...i.namespace==null?{}:{namespace:i.namespace},...i.apiImportSettings==null?{}:{apiImportSettings:i.apiImportSettings},...i.overridePaths==null||i.overridePaths.length===0?{}:{overrides:i.overridePaths}}})}}function jFg(e){return e.type==="openapi"||e.type==="asyncapi"||e.type==="graphql"}Ec();yo();nf();gt();c0();nm();F$();gt();hy();ln();Co();function gAe({context:e,violations:t,logWarnings:r,logSummary:n=!0,logBreadcrumbs:i=!0,elapsedMillis:o=0}){let s=[],a={};for(let u of t){let p=JSON.stringify(u.nodePath),d=a[p]??[];d.some(m=>m.message===u.message&&m.nodePath.length===u.nodePath.length&&m.nodePath.every((g,A)=>y6(g,u.nodePath[A]))&&m.relativeFilepath===u.relativeFilepath&&m.severity===u.severity)||(s.push(u),a[p]=[...d,u])}t=s;let c=VFg(t),l=zFg(t);for(let u of Array.from(l.keys()).sort()){let p=l.get(u);if(p){let d=p.violations[0]?.relativeFilepath??"";QFg({logWarnings:r,logBreadcrumbs:i,configRelativeFilepath:d,nodePath:p.nodePath,violations:p.violations,context:e})}}return n&&UFg({context:e,stats:c,logWarnings:r,elapsedMillis:o}),{hasErrors:c.numFatal>0}}function zFg(e){let t={};for(let r of e){let i=r.nodePath.length===0?`file:${r.relativeFilepath}`:`node:${JSON.stringify(r.nodePath)}`;t[i]||(t[i]={nodePath:r.nodePath,violations:[]}),t[i].violations.push(r)}return new Map(Object.entries(t))}function QFg({logWarnings:e,logBreadcrumbs:t,configRelativeFilepath:r,nodePath:n,violations:i,context:o}){let s=MFg(i);if(s==="warning"&&!e)return;let a="",c=i.map(l=>l.severity==="warning"&&!e?null:(a===""&&(a=l.relativeFilepath),`${_Fg(l.severity)} ${l.message}`)).filter(l=>l!=null).join(`
4115
+ `):void 0);for(let i of t.logs.slice(this.lengthOfLastLogs))this.context.logger.log(qSg(i.level),i.message),this.#n==null&&(this.#n=LSg(i.message)??this.#n),this.cachedReplayResult==null&&(this.cachedReplayResult=_Sg(i.message));this.lengthOfLastLogs=t.logs.length;let n=i=>{this.context.logger.debug(`Generated files. ${aAe("View here",i,{fallback:(o,s)=>`${o}: ${s}`})}`)};return await t.status._visit({notStarted:St,running:St,failed:({message:i,s3PreSignedReadUrl:o})=>{o!=null&&n(o),this.context.failAndThrow(i,void 0,{code:T.Code.ContainerError})},finished:async i=>{if(i.s3PreSignedReadUrlV2!=null){n(i.s3PreSignedReadUrlV2);let o=this.getAbsolutePathToLocalOutput();o!=null&&await Ryi({s3PreSignedReadUrl:i.s3PreSignedReadUrlV2,absolutePathToLocalOutput:o,context:this.context})}if(this.absolutePathToPreview==null)for(let o of r)this.context.logger.info(`Published ${o}`);this.#e=!0,this.#t=i.createdSnippets!=null?i.createdSnippets:!1,this.#r=i.snippetsS3PreSignedReadUrl,this.#o=i.pullRequestUrl,this.#s=i.noChangesDetected,i.actualVersion!=null&&(this.#n=i.actualVersion),this.emitReplayTelemetryIfReady()},_other:()=>{this.context.logger.warn("Received unknown update type: "+t.status.type)}}),this.#e?{createdSnippets:this.#t,snippetsS3PreSignedReadUrl:this.#r,actualVersion:this.#n,pullRequestUrl:this.#o,noChangesDetected:this.#s,publishTarget:this.#i}:void 0}getAbsolutePathToLocalOutput(){return this.absolutePathToPreview!=null?ke(this.absolutePathToPreview,Ee.of(_Fe.default.basename(this.generatorInvocation.name))):this.generatorInvocation.absolutePathToLocalOutput}emitReplayTelemetryIfReady(){if(!this.replayEventEmitted&&this.cachedReplayResult!=null&&!this.telemetryContext.disableTelemetry)try{let t={success:!0,steps:{replay:this.cachedReplayResult},warnings:[]},n={...(0,cXu.buildReplayTelemetryProps)({pipelineResult:t,generatorName:this.generatorInvocation.name,generatorVersion:this.generatorInvocation.version,cliVersion:this.telemetryContext.cliVersion,repoUri:USg(this.generatorInvocation),automationMode:this.telemetryContext.automationMode,autoMerge:this.telemetryContext.autoMerge,skipIfNoDiff:this.telemetryContext.skipIfNoDiff,hasBreakingChanges:!1,versionArg:this.telemetryContext.versionArg,versionBump:this.telemetryContext.versionBump,replayConfigEnabled:this.telemetryContext.replayConfigEnabled,noReplayFlag:this.telemetryContext.noReplayFlag,githubMode:VSg(this.generatorInvocation),previewMode:this.absolutePathToPreview!=null,durationMs:Date.now()-this.taskStartedAtMs}),surface:"fiddle",org_id:this.telemetryContext.orgId};this.context.instrumentPostHogEvent({command:"replay",properties:n}),this.context.logger.debug(`[telemetry] replay event sent: ${JSON.stringify(n)}`),this.replayEventEmitted=!0}catch(t){this.context.logger.debug(`[telemetry] failed to send replay event: ${String(t)}`)}}#e=!1;get isFinished(){return this.#e}#t=!1;get createdSnippets(){return this.#t}#r=void 0;get snippetsS3PreSignedReadUrl(){return this.#r}#n=void 0;get actualVersion(){return this.#n}#i=void 0;get publishTarget(){return this.#i}#o=void 0;get pullRequestUrl(){return this.#o}#s=void 0;get noChangesDetected(){return this.#s}},MSg=/Tagging release (v?\d+\.\d+\.\d+(?:-[\w.-]+)?)/;function LSg(e){let t=e.match(MSg);if(t?.[1]!=null)return t[1].replace(/^v/,"")}function _Sg(e){let t=e.match(QSg);if(t?.[1]!=null)try{return JSON.parse(t[1])?.steps?.replay}catch{return}}function USg(e){let t=e.raw?.github;return t==null?"":"uri"in t&&typeof t.uri=="string"?t.uri:"repository"in t&&typeof t.repository=="string"?t.repository:""}function VSg(e){let t=e.raw?.github;if(t!=null&&"mode"in t){if(t.mode==="pull-request")return"pull-request";if(t.mode==="commit-and-release")return"commit-and-release"}return"push"}async function Ryi({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r,skipFernignore:n=!1}){try{let i=await WSg(t),o=await HSg(t);!n&&i&&o?await KSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}):!n&&i&&!o?await JSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}):await GSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}),r.logger.info(le.green(`Downloaded to ${t}`))}catch(i){r.failAndThrow("Failed to download files",i,{code:T.Code.NetworkError})}}async function uXu({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){try{let n=await Ld.get(e,{responseType:"stream",timeout:6e4,signal:AbortSignal.timeout(aws)});await(0,WN.mkdir)(_Fe.default.dirname(t),{recursive:!0}),await(0,Byi.pipeline)(n.data,(0,RZt.createWriteStream)(t)),r.logger.info(le.green(`Downloaded to ${t}`))}catch(n){r.failAndThrow("Failed to download archive",n,{code:T.Code.NetworkError})}}var aws=300*1e3;async function GSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await Ld.get(e,{responseType:"stream",timeout:6e4,signal:AbortSignal.timeout(aws)}),n=await Dyi.default.dir({prefix:"fern",unsafeCleanup:!0}),i=_Fe.default.join(n.path,"output.zip");await(0,Byi.pipeline)(r.data,(0,RZt.createWriteStream)(i)),await sws(t),await(0,WN.mkdir)(t,{recursive:!0}),await dXu(i,t)}async function sws(e){await Gt(e)&&(await pXu(e),await(0,WN.rm)(e,{recursive:!0,force:!0}))}async function pXu(e){try{let t=await(0,WN.readdir)(e,{withFileTypes:!0});for(let r of t){let n=Xt.of(_Fe.default.join(e,r.name));r.isDirectory()&&await pXu(n);try{await(0,WN.chmod)(n,493)}catch{}}await(0,WN.chmod)(e,493)}catch{}}function qSg(e){switch(e){case"DEBUG":return Un.Debug;case"INFO":return Un.Info;case"WARN":return Un.Warn;case"ERROR":return Un.Error;default:return Un.Info}}async function WSg(e){let t=ke(e,Ee.of(q1));return await Gt(t)}async function HSg(e){let t=ke(e,Ee.of(".git"));return await Gt(t)}async function nY(e,t,r){return(await Qa(r.logger,"git",e,{cwd:t,doNotPipeOutput:!0})).stdout}async function KSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){let n=ke(t,Ee.of(q1)),i=await Gee({absolutePathToFernignore:n});await nY(["rm","-rf","."],t,r),await fXu({s3PreSignedReadUrl:e,outputPath:t}),await nY(["add","."],t,r),await nY(["reset","--",...i],t,r),await nY(["restore","."],t,r)}async function JSg({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){let n=Xt.of((await Dyi.default.dir({})).path),i=ke(t,Ee.of(q1)),o=await Gee({absolutePathToFernignore:i});await(0,WN.cp)(t,n,{recursive:!0}),await nY(["init"],n,r),await nY(["add","."],n,r),await nY(["-c","user.name=fern","-c","user.email=hey@buildwithfern.com","-c","commit.gpgsign=false","commit","--allow-empty","--no-verify","-m","init"],n,r),await nY(["rm","-rf","."],n,r),await fXu({s3PreSignedReadUrl:e,outputPath:n}),await nY(["add","."],n,r),await nY(["reset","--",...o],n,r),await nY(["restore","."],n,r),await sws(ke(n,Ee.of(".git"))),await sws(t),await(0,WN.cp)(n,t,{recursive:!0})}async function fXu({s3PreSignedReadUrl:e,outputPath:t}){let r=await Ld.get(e,{responseType:"stream",timeout:6e4,signal:AbortSignal.timeout(aws)}),n=await Dyi.default.dir({prefix:"fern",unsafeCleanup:!0}),i=_Fe.default.join(n.path,"output.zip");await(0,Byi.pipeline)(r.data,(0,RZt.createWriteStream)(i)),await dXu(i,t)}async function dXu(e,t){return new Promise((r,n)=>{lXu.default.open(e,{lazyEntries:!0},(i,o)=>{if(i||!o){n(i??new Error("Failed to open zip file"));return}o.on("error",n),o.on("end",r),o.on("entry",s=>{let a=_Fe.default.join(t,s.fileName);if(s.fileName.endsWith("/")){(0,WN.mkdir)(a,{recursive:!0}).then(()=>o.readEntry()).catch(n);return}(0,WN.mkdir)(_Fe.default.dirname(a),{recursive:!0}).then(()=>{o.openReadStream(s,(c,l)=>{if(c||!l){n(c??new Error("Failed to open read stream"));return}l.pipe((0,RZt.createWriteStream)(a)).on("finish",()=>o.readEntry()).on("error",n)})}).catch(n)}),o.readEntry()})})}function cws(e){return[...new Set(e.filter(t=>t.length>0))].sort((t,r)=>r.length-t.length)}function pq(e,t){return cws(t).reduce((r,n)=>r.replaceAll(n,"[REDACTED]"),e)}function lws(e,t){return pq(e,t)}var YSg=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function GSt(e){let t=YSg.exec(e);return t===null||t[1]===void 0||t[2]===void 0||t[3]===void 0?null:{core:[t[1],t[2],t[3]],prerelease:t[4]?.split(".")??null}}function mXu(e,t){for(let r=0;r<e.core.length;r+=1){let n=hXu(e.core[r]??"",t.core[r]??"");if(n!==0)return n}return XSg(e.prerelease,t.prerelease)}function XSg(e,t){if(e===null||t===null)return e===t?0:e===null?1:-1;let r=Math.max(e.length,t.length);for(let n=0;n<r;n+=1){let i=e[n],o=t[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;let s=ZSg(i,o);if(s!==0)return s}return 0}function ZSg(e,t){let r=/^\d+$/.test(e),n=/^\d+$/.test(t);return r&&n?hXu(e,t):r!==n?r?-1:1:e===t?0:e<t?-1:1}function hXu(e,t){return e.length!==t.length?e.length<t.length?-1:1:e===t?0:e<t?-1:1}var uws=class extends Error{name="GeneratorConfigPolicyInvariantError";code="INVALID_GENERATOR_CUTOVER_POLICY";generatorId;language;cutoverVersion;retryable=!1;recommendedAction="FIX_GENERATOR_CUTOVER_POLICY";constructor(t,r){super(`Generator ${t} has an invalid cutover version: ${r.cutoverVersion}`),this.generatorId=t,this.language=r.language,this.cutoverVersion=r.cutoverVersion}};function $Sg(e){return new Map(e.map(([t,r])=>{let n=GSt(r.cutoverVersion);if(n===null)throw new uws(t,r);return[t,{...r,parsedCutoverVersion:n}]}))}var ewg=$Sg([["fernapi/fern-typescript",{language:"typescript",cutoverVersion:"4.0.0"}],["fernapi/fern-typescript-sdk",{language:"typescript",cutoverVersion:"4.0.0"}],["fernapi/fern-typescript-node-sdk",{language:"typescript",cutoverVersion:"4.0.0"}],["fernapi/fern-typescript-browser-sdk",{language:"typescript",cutoverVersion:"4.0.0"}],["fernapi/fern-python-sdk",{language:"python",cutoverVersion:"6.0.0"}],["fernapi/fern-java-sdk",{language:"java",cutoverVersion:"5.0.0"}],["fernapi/fern-kotlin-sdk",{language:"kotlin",cutoverVersion:"5.0.0"}],["fernapi/fern-go-sdk",{language:"go",cutoverVersion:"2.0.0"}],["fernapi/fern-csharp-sdk",{language:"csharp",cutoverVersion:"3.0.0"}],["fernapi/fern-php-sdk",{language:"php",cutoverVersion:"3.0.0"}],["fernapi/fern-ruby-sdk",{language:"ruby",cutoverVersion:"2.0.0"}],["fernapi/fern-ruby-sdk-v2",{language:"ruby",cutoverVersion:"2.0.0"}],["fernapi/fern-rust-sdk",{language:"rust",cutoverVersion:"1.0.0"}],["fernapi/fern-swift-sdk",{language:"swift",cutoverVersion:"1.0.0"}],["fernapi/fern-cli",{language:"cli",cutoverVersion:"1.0.0"}],["fernapi/fern-cli-generator",{language:"cli",cutoverVersion:"1.0.0"}],["fernapi/fern-mcp-server",{language:"mcp",cutoverVersion:"0.1.0"}]]);function kZt(e){return ewg.get(e)}var Wse=class extends Error{name="GeneratorConfigCompatibilityError";code;generatorId;language;requestedVersion;cutoverVersion;receivedConfigKind;expectedConfigKind;expectedLanguage;retryable=!1;recommendedAction;constructor(t){super(t.message),this.code=t.code,this.generatorId=t.generatorId,this.language=t.language,this.requestedVersion=t.requestedVersion,this.cutoverVersion=t.cutoverVersion,this.receivedConfigKind=t.receivedConfigKind,this.expectedConfigKind=t.expectedConfigKind,this.expectedLanguage=t.expectedLanguage,this.recommendedAction=t.recommendedAction}};function pws(e){return kZt(e)?.language}function XGe(e){let t=cAe(e),r=e.configKind;if(!rwg(r))throw YGe(e,{code:"INVALID_CONFIG_KIND",message:"Configuration kind must be legacy-fern or sdk-config-v1",cutoverVersion:t.cutoverVersion,expectedLanguage:t.language,expectedConfigKind:t.configKind,recommendedAction:"USE_SUPPORTED_CONFIG_KIND"},r);if(r!==t.configKind){let n=kZt(e.generatorId);throw n===void 0?new Error(`Missing validated generator policy for ${e.generatorId}`):twg(e,n,t.configKind,r)}return t}function cAe(e){let t=kZt(e.generatorId);if(t===void 0)throw YGe(e,{code:"UNKNOWN_GENERATOR",message:`Unknown first-party generator: ${e.generatorId}`,cutoverVersion:null,expectedLanguage:null,expectedConfigKind:null,recommendedAction:"USE_KNOWN_GENERATOR_ID"});if(t.language!==e.language)throw YGe(e,{code:"GENERATOR_LANGUAGE_MISMATCH",message:`Generator ${e.generatorId} targets ${t.language}, not ${e.language}`,cutoverVersion:t.cutoverVersion,expectedLanguage:t.language,expectedConfigKind:null,recommendedAction:"USE_GENERATOR_LANGUAGE"});let r=GSt(e.requestedVersion);if(r===null)throw YGe(e,{code:"INVALID_GENERATOR_VERSION",message:`Generator version must be an exact semantic version: ${e.requestedVersion}`,cutoverVersion:t.cutoverVersion,expectedLanguage:t.language,expectedConfigKind:null,recommendedAction:"USE_EXACT_GENERATOR_VERSION"});let n=mXu(r,t.parsedCutoverVersion)<0,i=n?"legacy-fern":"sdk-config-v1";return{generatorId:e.generatorId,language:t.language,requestedVersion:e.requestedVersion,cutoverVersion:t.cutoverVersion,configKind:i,payloadKind:n?"fern-runtime-bundle":"sdk-config-v1"}}function ZGe({generatorId:e,language:t,configKind:r,versionSource:n}){let i=kZt(e);if(i===void 0)throw YGe({generatorId:e,language:t,requestedVersion:"unpinned"},{code:"UNKNOWN_GENERATOR",message:`Unknown first-party generator: ${e}`,cutoverVersion:null,expectedLanguage:null,expectedConfigKind:null,recommendedAction:"USE_KNOWN_GENERATOR_ID"});if(i.language!==t)throw YGe({generatorId:e,language:t,requestedVersion:"unpinned"},{code:"GENERATOR_LANGUAGE_MISMATCH",message:`Generator ${e} targets ${i.language}, not ${t}`,cutoverVersion:i.cutoverVersion,expectedLanguage:i.language,expectedConfigKind:null,recommendedAction:"USE_GENERATOR_LANGUAGE"});let o={generatorId:e,language:t,cutoverVersion:i.cutoverVersion};if(r==="legacy-fern"){if(n!=="fern-latest")throw new Error("Legacy Fern unpinned routes must use fern-latest as their version source");return{...o,versionSource:n,configKind:r,payloadKind:"fern-runtime-bundle"}}return{...o,versionSource:n,configKind:r,payloadKind:"sdk-config-v1"}}function fws(e){return ZGe({...e,configKind:"sdk-config-v1",versionSource:"sdk-config-omitted"})}function YGe(e,t,r=e.configKind){return new Wse({generatorId:e.generatorId,language:e.language,requestedVersion:e.requestedVersion,receivedConfigKind:r,...t})}function twg(e,t,r,n){let i=r==="legacy-fern";return YGe(e,{code:i?"LEGACY_FERN_CONFIG_REQUIRED":"SDK_CONFIG_V1_REQUIRED",message:i?`Generator ${e.generatorId} ${e.requestedVersion} requires legacy Fern configuration`:`Generator ${e.generatorId} ${e.requestedVersion} requires SDK Config v1`,cutoverVersion:t.cutoverVersion,expectedLanguage:t.language,expectedConfigKind:r,recommendedAction:i?"USE_LEGACY_FERN_CONFIG":"USE_SDK_CONFIG_V1"},n)}function rwg(e){return e==="legacy-fern"||e==="sdk-config-v1"}var iY="latest",dws="__fern_sdk_config_unpinned__";function FZt(e){return e===dws}function mws(e){return e??dws}function kyi(e,t){return e.requestedVersion!=null?!1:e.versionSource==="fern-latest"?t===iY:FZt(t)}var iwg=2e3,gXu=1080*1e3,AXu=6e4,WSt=64,owg=25*1024*1024,swg=25*1024*1024,yXu=5*1024*1024,bXu=25*1024*1024,awg=25*1024*1024,PXu=100*1024*1024,cwg=PXu,BXu=50*1024*1024,lwg=1024*1024,DXu=60*1024*1024,hws=20*1024,uwg="unpinned",pwg=new Set(["localhost","127.0.0.1","[::1]","::1"]),fwg=new Intl.Collator("en",{numeric:!0});function RXu(e,t){return t?{type:"download"}:e}var dwg=/^[a-z][a-z0-9_]{0,63}$/,Nyi=class extends Error{status;code;constructor(t,r,n){super(t),this.name="FernSdkGenApiSubmissionError",this.status=r,this.code=n}},jZt="use-sdk-gen-api",HSt="FERN_USE_SDK_GEN_API";function KSt(){let e=process.env[HSt]?.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}function JSt(e){let t=KSt();return t!=null?Promise.resolve(t):Een().isEnabled(jZt,kXu(e))}function Aws(e){let t=KSt();return t??Een().getCachedValue(jZt,kXu(e))}async function zZt({organization:e,generatorNames:t}){let r=[...new Set(t)],n=await Promise.all(r.map(async i=>{try{return await JSt({organization:e,generatorName:i})}catch{return!1}}));return new Map(r.map((i,o)=>[i,n[o]===!0]))}function kXu({organization:e,generatorName:t}){let r=bv(t);return{org:e,generator:t,...r!=null?{language:r}:{}}}var mwg=new Set(["fernapi/fern-mcp-server"]);function $Ge(e){return mwg.has(e)}function QZt({generatorName:e,version:t}){let r=bv(e);return r==null||GSt(t)==null?!1:cAe({generatorId:e,language:r,requestedVersion:t}).configKind==="sdk-config-v1"}function UFe({generatorName:e,version:t,usesSdkConfig:r}){if(!$Ge(e)&&!(!r&&!QZt({generatorName:e,version:t})))return KSt()!==!1}function YSt(e){return $Ge(e)}function Kse(){let e=process.env.FERN_SDK_GEN_API_ORIGIN??"https://sdk-gen.postman.co";if(e==null)return;let t;try{t=new URL(e)}catch{throw new Error("FERN_SDK_GEN_API_ORIGIN must be a valid URL")}if(t.username.length>0||t.password.length>0)throw new Error("FERN_SDK_GEN_API_ORIGIN must not contain credentials");let r=t.protocol==="http:"&&pwg.has(t.hostname);if(t.protocol!=="https:"&&!r)throw new Error("FERN_SDK_GEN_API_ORIGIN must use HTTPS unless it targets localhost");return t.toString().replace(/\/$/,"")}function bv(e){return pws(e)}function FXu(e,t="legacy-fern"){let r=bv(e.name);if(r!=null)return e.version===iY&&t==="legacy-fern"?ZGe({generatorId:e.name,language:e.language??r,configKind:t,versionSource:"fern-latest"}):XGe({generatorId:e.name,language:e.language??r,requestedVersion:e.version,configKind:t})}function XSt(e,t){let r=e.outputMode;switch(r.type){case"downloadFiles":return{requestedOutput:{type:"download"}};case"github":return EXu({owner:r.owner,repo:r.repo,branch:r.branch,mode:r.makePr===!0?"pull-request":"release",license:r.license,publishInfo:r.publishInfo,githubOptions:t});case"githubV2":{let n=r.githubV2;return EXu({owner:n.owner,repo:n.repo,host:n.host,branch:n.branch,mode:n.type==="pullRequest"?"pull-request":n.type==="push"?"push":"release",reviewers:n.type==="pullRequest"?gwg(n.reviewers):void 0,license:n.license,publishInfo:n.publishInfo,workflows:n.workflows,githubOptions:t})}case"publishV2":{let n=Awg(r.publishV2);return{...n.package!=null?{package:n.package}:{},requestedOutput:{type:"publish",publish:n.publish}}}case"publish":{let n=Iwg(e,r.registryOverrides);return{...n.package!=null?{package:n.package}:{},requestedOutput:{type:"publish",publish:n.publish}}}}}function EXu({owner:e,repo:t,host:r,branch:n,mode:i,reviewers:o,license:s,publishInfo:a,workflows:c,githubOptions:l}){let u=a!=null?ywg(a):void 0;return{...u?.package!=null?{package:u.package}:{},requestedOutput:{type:"github",repository:`${e}/${t}`,...r!=null?{host:r}:{},...n!=null?{branch:n}:{},mode:i,...o!=null?{reviewers:o}:{},...s!=null?{license:s}:{},...u!=null?{publish:u.publish}:{},...c===!1?{workflows:!1}:{},...l}}}function hwg(e,t){return e.type==="github"&&t!=null?{...e,...t}:e}function gwg(e){if(e==null)return;let t=e.filter(n=>n.type==="team").map(n=>n.name),r=e.filter(n=>n.type==="user").map(n=>n.name);if(!(t.length===0&&r.length===0))return{...t.length>0?{teams:t}:{},...r.length>0?{users:r}:{}}}function Awg(e){switch(e.type){case"npmOverride":return yws(e.npmOverride);case"mavenOverride":return bws(e.mavenOverride);case"pypiOverride":return NXu(e.pypiOverride);case"rubyGemsOverride":return qSt("rubygems",e.rubyGemsOverride);case"nugetOverride":return qSt("nuget",e.nugetOverride);case"cratesOverride":return qSt("crates",e.cratesOverride);case"postman":throw new Error("sdk-gen-api does not support Postman collection publication as an SDK output")}}function ywg(e){switch(e.type){case"npm":return yws(e);case"maven":return bws(e);case"pypi":return NXu(e);case"rubygems":return qSt("rubygems",e);case"nuget":return qSt("nuget",e);case"crates":return qSt("crates",e);case"postman":throw new Error("sdk-gen-api does not support Postman collection publication as an SDK output")}}function yws(e){return{...e?.packageName?{package:{packageName:e.packageName}}:{},publish:{registry:"npm",...e?.registryUrl?{url:e.registryUrl}:{}}}}function NXu(e){let t=e!=null&&"coordinate"in e?e.coordinate:e?.packageName;return{...t?{package:{packageName:t}}:{},publish:{registry:"pypi",...e?.registryUrl?{url:e.registryUrl}:{}}}}function bws(e){let t=e?.coordinate!=null?Ewg(e.coordinate):void 0;return{...t!=null?{package:t}:{},publish:{registry:"maven",...e?.registryUrl?{url:e.registryUrl}:{}}}}var bwg=new Set(["OIDC","<USE_OIDC>"]);function qSt(e,t){let r=e==="nuget"||e==="rubygems",n=r&&t?.apiKey!=null&&bwg.has(t.apiKey),i=r&&!n?yAi(t?.apiKey):void 0;return{...t?.packageName?{package:{packageName:t.packageName}}:{},publish:{registry:e,...t?.registryUrl?{url:t.registryUrl}:{},...i!=null?{apiKeyEnvironmentVariable:i}:{},...n?{trustedPublishing:!0}:{}}}}function Ewg(e){let[t,r]=e.split(":");if(!t||!r)throw new Error(`Invalid Maven coordinate for sdk-gen-api: ${e}`);return{groupId:t,artifactId:r}}function Iwg(e,t){let r=bv(e.name);if((r==="typescript"||r==="mcp")&&t.npm!=null)return yws(t.npm);if((r==="java"||r==="kotlin")&&t.maven!=null)return bws(t.maven);let n=jXu(r);if(n==null)throw new Error(`sdk-gen-api cannot infer a registry for ${r??e.name}`);return{publish:{registry:n}}}function jXu(e){switch(e){case"typescript":return"npm";case"python":return"pypi";case"java":case"kotlin":return"maven";case"go":return"go";case"csharp":return"nuget";case"php":return"composer";case"ruby":return"rubygems";case"rust":return"crates";case"mcp":return"npm";case"swift":case"cli":case void 0:return}}function zXu(e,t){let r=t.outputMode;if(r.type!=="publish"&&r.type!=="publishV2")return;let n=XSt(t).requestedOutput;if(n.type==="publish"&&n.publish.url!=null&&Iqu(n.publish.url),r.type==="publish"){let o=bv(t.name);if((o==="typescript"||o==="mcp")&&r.registryOverrides.npm!=null)return IXu(e,r.registryOverrides.npm.token);if((o==="java"||o==="kotlin")&&r.registryOverrides.maven!=null)return vXu(e,r.registryOverrides.maven);let s=jXu(o);throw s==null||!Cwg(s)?new Error(`sdk-gen-api does not support direct ${s??"unknown"} registry publication`):new Error(`Direct ${s} publication through sdk-gen-api requires publish credentials`)}let i=r.publishV2;switch(i.type){case"npmOverride":{let o=Fyi("npm",i.npmOverride);return IXu(e,o.token)}case"mavenOverride":{let o=Fyi("maven",i.mavenOverride);return vXu(e,o)}case"pypiOverride":{let o=Fyi("pypi",i.pypiOverride);return vwg(e,o.username,o.password)}case"cratesOverride":{let o=Fyi("crates",i.cratesOverride);return QXu(e,"crates",o.token)}case"rubyGemsOverride":throw new Error("sdk-gen-api does not support direct rubygems registry publication");case"nugetOverride":throw new Error("sdk-gen-api does not support direct nuget registry publication");case"postman":throw new Error("sdk-gen-api does not support Postman collection publication as an SDK output")}}function Myi(e,t,r,n){return{targetId:e,...DCs(t,r,n)}}function Fyi(e,t){if(t==null)throw new Error(`Direct ${e} publication through sdk-gen-api is missing its registry configuration`);return t}function IXu(e,t){return QXu(e,"npm",t)}function QXu(e,t,r){return Myi(e,{registry:t,token:r})}function vwg(e,t,r){return Myi(e,{registry:"pypi",username:t,password:r})}function vXu(e,t){return Myi(e,{registry:"maven",username:t.username,password:t.password,...t.signature==null?{}:{signature:t.signature}})}function Cwg(e){return e==="npm"||e==="maven"||e==="pypi"||e==="crates"}function xwg(e,t,r){let n=e.targets.flatMap((i,o)=>{if(i.requestedOutput.type!=="publish")return[];let s=t[o];if(s==null)throw new Error(`Cannot pair sdk-gen-api target ${i.targetId} with publish credentials`);let a=r?.[o],{publishUrl:c,publishRegistry:l}=LXu(i.requestedOutput),u=a!=null?Myi(i.targetId,a,c,l):zXu(i.targetId,s);return u!=null?[u]:[]});if(n.length!==0){if(n.length>WSt)throw new Error(`sdk-gen-api supports at most ${WSt} direct publish credential targets`);if(e.credentialSetId==null)throw new Error("sdk-gen-api direct registry targets require a credentialSetId");return{schemaVersion:"fern-publish-credentials/v1",credentialSetId:e.credentialSetId,targets:n}}}function MXu(e){zXu("preflight",e)}function Lyi(e){bAi(e.map(t=>({publicationRequested:t.requestedOutput?.type==="publish"||t.requestedOutput?.type==="github"&&t.requestedOutput.publish!=null,credentialsRequired:t.requestedOutput?.type==="publish",...LXu(t.requestedOutput),...t.publishCredential==null?{}:{publishCredential:t.publishCredential}})))}function LXu(e){let t=e?.type==="publish"||e?.type==="github"?e.publish:void 0;return t==null?{}:{publishRegistry:t.registry,...t.url==null?{}:{publishUrl:t.url}}}function _Xu(e){let{generatorInvocation:t,sdkVersion:r,specsTarGzBuffer:n,whitelabel:i}=e,o=bv(t.name),s=r==null||r.trim().length>0&&(!(0,NZt.isAutoVersion)(r)||UXu(e.requestedOutput));return o!=null&&s&&n!=null&&i==null}function UXu(e){return e?.type==="github"}function VXu({candidate:e,isSdkConfigTarget:t,isPreview:r}){let{generatorInvocation:n,sdkVersion:i,specsTarGzBuffer:o,whitelabel:s}=e;return s!=null?"whitelabel generation has not yet moved from Fiddle to the shared pipeline":i!=null&&(0,NZt.isAutoVersion)(i)&&!UXu(e.requestedOutput)?t?r?"preview generation only downloads files, so it cannot use --version AUTO":"automatic SDK versioning (--version AUTO) through sdk-gen-api requires GitHub output":"automatic SDK versioning (--version AUTO) through sdk-gen-api requires GitHub output in generators.yml":o==null?"the source archive is unavailable":`generator language ${n.language??"unknown"} does not match ${bv(n.name)}`}var jyi=class{expectedTargets;participants=[];removedTargetIds=new Set;terminalError;dispatched=!1;constructor(t){if(t<1)throw new Error("A Fern sdk-gen-api batch must expect at least one target");this.expectedTargets=t}run(t){return this.terminalError!=null?Promise.reject(this.terminalError):t.targetIdSeed!=null&&this.removedTargetIds.has(t.targetIdSeed)?Promise.reject(new Error(`Fern sdk-gen-api target ${t.targetIdSeed} was removed`)):this.dispatched?Promise.reject(new Error("The Fern sdk-gen-api batch was already dispatched")):new Promise((r,n)=>{this.participants.push({...t,resolve:r,reject:n}),this.dispatchIfReady()})}skip(){this.dispatched||this.terminalError!=null||(this.expectedTargets-=1,this.dispatchIfReady())}remove(t,r){if(this.dispatched||this.terminalError!=null||this.removedTargetIds.has(t))return!1;this.removedTargetIds.add(t);let n=this.participants.findIndex(o=>o.targetIdSeed===t),[i]=n>=0?this.participants.splice(n,1):[];return i?.reject(r),this.expectedTargets-=1,this.dispatchIfReady(),!0}cancel(t){if(!(this.dispatched||this.terminalError!=null)){this.terminalError=t;for(let r of this.participants)r.reject(t)}}dispatchIfReady(){this.dispatched||this.terminalError!=null||this.expectedTargets===0||this.participants.length!==this.expectedTargets||(this.dispatched=!0,this.dispatch())}async dispatch(){let t=[...this.participants].sort(zwg);try{(await HXu(t)).forEach((n,i)=>{let o=t[i];n.status==="fulfilled"?o?.resolve(n.value):o?.reject(n.reason)})}catch(r){this.terminalError=r;for(let n of this.participants)n.reject(r)}}},zyi=class{expectedTargetIds;settledTargetIds=new Set;waiters=[];preflightParticipants=[];terminalError;didRunPreflight=!1;constructor(t){if(this.expectedTargetIds=new Set(t),this.expectedTargetIds.size!==t.length)throw new Error("Fern sdk-gen-api preparation target IDs must be unique")}ready(t,r){if(this.assertExpected(t),this.settledTargetIds.has(t))throw new Error(`Fern sdk-gen-api target ${t} prepared more than once`);return this.settledTargetIds.add(t),r!=null&&this.preflightParticipants.push(r),new Promise((n,i)=>{this.waiters.push({resolve:n,reject:i}),this.finishIfSettled()})}fail(t,r,n){return this.assertExpected(t),this.settledTargetIds.has(t)?!1:(this.settledTargetIds.add(t),n||(this.terminalError=r),this.finishIfSettled(),!0)}assertExpected(t){if(!this.expectedTargetIds.has(t))throw new Error(`Unexpected Fern sdk-gen-api preparation target ${t}`)}finishIfSettled(){if(this.settledTargetIds.size===this.expectedTargetIds.size){if(!this.didRunPreflight&&this.terminalError==null&&this.preflightParticipants.length>0){this.didRunPreflight=!0;try{WXu(this.preflightParticipants)}catch(t){this.terminalError=t}}for(let t of this.waiters)this.terminalError!=null?t.reject(this.terminalError):t.resolve()}}};async function GXu(e){let[t]=await HXu([e]);if(t?.status==="fulfilled")return t.value;throw t?.reason??new Error("sdk-gen-api did not return the requested target")}function qXu(e){if(e>WSt)throw new Error(`sdk-gen-api supports at most ${WSt} target payloads per build; received ${e}`)}function WXu(e){let t=e[0];if(t==null)throw new Error("Cannot submit an empty Fern sdk-gen-api build");Nwg(e);let r;try{r=Kse()}catch(p){return t.context.failAndThrow(p instanceof Error?p.message:"Invalid sdk-gen-api origin",p,{code:T.Code.ConfigError})}if(!r)return t.context.failAndThrow("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled",void 0,{code:T.Code.ConfigError});Ywg(e),Qwg(e,t);let n=Xwg({apiName:t.apiName,organization:t.organization,cliVersion:t.cliVersion,specsTarGzBuffer:t.specsTarGzBuffer,targets:e.map(p=>({generatorInvocation:p.generatorInvocation,resolvedGeneratorVersion:p.resolvedGeneratorVersion,sdkGenApiRoute:p.sdkGenApiRoute,sdkName:p.sdkName,sdkVersion:p.sdkVersion,apiVersion:p.apiVersion,targetIdSeed:p.targetIdSeed,sourceSpecIndexes:p.sourceSpecIndexes,audiences:p.audiences,payload:p.payload,requestedOutput:p.requestedOutput,autoVersionPreviewOutput:p.autoVersionPreviewOutput,publishCredential:p.publishCredential,githubOptions:p.githubOptions}))}),i=xwg(n,e.map(p=>p.generatorInvocation),e.map(p=>p.publishCredential)),o=i!=null?Buffer.from(JSON.stringify(i)):void 0;if(o!=null&&o.length>65536)return t.context.failAndThrow(`sdk-gen-api publish credentials file is ${Lwg(o.length)}, exceeding the 64 KiB limit`,void 0,{code:T.Code.ConfigError});let s=t.specsTarGzBuffer.length+e.reduce((p,d)=>p+d.payload.body.length,0)+(o?.length??0);if(s>BXu)return t.context.failAndThrow(`sdk-gen-api source archive, target payloads, and publish credentials total ${fq(s)}, exceeding the 50 MiB in-memory upload limit`,void 0,{code:T.Code.ConfigError});let a=JSON.stringify(n),c=Buffer.byteLength(a,"utf8");if(c>lwg)return t.context.failAndThrow(`sdk-gen-api serialized request field is ${fq(c)}, exceeding the 1 MiB UTF-8 field limit; reduce generator customConfig, readme, settings, or API override metadata`,void 0,{code:T.Code.ConfigError});let l=new TXu.default;l.append("request",a),l.append("sources",t.specsTarGzBuffer,{filename:"specs.tar.gz",contentType:"application/gzip"}),e.forEach((p,d)=>{let f=n.targets[d];if(f==null)throw new Error(`Cannot pair sdk-gen-api payload at index ${d} with a target`);let m=p.payload.payloadKind==="fern-runtime-bundle";l.append("payloads",p.payload.body,{filename:`${f.targetId}.json${m?".gz":""}`,contentType:m?"application/gzip":"application/json"})}),o!=null&&l.append("credentials",o,{filename:"publish-credentials.v1.json",contentType:"application/json"});let u=l.getLengthSync();return u>DXu?t.context.failAndThrow(`sdk-gen-api multipart request is ${fq(u)}, exceeding the 60 MiB limit; reduce source or target payload size`,void 0,{code:T.Code.ConfigError}):{first:t,origin:r,request:n,form:l,sensitiveValues:cws([t.token.value,...Dwg(i)])}}async function HXu(e){let{first:t,origin:r,request:n,form:i,sensitiveValues:o}=WXu(e);wwg({first:t,origin:r,request:n,participants:e,sensitiveValues:o});let s;try{s=(await Ld.post(`${r}/v1/fern/build`,i,{headers:{...i.getHeaders(),Authorization:`Bearer ${t.token.value}`,"X-Fern-Organization-Id":t.organization},maxBodyLength:DXu,timeout:AXu})).data.buildId}catch(l){Twg(t.context,l,o);let u=xXu(l,o);return t.context.failAndThrow(`Failed to submit sdk-gen-api build: ${u.message}${Pwg(u,t.token)}`,u,{code:T.Code.NetworkError})}for(let l of e)l.context.logger.debug(`sdk-gen-api build ID: ${s}`);Swg({participants:e,request:n,origin:r,buildId:s});let a=new Map,c=Date.now()+gXu;for(;;){let l=Date.now()>=c,u;try{let f=await Ld.get(`${r}/v1/fern/build/${s}`,{headers:{Authorization:`Bearer ${t.token.value}`,"X-Fern-Organization-Id":t.organization},timeout:AXu});u=Rwg(f.data,o)}catch(f){let m=xXu(f,o);return t.context.failAndThrow("Failed to poll sdk-gen-api build",m,{code:T.Code.NetworkError})}let p=n.targets.find(f=>!u.targets.some(m=>m.targetId===f.targetId));if(p!=null)return t.context.failAndThrow(`sdk-gen-api response did not contain target ${p.targetId}`,void 0,{code:T.Code.InternalError});for(let[f,m]of n.targets.entries()){let g=u.targets.find(I=>I.targetId===m.targetId),A=e[f]?.context;if(g==null||A==null)continue;let b=a.get(g.targetId)??0;for(let I of g.logs.slice(b))Owg(A,I);a.set(g.targetId,g.logs.length)}if(n.targets.every(f=>_wg(u,f.targetId))||u.status==="failed"||u.status==="succeeded"){let f=await Promise.allSettled(e.map((m,g)=>Vwg(m,n.targets[g]?.targetId,u,n.targets[g]?.requestedOutput)));return Uwg({participant:t,status:u,buildId:s}),f}if(l)return t.context.failAndThrow(`Timed out waiting for sdk-gen-api build ${s} after ${gXu/6e4} minutes`,void 0,{code:T.Code.InternalError});await ef(iwg)}}function Swg({participants:e,request:t,origin:r,buildId:n}){for(let[i,o]of e.entries()){let s=t.targets[i];if(s!=null)try{o.context.instrumentPostHogEvent({orgId:o.organization,command:"sdk-gen-api build submitted",properties:{sdkGenApiBuildId:n,sdkGenApiTargetId:s.targetId,sdkGenApiTargetCount:t.targets.length,sdkGenApiHost:new URL(r).host,apiName:t.apiName,generatorName:s.fernGenerator.id,generatorVersion:s.fernGenerator.version??o.generatorInvocation.version,language:s.language,payloadKind:s.payloadKind,outputMode:s.requestedOutput.type,sdkName:s.sdk.name,sdkVersion:s.sdk.version}})}catch(a){o.context.logger.debug(`[telemetry] failed to send sdk-gen-api build event: ${String(a)}`)}}}function wwg({first:e,origin:t,request:r,participants:n,sensitiveValues:i}){let o=new Map(r.targets.map((s,a)=>{let c=n[a];return[s.targetId,{uploadBytes:c?.payload.body.length??0,targetIdSeed:c?.targetIdSeed,sourceSpecIndexes:c?.sourceSpecIndexes}]}));e.context.logger.debug(`Submitting sdk-gen-api build: ${Qyi({origin:t,sourceArchiveBytes:e.specsTarGzBuffer.length,request:{protocolVersion:r.protocolVersion,apiName:r.apiName,cliVersion:r.cliVersion,idempotencyKey:CXu(r.idempotencyKey),credentialSetId:r.credentialSetId==null?void 0:CXu(r.credentialSetId),apiInputs:r.apiInputs,targets:r.targets.map(s=>({targetId:s.targetId,apiInputId:s.apiInputId,language:s.language,sdk:s.sdk,fernGenerator:s.fernGenerator,payloadKind:s.payloadKind,package:s.package,requestedOutput:s.requestedOutput,invocation:{customConfigKeys:Object.keys(s.invocation.customConfig).sort(),keywords:s.invocation.keywords,smartCasing:s.invocation.smartCasing,smartCasingDigitWordBoundary:s.invocation.smartCasingDigitWordBoundary,disableExamples:s.invocation.disableExamples,audiences:s.invocation.audiences,hasReadme:s.invocation.readme!=null,hasSettings:s.invocation.settings!=null,hasApiOverride:s.invocation.apiOverride!=null},payload:o.get(s.targetId)}))}},i)}`)}function Twg(e,t,r){if(!(t instanceof S5t)){e.logger.debug(`sdk-gen-api submission failed before receiving an HTTP response: ${Qyi(t instanceof Error?{name:t.name,message:t.message}:{error:String(t)},r)}`);return}e.logger.debug(`sdk-gen-api submission HTTP failure: ${Qyi({status:t.response?.status??t.status,statusText:t.response?.statusText,code:t.code,responseBody:t.response?.data},r)}`)}function CXu(e){return e.length<=12?e:`${e.slice(0,12)}...`}function Qyi(e,t){let r;try{r=typeof e=="string"?e:JSON.stringify(e)}catch(i){r=i instanceof Error?`Failed to serialize debug value: ${i.message}`:String(e)}let n=pq(r,t);return n.length>hws?`${n.slice(0,hws)}... [truncated ${n.length-hws} bytes]`:n}function Owg(e,t){switch(t.level.toLowerCase()){case"error":e.logger.error(t.message);return;case"warn":case"warning":e.logger.warn(t.message);return;case"debug":case"trace":e.logger.debug(t.message);return;default:e.logger.info(t.message)}}function Pwg(e,t){return t.type!=="guest"||e.status!==409||!/idempotency key/i.test(e.message)?"":" This run is identical to an earlier guest build that has already ended. Change the input (for example --version), or start a fresh guest session with --new-session."}function xXu(e,t){if(!(e instanceof S5t))return new Nyi(pq(e instanceof Error?e.message:"Unknown submission error",t),void 0,void 0);let r=Bwg(e,t);return new Nyi(r??pq(e.message,t),e.response?.status??e.status,e.code)}function Bwg(e,t){let r=e.response?.data;if(typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")return pq(r.message,t);if(r!=null)return`sdk-gen-api response body: ${Qyi(r,t)}`}function Dwg(e){return(e?.targets??[]).flatMap(t=>t.registry==="npm"||t.registry==="crates"?[t.token]:t.registry==="pypi"?[t.username,t.password]:[t.username,t.password,...t.signature!=null?[t.signature.keyId,t.signature.password,t.signature.secretKey]:[]])}function Rwg(e,t){return{...e,targets:e.targets.map(r=>({...r,logs:r.logs.map(n=>({...n,message:pq(n.message,t)})),...r.error==null?{}:{error:{...typeof r.error.code=="string"?{code:pq(r.error.code,t)}:{},message:pq(r.error.message,t)}},...r.publication==null?{}:r.publication.status==="success"?{publication:{...r.publication,publishTarget:{...r.publication.publishTarget,identifier:lws(r.publication.publishTarget.identifier,t)}}}:{publication:{...r.publication,publishTarget:{...r.publication.publishTarget,identifier:lws(r.publication.publishTarget.identifier,t)},error:kwg(r.publication.error,t)}}}))}}function kwg(e,t){let{reason:r,detail:n,...i}=e,o=typeof n=="string"?pq(n,t).trim():void 0,s=typeof r=="string"&&dwg.test(r)&&pq(r,t)===r?r:void 0;return{...i,message:pq(e.message,t),...s!=null?{reason:s}:{},...o!=null&&o.length>0?{detail:o}:{}}}function Fwg(e){let t=`sdk-gen-api publication failed (${e.code}): ${e.message}`;return e.detail==null||e.detail===e.message?t:e.reason!=null?`${t}: ${e.detail} [${e.reason}]`:`${t}: ${e.detail}`}function Nwg(e){for(let t of e){let{generatorInvocation:r}=t,n=r.language??bv(r.name);n==null&&t.context.failAndThrow(`Cannot submit SDK generation to sdk-gen-api: generator language is unknown for ${r.name}`,void 0,{code:T.Code.ConfigError});let i;try{i=jwg(t,n)}catch(o){if(!(o instanceof Wse))throw o;t.context.failAndThrow(MZt(o),void 0,{code:T.Code.ConfigError,instructionsTopic:LZt(o)})}i.payloadKind!==t.payload.payloadKind&&t.context.failAndThrow(`Cannot submit SDK generation to sdk-gen-api: selected route payload ${i.payloadKind} does not match participant payload ${t.payload.payloadKind}`,void 0,{code:T.Code.ConfigError})}}function jwg(e,t){let{generatorInvocation:r,sdkGenApiRoute:n}=e;if(n?.requestedVersion==null){if(n!=null){if(!kyi(n,r.version))throw JXu(n,r.version);return ZGe({generatorId:r.name,language:t,configKind:n.configKind,versionSource:n.versionSource})}return XGe({generatorId:r.name,language:t,requestedVersion:r.version,configKind:e.payload.payloadKind==="fern-runtime-bundle"?"legacy-fern":"sdk-config-v1"})}return XGe({generatorId:r.name,language:t,requestedVersion:n.requestedVersion,configKind:n.configKind})}function MZt(e){let t=[e.code,`generator=${e.generatorId}`,`language=${e.language}`,`requestedVersion=${e.requestedVersion}`,`cutoverVersion=${e.cutoverVersion??"n/a"}`,`receivedConfigKind=${String(e.receivedConfigKind)}`,`expectedConfigKind=${e.expectedConfigKind??"n/a"}`,`expectedLanguage=${e.expectedLanguage??"n/a"}`,`retryable=${e.retryable}`,`recommendedAction=${e.recommendedAction}`].join("; "),r=e.recommendedAction==="USE_SDK_CONFIG_V1"?" Run `fern sdk migrate`, then pass the generated document with `fern generate --sdk-config <path>` before using this generator version.":"";return`Cannot submit SDK generation to sdk-gen-api: ${e.message} [${t}].${r}`}function LZt(e){return e.recommendedAction==="USE_SDK_CONFIG_V1"?eo.SdksMigrate:void 0}function KXu(e,t,r){if(e==null)return t.version;if(e.requestedVersion!=null)return e.requestedVersion;if(!kyi(e,t.version))throw JXu(e,t.version);return r}function JXu(e,t){return new Error(`An unpinned sdk-gen-api route does not match its generator version representation: invocationVersion=${JSON.stringify(t)}; configKind=${e.configKind}; versionSource=${e.requestedVersion==null?e.versionSource:"pinned"}`)}function gws(e,t,r){return KXu(e,t,r)??uwg}function zwg(e,t){let r=fwg.compare(e.targetIdSeed??"",t.targetIdSeed??"");if(r!==0)return r;let n=e.generatorInvocation.name.localeCompare(t.generatorInvocation.name);if(n!==0)return n;let i=gws(e.sdkGenApiRoute,e.generatorInvocation).localeCompare(gws(t.sdkGenApiRoute,t.generatorInvocation));return i!==0?i:(e.sdkVersion??"").localeCompare(t.sdkVersion??"")}function Qwg(e,t){e.length>WSt&&t.context.failAndThrow(`sdk-gen-api supports at most ${WSt} target payloads per build; received ${e.length}`,void 0,{code:T.Code.ConfigError}),t.specsTarGzBuffer.length>owg&&t.context.failAndThrow(`sdk-gen-api source archive is ${fq(t.specsTarGzBuffer.length)}, exceeding the 25 MiB compressed limit`,void 0,{code:T.Code.ConfigError});let r=e.findIndex(s=>s.payload.body.length>(s.payload.payloadKind==="fern-runtime-bundle"?yXu:bXu));if(r>=0){let s=e[r],a=s?.payload.payloadKind==="fern-runtime-bundle"?yXu:bXu;t.context.failAndThrow(`sdk-gen-api ${SXu(s,r)} is ${fq(s?.payload.body.length??0)}, exceeding the ${fq(a)} upload limit`,void 0,{code:T.Code.ConfigError})}let n=e.reduce((s,a)=>s+a.payload.body.length,t.specsTarGzBuffer.length);n>BXu&&t.context.failAndThrow(`sdk-gen-api source archive and target payloads total ${fq(n)}, exceeding the 50 MiB in-memory upload limit; reduce the source archive size, target payload size, or number of targets`,void 0,{code:T.Code.ConfigError});let i=e.reduce((s,a)=>a.payload.payloadKind==="fern-runtime-bundle"?s+a.payload.body.length:s,0);i>awg&&t.context.failAndThrow(`sdk-gen-api runtime bundles total ${fq(i)}, exceeding the 25 MiB compressed limit; reduce the number or size of targets`,void 0,{code:T.Code.ConfigError}),wXu({buffer:t.specsTarGzBuffer,maxBytes:swg,label:"source archive",context:t.context});let o=0;for(let[s,a]of e.entries())o+=a.payload.payloadKind==="fern-runtime-bundle"?wXu({buffer:a.payload.body,maxBytes:cwg,label:SXu(a,s),context:t.context}):a.payload.body.length,o>PXu&&t.context.failAndThrow(`sdk-gen-api target payloads total ${fq(o)}, exceeding the 100 MiB decoded limit; reduce the number or size of targets`,void 0,{code:T.Code.ConfigError})}function SXu(e,t){return`${e?.payload.payloadKind??"target payload"} ${e?.targetIdSeed??t.toString()}`}function wXu({buffer:e,maxBytes:t,label:r,context:n}){let i;try{i=(0,OXu.gunzipSync)(e,{maxOutputLength:t+1})}catch(o){return Mwg(o)?n.failAndThrow(`sdk-gen-api ${r} exceeds the ${fq(t)} decompressed limit`,void 0,{code:T.Code.ConfigError}):n.failAndThrow(`sdk-gen-api ${r} is malformed gzip; regenerate it and retry`,o,{code:T.Code.ConfigError})}return i.length>t?n.failAndThrow(`sdk-gen-api ${r} is ${fq(i.length)} decompressed, exceeding the ${fq(t)} decompressed limit`,void 0,{code:T.Code.ConfigError}):i.length}function Mwg(e){return e instanceof Error&&"code"in e&&e.code==="ERR_BUFFER_TOO_LARGE"}function fq(e){return`${(e/(1024*1024)).toFixed(2)} MiB`}function Lwg(e){return`${(e/1024).toFixed(2)} KiB`}function _wg(e,t){let r=e.targets.find(n=>n.targetId===t);return r?.status==="failed"||r?.status==="succeeded"}function Uwg({participant:e,status:t,buildId:r}){if(e.token.type!=="guest"||!t.targets.some(i=>i.status==="succeeded"&&i.result?.artifactUrl!=null))return;let n=Cqu({claimUrl:e.token.claimUrl,buildId:r});e.context.logger.info(n!=null?`Build ${r} is kept for 7 days: ${n} (claiming the session moves it into your organization)`:`Build ${r} is kept for 7 days (claiming the session moves it into your organization)`)}async function Vwg(e,t,r,n){let i=r.targets.find(u=>u.targetId===t);if(i==null)return e.context.failAndThrow("sdk-gen-api response did not contain the requested target",void 0,{code:T.Code.InternalError});if(i.status==="failed")return i.publication?.status==="failure"?e.context.failAndThrow(Fwg(i.publication.error),void 0,{code:T.Code.ContainerError}):e.context.failAndThrow(Gwg(i.error),void 0,{code:T.Code.ContainerError});if(i.status!=="succeeded")return e.context.failAndThrow(`sdk-gen-api build ended with status ${r.status} while target ${i.targetId} remained ${i.status}`,void 0,{code:T.Code.InternalError});let o=e.sdkVersion!=null&&(0,NZt.isAutoVersion)(e.sdkVersion),s=o&&i.publication?.status==="success"&&i.publication.output.noChangesDetected===!0&&i.result?.actualVersion==null,a=i.result?.artifactUrl;if(a==null&&!s)return e.context.failAndThrow("sdk-gen-api target completed without an artifact URL",void 0,{code:T.Code.InternalError});a==null?e.context.logger.info("No changes detected; there is no SDK preview to download."):e.absolutePathToPreview!=null?await Ryi({s3PreSignedReadUrl:a,absolutePathToLocalOutput:ke(e.absolutePathToPreview,Ee.of(Squ(e.generatorInvocation.name,Kwg(e.generatorInvocation)))),context:e.context,skipFernignore:e.skipFernignore}):e.absolutePathToLocalOutputArchive!=null?await uXu({s3PreSignedReadUrl:a,absolutePathToLocalOutput:e.absolutePathToLocalOutputArchive,context:e.context}):e.generatorInvocation.absolutePathToLocalOutput!=null&&await Ryi({s3PreSignedReadUrl:a,absolutePathToLocalOutput:e.generatorInvocation.absolutePathToLocalOutput,context:e.context,skipFernignore:e.skipFernignore});let c=i.result?.actualVersion??(o?void 0:e.sdkVersion),l=e.autoVersionPreviewOutput!=null?{pullRequestUrl:void 0,noChangesDetected:i.publication?.status==="success"&&i.publication.output.noChangesDetected===!0?!0:void 0}:qwg(e,i,n);return o&&c!=null&&e.context.logger.info(`AUTO versioning picked new version: ${c}`),{createdSnippets:!1,snippetsS3PreSignedReadUrl:void 0,actualVersion:c,...l,publishTarget:c==null||e.autoVersionPreviewOutput!=null?void 0:Jwg(i,c)}}function Gwg(e){let t=e?.message||"sdk-gen-api generation failed";return e?.code!=null&&e.code!==""?`${e.code}: ${t}`:t}function qwg(e,t,r){if(r?.type!=="github")return{pullRequestUrl:void 0,noChangesDetected:void 0};let{publication:n}=t;if(n?.status!=="success"||n.publishTarget.type!=="github")return e.context.failAndThrow(`sdk-gen-api reported the build as succeeded but did not confirm the GitHub delivery to ${r.repository}`,void 0,{code:T.Code.InternalError});let i=Wwg(n.output.pullRequestUrl),o=n.output.noChangesDetected===!0,s={pullRequestUrl:o?void 0:i,noChangesDetected:o?!0:void 0},a=n.output.pullRequestUrl!=null&&i==null;return Hwg(e.context.logger,r,s,a),s}function Wwg(e){let t=e==null?void 0:YXu(e);if(t==null)return;let{origin:r,pathname:n}=new URL(t);return`${r}${n}`}function Hwg(e,{repository:t,mode:r},{pullRequestUrl:n,noChangesDetected:i},o){if(i){e.info(`No changes detected for ${t}; nothing was delivered to GitHub.`);return}if(n!=null){e.info(`Pull request: ${n}`);return}if(o){e.warn(`sdk-gen-api returned a pull request link for ${t} that was not a safe HTTPS URL.`);return}r==="pull-request"&&e.warn(`sdk-gen-api did not return a pull request link for ${t}.`)}function Kwg(e){return e.sdkConfigTargetIndex}function Jwg(e,t){if(e.publication?.status!=="success")return;let r=e.publication.publishTarget.type,n=e.publication.publishTarget.identifier,i=YXu(n);switch(r){case"npm":return{registry:r,label:"npm",version:t,identifier:n,...i!=null?{url:i}:{}};case"pypi":return{registry:r,label:"PyPI",version:t,identifier:n,...i!=null?{url:i}:{}};case"crates":return{registry:r,label:"crates.io",version:t,identifier:n,...i!=null?{url:i}:{}};case"maven":return{registry:r,label:"Maven Central",version:t,identifier:n,...i!=null?{url:i}:{}};case"github":case"unsupported":return}}function YXu(e){try{let t=new URL(e);return t.protocol==="https:"&&t.username.length===0&&t.password.length===0?e:void 0}catch{return}}function Ywg(e){let t=e[0];if(t==null)return;let r=(0,Hse.createHash)("sha256").update(t.specsTarGzBuffer).digest("hex");for(let n of e.slice(1)){let i=(0,Hse.createHash)("sha256").update(n.specsTarGzBuffer).digest("hex");if(n.apiName!==t.apiName||n.organization!==t.organization||n.token.value!==t.token.value||i!==r)throw new Error("Fern sdk-gen-api batch targets must share API, organization, token, and sources")}}function Xwg({apiName:e,organization:t,cliVersion:r,specsTarGzBuffer:n,targets:i}){if(i.length===0)throw new Error("Cannot create an empty Fern sdk-gen-api request");let o=[],s=i.map(({targetIdSeed:f,sourceSpecIndexes:m},g)=>{if(m==null)return o.some(b=>b.id==="default")||o.push({id:"default",specIndexes:"all"}),"default";let A=`target-${f??g.toString()}`;return o.push({id:A,specIndexes:m}),A}),a=i.map(({generatorInvocation:f,resolvedGeneratorVersion:m,sdkGenApiRoute:g,sdkName:A,sdkVersion:b,apiVersion:I,targetIdSeed:C,audiences:x,payload:S,requestedOutput:B,autoVersionPreviewOutput:D,githubOptions:R},O)=>{let z=bv(f.name);if(z==null)throw new Error(`Unsupported Fern SDK generator: ${f.name}`);let X=XSt(f,R),ee=hwg(B??X.requestedOutput,R),te=S.payloadKind==="fern-runtime-bundle"?X.package:S.package,ae=KXu(g,f,m),ce=gws(g,f,m);return{targetId:(0,Hse.createHash)("sha256").update(`${e}:${f.name}:${ce}:${C??O.toString()}`).digest("hex").slice(0,20),apiInputId:s[O]??"default",language:z,sdk:{name:A??e,...b!=null?{version:b}:{},...I!=null?{apiVersion:I}:{}},fernGenerator:{id:f.name,...ae!=null?{version:ae}:{}},payloadKind:S.payloadKind,...te!=null?{package:te}:{},invocation:{customConfig:Kee(f.config)??{},keywords:f.keywords??[],smartCasing:f.smartCasing,smartCasingDigitWordBoundary:f.smartCasingDigitWordBoundary,disableExamples:f.disableExamples,...x!=null?{audiences:x}:{},...f.readme!=null?{readme:f.readme}:{},...f.settings!=null?{settings:f.settings}:{},...f.apiOverride!=null?{apiOverride:f.apiOverride}:{}},requestedOutput:ee,...D!=null?{autoVersionPreview:{github:D}}:{}}}),c=i.map(f=>(0,Hse.createHash)("sha256").update(f.payload.body).digest("hex")),l=JSON.stringify({protocolVersion:2,organization:t,apiName:e,apiInputs:o,targets:a,payloadHashes:c,sourceHash:(0,Hse.createHash)("sha256").update(n).digest("hex")}),u=a.some(f=>f.requestedOutput.type==="publish")?Zwg(l):void 0,p=a.some(f=>f.sdk.version==null||(0,NZt.isAutoVersion)(f.sdk.version))?(0,Hse.randomUUID)():void 0,d=(0,Hse.createHash)("sha256").update(n).update(JSON.stringify({protocolVersion:2,organization:t,apiName:e,credentialSetId:u,apiInputs:o,targets:a,payloadHashes:c,...p!=null?{dynamicVersionRunId:p}:{}})).digest("hex");return{protocolVersion:2,apiName:e,...r?{cliVersion:r}:{},idempotencyKey:d,...u!=null?{credentialSetId:u}:{},apiInputs:o,targets:a}}function Zwg(e){let t=(0,Hse.createHash)("sha256").update(e).digest().subarray(0,16);t[6]=(t[6]??0)&15|128,t[8]=(t[8]??0)&63|128;let r=t.toString("hex");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}Ec();yo();gt();zn();function e9e({apiName:e,organization:t,generatorInvocation:r}){let n=$wg(r);return{apiName:e,organization:t,customConfig:Kee(r.config),outputConfig:n??ar.GeneratorOutputConfig.local()}}function $wg(e){let t=e.outputMode;switch(t.type){case"downloadFiles":return ar.GeneratorOutputConfig.local();case"publishV2":return e1g({publish:t.publishV2,version:e.version});case"githubV2":return t1g({github:t.githubV2,language:e.language,version:e.version});case"publish":case"github":return;default:Ze(t)}}function e1g({publish:e,version:t}){switch(e.type){case"npmOverride":{let r=e.npmOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.npm({version:t,packageName:r.packageName,repoUrl:void 0}))}case"mavenOverride":{let r=e.mavenOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.maven({version:t,coordinate:r.coordinate,repoUrl:void 0}))}case"pypiOverride":{let r=e.pypiOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.pypi({version:t,packageName:r.coordinate,repoUrl:void 0}))}case"rubyGemsOverride":{let r=e.rubyGemsOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.rubygems({version:t,packageName:r.packageName,repoUrl:void 0}))}case"nugetOverride":{let r=e.nugetOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.nuget({version:t,packageName:r.packageName,repoUrl:void 0}))}case"cratesOverride":{let r=e.cratesOverride;return r==null?void 0:ar.GeneratorOutputConfig.publish(ar.PublishInfo.crates({version:t,packageName:r.packageName,repoUrl:void 0}))}case"postman":return;default:Ze(e)}}function t1g({github:e,version:t,language:r}){let n=r1g({owner:e.owner,repo:e.repo});if(r===Qr.GenerationLanguage.GO)return ar.GeneratorOutputConfig.publish(ar.PublishInfo.go({version:t,repoUrl:n}));if(r===Qr.GenerationLanguage.SWIFT)return ar.GeneratorOutputConfig.publish(ar.PublishInfo.swift({version:t,repoUrl:n}));let i=e.publishInfo;if(i!=null)switch(i.type){case"maven":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.maven({version:t,coordinate:i.coordinate,repoUrl:n}));case"npm":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.npm({version:t,packageName:i.packageName,repoUrl:n}));case"pypi":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.pypi({version:t,packageName:i.packageName,repoUrl:n}));case"rubygems":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.rubygems({version:t,packageName:i.packageName,repoUrl:n}));case"nuget":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.nuget({version:t,packageName:i.packageName,repoUrl:n}));case"crates":return ar.GeneratorOutputConfig.publish(ar.PublishInfo.crates({version:t,packageName:i.packageName,repoUrl:n}));case"postman":return;default:Ze(i)}}function r1g({owner:e,repo:t}){return`https://github.com/${e}/${t}`}Wn();A3();Pt();KU();var iy=Ae(xip(),1),DL=Ae(eA(),1),Tip=Ae(require("path"),1),PFg="0.0.1";function l$t(e){if(e.raw?.github!=null&&typeof e.raw.github=="object"&&"license"in e.raw.github){let t=e.raw.github;if(t.license!=null){if(typeof t.license=="string")return{type:"basic",value:t.license};if(typeof t.license=="object"&&"custom"in t.license)return{type:"custom",value:t.license.custom}}}if(e.raw?.metadata?.license!=null){let t=e.raw.metadata.license;if(typeof t=="string")return{type:"basic",value:t};if(typeof t=="object"&&"custom"in t)return{type:"custom",value:t.custom}}}function BFg(e,t){let r=l$t(e);if(r!=null){if(r.type==="basic"){if(r.value==="MIT"||r.value==="Apache-2.0")return iy.FernGeneratorExec.LicenseConfig.basic({id:r.value==="MIT"?iy.FernGeneratorExec.LicenseId.Mit:iy.FernGeneratorExec.LicenseId.Apache2})}else if(r.type==="custom")return iy.FernGeneratorExec.LicenseConfig.custom({filename:Tip.basename(r.value)})}}function aEi(e,t={}){let r=t.omitPublishCredentials??!1;return e!=null?qr.GithubPublishInfo._visit(e,{npm:n=>{let i=(n.token??"").trim(),o=U1s(i),s=i!=="";return iy.FernGeneratorExec.GithubPublishInfo.npm({registryUrl:n.registryUrl,packageName:n.packageName,tokenEnvironmentVariable:(0,DL.EnvironmentVariable)(r?o!=null?"<USE_OIDC>":"":o!=null?"<USE_OIDC>":i.startsWith("${")&&i.endsWith("}")?i.slice(2,-1).trim():""),shouldGeneratePublishWorkflow:o!=null||s})},maven:n=>iy.FernGeneratorExec.GithubPublishInfo.maven({registryUrl:n.registryUrl,coordinate:n.coordinate,usernameEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.credentials?.username??""),passwordEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.credentials?.password??""),signature:n.signature!=null?{keyIdEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.signature.keyId??""),passwordEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.signature.password??""),secretKeyEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.signature.secretKey??"")}:void 0}),pypi:n=>{let i=(n.credentials?.password??"").trim(),o=U1s(i),s=n.credentials!=null;return iy.FernGeneratorExec.GithubPublishInfo.pypi({registryUrl:n.registryUrl,packageName:n.packageName,usernameEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":"PYPI_USERNAME"),passwordEnvironmentVariable:(0,DL.EnvironmentVariable)(r?o!=null?"OIDC":"":o!=null?"OIDC":"PYPI_PASSWORD"),shouldGeneratePublishWorkflow:o!=null||s,pypiMetadata:n.pypiMetadata})},rubygems:n=>iy.FernGeneratorExec.GithubPublishInfo.rubygems({registryUrl:n.registryUrl,packageName:n.packageName,apiKeyEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.apiKey??"")}),postman:n=>iy.FernGeneratorExec.GithubPublishInfo.postman({apiKeyEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.apiKey??""),workspaceIdEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.workspaceId??"")}),nuget:n=>{let i=(n.apiKey??"").trim(),o=U1s(i);return iy.FernGeneratorExec.GithubPublishInfo.nuget({registryUrl:n.registryUrl,packageName:n.packageName,apiKeyEnvironmentVariable:(0,DL.EnvironmentVariable)(r?o!=null?"<USE_OIDC>":"":o!=null?"<USE_OIDC>":i.startsWith("${")&&i.endsWith("}")?i.slice(2,-1).trim():""),shouldGeneratePublishWorkflow:o!=null?!0:void 0})},crates:n=>iy.FernGeneratorExec.GithubPublishInfo.crates({registryUrl:n.registryUrl,packageName:n.packageName,tokenEnvironmentVariable:(0,DL.EnvironmentVariable)(r?"":n.token??"")}),_other:()=>{}}):void 0}function U1s(e){if(e==="OIDC"||e==="<USE_OIDC>")return e}function xwt({generatorInvocation:e,customConfig:t,workspaceName:r,organization:n,outputVersion:i=PFg,absolutePathToSnippet:o,absolutePathToSnippetTemplates:s,absolutePathToFernConfig:a,writeUnitTests:c,generateOauthClients:l,generatePaginatedClients:u,whiteLabel:p,publishToRegistry:d,omitPublishCredentials:f,paths:m}){let g=BFg(e,a),{snippetPath:A,snippetTemplatePath:b,irPath:I,outputDirectory:C}=m,x=e.outputMode._visit({publish:B=>{if(d===!0){let D=RFg(B,f===!0);return{...wip(i,D,m),snippetFilepath:A,publishingMetadata:e.publishMetadata}}return{...Sip(i,B,e,m),snippetFilepath:A,publishingMetadata:e.publishMetadata}},publishV2:B=>{if(d===!0){let D=kFg(B,f===!0);return{...wip(i,D,m),snippetFilepath:A,publishingMetadata:e.publishMetadata}}return{...Sip(i,B,e,m),snippetFilepath:A,publishingMetadata:e.publishMetadata}},downloadFiles:()=>({mode:iy.FernGeneratorExec.OutputMode.downloadFiles(),path:C,snippetFilepath:A,publishingMetadata:e.publishMetadata}),github:B=>{let D={mode:iy.FernGeneratorExec.OutputMode.github({repoUrl:`https://github.com/${B.owner}/${B.repo}`,version:i,publishInfo:aEi(B.publishInfo,{omitPublishCredentials:f}),installationToken:void 0}),path:C,publishingMetadata:e.publishMetadata};return o!==void 0&&(D.snippetFilepath=A),s!==void 0&&(D.snippetTemplateFilepath=b),D},githubV2:B=>{let D=B._visit({commitAndRelease:O=>`https://github.com/${O.owner}/${O.repo}`,push:O=>`https://github.com/${O.owner}/${O.repo}`,pullRequest:O=>`https://github.com/${O.owner}/${O.repo}`,_other:()=>{throw new T({message:"Encountered unknown github mode",code:T.Code.InternalError})}}),R={mode:iy.FernGeneratorExec.OutputMode.github({repoUrl:D,version:i,publishInfo:aEi(B.publishInfo,{omitPublishCredentials:f})}),path:C,publishingMetadata:e.publishMetadata};return o!==void 0&&(R.snippetFilepath=A),s!==void 0&&(R.snippetTemplateFilepath=b),R},_other:()=>{throw new T({message:"Output type did not match any of the types supported by Fern",code:T.Code.InternalError})}}),S=FFg(e,i);return{irFilepath:I,output:x,publish:S,customConfig:t,workspaceName:r,organization:n,environment:iy.FernGeneratorExec.GeneratorEnvironment.local(),dryRun:!1,whitelabel:p??!1,writeUnitTests:c,generateOauthClients:l,generatePaginatedClients:u,license:g}}function Sip(e,t,r,n){let{outputDirectory:i}=n,o;"registryOverrides"in t?o=t.registryOverrides.maven??t.registryOverrides.npm:o!=null&&(o=t._visit({mavenOverride:a=>a,npmOverride:a=>a,pypiOverride:a=>a,rubyGemsOverride:a=>a,postman:a=>a,nugetOverride:a=>a,cratesOverride:a=>a,_other:()=>{}}));let s="";return r.raw?.github!=null&&(gxe(r.raw.github)?s=Px(r.raw.github.uri).repoUrl:s=r.raw?.github.repository),{mode:iy.FernGeneratorExec.OutputMode.github({repoUrl:s,version:e}),path:i}}function wip(e,t,r){let{outputDirectory:n}=r,{registries:i,registriesV2:o}=DFg(t);return{mode:iy.FernGeneratorExec.OutputMode.publish({registries:i,registriesV2:o,publishTarget:t,version:e}),path:n}}function DFg(e){let t=structuredClone(Oip),r=structuredClone(Pip);if(e==null)return{registries:t,registriesV2:r};switch(e.type){case"npm":t.npm={registryUrl:e.registryUrl,token:e.token,scope:""},r.npm={registryUrl:e.registryUrl,token:e.token,packageName:e.packageName};break;case"maven":t.maven={registryUrl:e.registryUrl,username:e.username,password:e.password,group:"",signature:e.signature},r.maven={registryUrl:e.registryUrl,username:e.username,password:e.password,coordinate:e.coordinate,signature:e.signature};break;case"pypi":r.pypi={registryUrl:e.registryUrl,username:e.username,password:e.password,packageName:e.packageName,pypiMetadata:e.pypiMetadata};break;case"rubygems":r.rubygems={registryUrl:e.registryUrl,apiKey:e.apiKey,packageName:e.packageName};break;case"nuget":r.nuget={registryUrl:e.registryUrl,apiKey:e.apiKey,packageName:e.packageName};break;case"crates":r.crates={registryUrl:e.registryUrl,token:e.token,packageName:e.packageName};break;default:break}return{registries:t,registriesV2:r}}function RFg(e,t){if("registryOverrides"in e){let r=e.registryOverrides;if(r.npm!=null)return iy.FernGeneratorExec.GeneratorPublishTarget.npm({registryUrl:r.npm.registryUrl,token:t?"":r.npm.token,packageName:r.npm.packageName});if(r.maven!=null)return iy.FernGeneratorExec.GeneratorPublishTarget.maven({registryUrl:r.maven.registryUrl,username:t?"":r.maven.username??"",password:t?"":r.maven.password??"",coordinate:r.maven.coordinate??"",signature:void 0})}}function kFg(e,t){return e._visit({npmOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.npm({registryUrl:r.registryUrl,token:t?"":r.token,packageName:r.packageName}):void 0,mavenOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.maven({registryUrl:r.registryUrl,username:t?"":r.username,password:t?"":r.password,coordinate:r.coordinate,signature:t?void 0:r.signature??void 0}):void 0,pypiOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.pypi({registryUrl:r.registryUrl,username:t?"":r.username,password:t?"":r.password,packageName:r.coordinate,pypiMetadata:r.pypiMetadata??void 0}):void 0,rubyGemsOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.rubygems({registryUrl:r.registryUrl,apiKey:t?"":r.apiKey,packageName:r.packageName}):void 0,nugetOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.nuget({registryUrl:r.registryUrl,apiKey:t?"":r.apiKey,packageName:r.packageName}):void 0,cratesOverride:r=>r!=null?iy.FernGeneratorExec.GeneratorPublishTarget.crates({registryUrl:r.registryUrl,token:t?"":r.token,packageName:r.packageName}):void 0,postman:r=>iy.FernGeneratorExec.GeneratorPublishTarget.postman({apiKey:t?"":r.apiKey,workspaceId:t?"":r.workspaceId}),_other:()=>{}})}function FFg(e,t){let r=e.outputMode._visit({publish:()=>{},publishV2:()=>{},downloadFiles:()=>{},github:o=>o.publishInfo,githubV2:o=>o._visit({push:s=>s.publishInfo,commitAndRelease:s=>s.publishInfo,pullRequest:s=>s.publishInfo,_other:()=>{}}),_other:()=>{}});if(r==null||r.type!=="pypi")return;let n=(r.credentials?.password??"").trim();if(n!=="OIDC"&&n!=="<USE_OIDC>")return;let i=structuredClone(Pip);return i.pypi={registryUrl:r.registryUrl,username:"__token__",password:"OIDC",packageName:r.packageName,pypiMetadata:r.pypiMetadata},{registries:structuredClone(Oip),registriesV2:i,publishTarget:void 0,version:t}}var Oip={maven:{registryUrl:"",username:"",password:"",group:"",signature:void 0},npm:{registryUrl:"",token:"",scope:""}},Pip={maven:{registryUrl:"",username:"",password:"",coordinate:"",signature:void 0},npm:{registryUrl:"",token:"",packageName:""},pypi:{registryUrl:"",username:"",password:"",packageName:"",pypiMetadata:void 0},rubygems:{registryUrl:"",apiKey:"",packageName:""},nuget:{registryUrl:"",apiKey:"",packageName:""},crates:{registryUrl:"",token:"",packageName:""}};gt();function u$t(e,t){if(Hh(e))return e;switch(t){case"github":return`https://github.com/${e}`;case"gitlab":return`https://gitlab.com/${e}`;case"bitbucket":return`https://bitbucket.org/${e}`;default:Ze(t)}}function p$t(e){return e.language==="mcp"&&e.output?.delivery==="hosted"?{...e,output:{delivery:"zip"}}:e}function V1s(e){let t=e.sdkConfigPath==null?"":`; SDK Config: ${e.sdkConfigPath.join(".")}`;return`[${e.severity}] [${e.code}] ${e.path.join(".")}: ${e.reason}${t}; ${e.suggestedAction}`}function Bip({workspace:e,generatorInvocation:t,audiences:r,replay:n,sourceArchive:i,mapFernGroupToSdkConfig:o}){let s=o({fernWorkspace:e,replay:n,group:{groupName:"sdk-gen-api",audiences:r,generators:[t],reviewers:void 0},source:NFg(i)}),a={...s.sdkConfig,targets:s.sdkConfig.targets.map(p$t)};return{payloadKind:"sdk-config-v1",body:Buffer.from(JSON.stringify(a),"utf8"),diagnostics:s.diagnostics}}function NFg(e){return{specs:e.specIndexes.map((r,n)=>{let i=e.manifest.specs[r];if(i==null)throw new Error(`Fern source manifest does not contain selected index ${r}`);if(!jFg(i))throw new Error(`SDK Config generation does not support Fern source type ${i.type} (${i.specPath})`);return{id:`source-${n}`,type:i.type,path:i.specPath.replace(/^\/+/,""),...i.namespace==null?{}:{namespace:i.namespace},...i.apiImportSettings==null?{}:{apiImportSettings:i.apiImportSettings},...i.overridePaths==null||i.overridePaths.length===0?{}:{overrides:i.overridePaths}}})}}function jFg(e){return e.type==="openapi"||e.type==="asyncapi"||e.type==="graphql"}Ec();yo();nf();gt();c0();nm();F$();gt();hy();ln();Co();function gAe({context:e,violations:t,logWarnings:r,logSummary:n=!0,logBreadcrumbs:i=!0,elapsedMillis:o=0}){let s=[],a={};for(let u of t){let p=JSON.stringify(u.nodePath),d=a[p]??[];d.some(m=>m.message===u.message&&m.nodePath.length===u.nodePath.length&&m.nodePath.every((g,A)=>y6(g,u.nodePath[A]))&&m.relativeFilepath===u.relativeFilepath&&m.severity===u.severity)||(s.push(u),a[p]=[...d,u])}t=s;let c=VFg(t),l=zFg(t);for(let u of Array.from(l.keys()).sort()){let p=l.get(u);if(p){let d=p.violations[0]?.relativeFilepath??"";QFg({logWarnings:r,logBreadcrumbs:i,configRelativeFilepath:d,nodePath:p.nodePath,violations:p.violations,context:e})}}return n&&UFg({context:e,stats:c,logWarnings:r,elapsedMillis:o}),{hasErrors:c.numFatal>0}}function zFg(e){let t={};for(let r of e){let i=r.nodePath.length===0?`file:${r.relativeFilepath}`:`node:${JSON.stringify(r.nodePath)}`;t[i]||(t[i]={nodePath:r.nodePath,violations:[]}),t[i].violations.push(r)}return new Map(Object.entries(t))}function QFg({logWarnings:e,logBreadcrumbs:t,configRelativeFilepath:r,nodePath:n,violations:i,context:o}){let s=MFg(i);if(s==="warning"&&!e)return;let a="",c=i.map(l=>l.severity==="warning"&&!e?null:(a===""&&(a=l.relativeFilepath),`${_Fg(l.severity)} ${l.message}`)).filter(l=>l!=null).join(`
4116
4116
  `);o.logger.log(LFg(s),oV({breadcrumbs:t?[r,...n.map(l=>{let u=typeof l=="string"?l:l.key;return typeof l!="string"&&l.arrayIndex!=null&&(u+=`[${l.arrayIndex}]`),u})]:[],title:a,subtitle:c})+`
4117
4117
  `)}function MFg(e){return e.some(t=>t.severity==="fatal")?"fatal":e.some(t=>t.severity==="error")?"error":"warning"}function LFg(e){switch(e){case"fatal":return Un.Error;case"error":return Un.Error;case"warning":return Un.Warn;default:Ze(e)}}function _Fg(e){switch(e){case"fatal":return le.red("[error]");case"error":return le.red("[error]");case"warning":return le.yellow("[warning]");default:Ze(e)}}function UFg({stats:e,context:t,logWarnings:r,elapsedMillis:n=0}){let{numFatal:i,numErrors:o,numWarnings:s}=e,a=n>0?` in ${(n/1e3).toFixed(3)} seconds.`:".",c=`Found ${i+o} errors and ${s} warnings`+a;!r&&s>0&&(c+=" Run fern check --warnings to print out the warnings not shown."),i+o>0?t.logger.error(c):s>0?t.logger.warn(c):t.logger.info(le.green("\u2713 All checks passed"))}function VFg(e){let t=0,r=0,n=0;for(let i of e)switch(i.severity){case"fatal":t+=1;continue;case"error":r+=1;continue;case"warning":n+=1;continue;default:Ze(i.severity)}return{numFatal:t,numErrors:r,numWarnings:n}}Wn();nf();gt();qde();Pt();function GFg(e,t,r){let n;try{n=yw(r,t)}catch(i){throw new T({message:`Failed to compare versions: ${Zn(i)}`,code:T.Code.VersionError})}if(!n)return[{severity:"fatal",message:`The generator ${e} requires CLI version ${t} or later (current version: ${r}). Please run \`fern upgrade\` to upgrade your CLI version and use this generator.`}]}function qFg(e){return Number(e.replace("v",""))}var G1s={name:"compatible-ir-version",create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e,cliVersion:t})=>{if(t==null||t==="0.0.0")return[];let r=Ihr({token:void 0}),n=await r.generators.cli.getCliRelease(t);if(!n.ok)return[];let i=n.body.irVersion,o="image"in e?e.image.name:e.name,s;if(e["ir-version"]!=null)s=qFg(e["ir-version"]);else{let c={...e,name:eh(o)},l=await gMe(c);if(l==null)return[];s=l}if(s<=i)return[];let a=await r.generators.cli.getMinCliForIr(s);return a.ok?GFg(o,a.body.version,t)??[]:[]}}})};Wn();var q1s={name:"no-direct-rubygems-publishing",checkOnly:!0,create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e})=>Qr.isDirectRubyGemsPublishing(e)?[{severity:"error",message:Qr.DIRECT_RUBYGEMS_PUBLISHING_UNSUPPORTED_MESSAGE}]:[]}})};Wn();var W1s={name:"unsigned-maven-publishing",create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e})=>{if(!Qr.isUnsignedMavenPublishingWithoutUrl(e))return[];let t="image"in e?e.image.name:e.name;return[{severity:"warning",message:Qr.getUnsignedMavenPublishingWithoutUrlMessage(t)}]}}})};var H1s={name:"valid-alias-group-references",create:async()=>({generatorsYml:{file:async e=>{let t=[],r=e.aliases,n=e.groups??{};if(r==null)return t;let i=new Set(Object.keys(n));for(let[o,s]of Object.entries(r))if(Array.isArray(s))for(let a of s)i.has(a)||t.push({severity:"error",message:`Alias "${o}" references unknown group "${a}". Available groups: ${[...i].join(", ")||"none"}`});return t}}})};function Dip(){return[G1s,q1s,W1s,H1s]}Wn();rr();gt();async function Rip({groups:e,visitor:t,nodePath:r,cliVersion:n}){if(e!=null)for(let[i,o]of Object.entries(e))await WFg({group:o,visitor:t,nodePath:[...r,i],cliVersion:n})}async function WFg({group:e,visitor:t,nodePath:r,cliVersion:n}){await Promise.all(e.generators.map(async(i,o)=>await t.generatorInvocation?.({invocation:i,cliVersion:n},[...r,"generators",o.toString(),"image"in i?i.image.name:i.name])))}async function kip(e,t,r){await r.file?.(e,[]),await rU(e,{"auth-schemes":St,api:St,whitelabel:St,metadata:St,readme:St,"default-group":St,aliases:St,reviewers:St,openapi:St,"openapi-overrides":St,"spec-origin":St,"async-api":St,"api-settings":St,ai:St,autorelease:St,replay:St,automation:St,groups:async n=>{await Rip({groups:n,visitor:r,nodePath:["groups"],cliVersion:t})}})}function Fip({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(o){let s=async(a,c)=>{for(let{name:l,visitors:u}of r){let p=u.generatorsYml?.[o];if(p!=null){let d=await p(a,{relativeFilepath:e,contents:t});n(d.map(f=>({name:l,severity:f.severity,relativeFilepath:e,nodePath:c,message:f.message})))}}};return{[o]:s}}return{...i("file"),...i("generatorInvocation")}}async function cEi(e,t,{includeCheckOnlyRules:r=!1}={}){let n=Dip().filter(i=>r||i.checkOnly!==!0);return HFg({workspace:e,rules:n,logger:t})}async function HFg({workspace:e,rules:t,logger:r}){let n=[],i=await Promise.all(t.map(async o=>({name:o.name,visitors:await o.create({workspace:e,logger:r})})));if(e.generatorsConfiguration?.rawConfiguration){let o=await KFg({contents:e.generatorsConfiguration.rawConfiguration,allRuleVisitors:i,cliVersion:e.cliVersion});n.push(...o)}return n}async function KFg({contents:e,allRuleVisitors:t,cliVersion:r}){let n=[],i=Fip({relativeFilepath:Ee.of(ml),contents:e,allRuleVisitors:t,addViolations:o=>{n.push(...o)}});return await kip(e,r,i),n}Pt();var K1s=Ae(jip(),1);async function J1s({workspace:e,context:t,ossWorkspace:r}){(0,K1s.default)(e.definition.rootApiFile.contents.name).validForNewPackages||t.failAndThrow("API name is not valid.",void 0,{code:T.Code.ValidationError});let n=performance.now(),i=n4e(e,t.logger),o=await cEi(e,t.logger,{includeCheckOnlyRules:!0}),s=[...i,...o];r&&s.push(...await dSe(r,t));let a=performance.now()-n,c=s.some(l=>l.severity==="fatal"||l.severity==="error");return{apiName:e.definition.rootApiFile.contents.name,violations:s,elapsedMillis:a,hasErrors:c}}async function zip({workspace:e,context:t,logWarnings:r,logSummary:n=!0,ossWorkspace:i}){let o=performance.now(),s=n4e(e,t.logger),a=await cEi(e,t.logger),c=[...s,...a];i&&c.push(...await dSe(i,t));let l=performance.now()-o,{hasErrors:u}=gAe({violations:c,context:t,logWarnings:r,logSummary:n,elapsedMillis:l});return{hasErrors:u}}async function aY({workspace:e,context:t,logWarnings:r,ossWorkspace:n}){(0,K1s.default)(e.definition.rootApiFile.contents.name).validForNewPackages||t.failAndThrow("API name is not valid.",void 0,{code:T.Code.ValidationError});let{hasErrors:i}=await zip({workspace:e,context:t,logWarnings:r,ossWorkspace:n});i&&t.failAndThrow(void 0,void 0,{code:T.Code.ValidationError})}c0();rr();ic();Ad();Zhe();Pt();vQ();ln();var Ngp=require("crypto"),G$t=require("fs/promises");Co();var V$t=Ae(WX(),1),CBs=require("path");gt();ss();var Yip=Ae(FA(),1),Yt=w.string().min(1),Vae=Yt.refine(e=>!/^(?:[\\/]|[A-Za-z]:)/.test(e)&&!e.split(/[\\/]/).some(t=>t===".."),{message:"must be a relative path without parent directory segments"}),$1s=Yt.refine(e=>!/^(?:[\\/]|[A-Za-z]:)/.test(e),{message:"must be a relative path"}),Xip=w.string().refine(e=>e.trim()!==e||!/^\d/.test(e)?!1:Yip.default.parse(e,{loose:!1})?.raw===e,{message:"must be an exact semantic version"}),m$t=w.lazy(()=>w.union([w.null(),w.boolean(),w.number(),w.string(),w.array(m$t),w.record(w.string(),m$t)])),Twt=w.record(w.string(),m$t),Zip=w.enum(["sha1","sha256","sha384","sha512"]),$ip=w.enum(["base64","hex"]),$Fg=w.enum(["body","timestamp","notification-url","message-id"]),e2g=w.strictObject({components:w.array($Fg).min(1).describe("Payload components concatenated in declaration order before signing."),delimiter:w.string().optional().describe("The delimiter inserted between payload components."),bodySort:w.literal("alphabetical").optional().describe("Canonicalizes form body keys and values alphabetically before signing.")}),t2g=w.strictObject({header:Yt.describe("The request header containing the signing timestamp."),format:w.enum(["unix-seconds","unix-millis","iso8601"]).optional().describe("The timestamp format used in the signature payload."),tolerance:w.number().positive().optional().describe("The maximum accepted timestamp age, in seconds.")}),r2g=w.discriminatedUnion("type",[w.strictObject({type:w.literal("query-parameter").describe("Reads the body hash from a query parameter."),name:Yt.describe("The query parameter containing the body hash.")})]),n2g=w.strictObject({algorithm:Zip.describe("The hash algorithm applied to the raw request body."),encoding:$ip.optional().describe("The encoding used for the body hash."),location:r2g.describe("Where the expected body hash is read from.")}),i2g=w.strictObject({portVariants:w.boolean().optional().describe("Whether verification tries URLs with and without an explicit default port."),legacyQueryEncoding:w.boolean().optional().describe("Whether verification also tries legacy form-style query encoding.")}).refine(({portVariants:e,legacyQueryEncoding:t})=>e===!0||t===!0,{message:"url normalization must enable at least one variant"}),o2g=w.discriminatedUnion("type",[w.strictObject({type:w.literal("hmac").describe("Identifies HMAC webhook signature verification."),header:Yt.describe("The request header containing the signature."),algorithm:Zip.optional().describe("The HMAC hash algorithm."),encoding:$ip.optional().describe("The encoding used for the HMAC signature."),signaturePrefix:w.string().optional().describe("A prefix removed from the signature header before comparison."),payloadFormat:e2g.optional().describe("How the payload signed by the provider is assembled."),timestamp:t2g.optional().describe("Timestamp validation included in signature verification."),bodyHashBinding:n2g.optional().describe("A separately transmitted hash that binds the raw body to the signed payload."),urlNormalization:i2g.optional().describe("Alternate notification URL forms accepted during verification.")})]),fEi=w.strictObject({name:Yt.optional().describe("The parameter name exposed by the SDK."),environmentVariable:Yt.optional().describe("The environment variable used to populate the parameter."),description:w.string().optional().describe("A description of the authentication parameter included in generated SDK documentation."),omit:w.boolean().optional().describe("Whether the parameter is omitted from the SDK surface.")}),s2g=w.strictObject({id:Yt.describe("A unique identifier for this authentication scheme."),type:w.literal("api-key").describe("Identifies an API key authentication scheme."),location:w.enum(["header","query","cookie"]).describe("Where the API key is sent on requests."),name:Yt.describe("The header, query parameter, or cookie name."),prefix:Yt.optional().describe("A prefix added before the API key value."),environmentVariable:Yt.optional().describe("The default environment variable for the API key."),description:w.string().optional().describe("A description of the authentication scheme included in generated SDK documentation.")}),a2g=w.strictObject({id:Yt.describe("A unique identifier for this authentication scheme."),type:w.literal("bearer").describe("Identifies a bearer token authentication scheme."),header:Yt.optional().describe("The request header that carries the bearer token."),prefix:Yt.optional().describe('The token prefix, such as "Bearer".'),environmentVariable:Yt.optional().describe("The default environment variable for the bearer token."),description:w.string().optional().describe("A description of the authentication scheme included in generated SDK documentation.")}),c2g=w.strictObject({id:Yt.describe("A unique identifier for this authentication scheme."),type:w.literal("basic").describe("Identifies an HTTP Basic authentication scheme."),username:fEi.optional().describe("The username parameter exposed by the SDK."),password:fEi.optional().describe("The password parameter exposed by the SDK."),description:w.string().optional().describe("A description of the authentication scheme included in generated SDK documentation.")}),d$t=w.strictObject({name:Yt.describe("The OAuth scope value requested from the provider."),description:w.string().optional().describe("A description of the OAuth scope included in generated SDK documentation.")}),Qip=Yt.refine(e=>e.trim()===e,{message:"must not have leading or trailing whitespace"}).refine(e=>!e.includes("${"),{message:"must be a literal public client ID, not an environment expression"}),Swt=w.record(w.string().min(1),w.string());function eop(e){try{return new URL(e)}catch{return}}var l2g=Yt.refine(e=>{let t=eop(e);return t!==void 0&&t.protocol==="http:"&&(t.hostname==="127.0.0.1"||t.hostname==="localhost")&&t.port!==""},{message:"must be an http URL on 127.0.0.1 or localhost that pins a port, such as http://127.0.0.1:8484/callback"});function u2g(e){return[...e].some(t=>{let r=t.charCodeAt(0);return r<=31||r===127})}var Mip=Yt.refine(e=>{let t=eop(e);return t!==void 0&&(t.protocol==="http:"||t.protocol==="https:")},{message:"must be an absolute http or https URL"}).refine(e=>!u2g(e),{message:"must not contain control characters"}),p2g=w.number().int().min(1).max(65535),f2g=w.discriminatedUnion("type",[w.strictObject({type:w.literal("authorization-code").describe("Uses the OAuth authorization code flow."),authorizationUrl:Yt.describe("The URL used to authorize the client."),tokenUrl:Yt.describe("The URL used to exchange a code for tokens."),refreshUrl:Yt.optional().describe("The URL used to refresh access tokens."),scopes:w.array(d$t).optional().describe("The scopes supported by this flow."),clientId:Qip.optional().describe("The public, non-secret OAuth client ID that generated interactive login flows, such as CLI browser login with PKCE, send to the authorization and token endpoints. It is embedded verbatim in generated code, so it must never be a client secret."),redirectUri:l2g.optional().describe("The loopback callback of the interactive login, such as http://127.0.0.1:8484/callback. The login binds this exact host, port and path and sends it to the authorization server, so it must match the redirect registered there. Without it the login uses a free port chosen by the operating system."),redirectUriBackupPorts:w.array(p2g).min(1).optional().describe("Ports tried in order when the port of redirectUri is busy. Each reuses the host and path of redirectUri, and every resulting URI must be registered with the authorization server. Requires redirectUri."),successRedirectUrl:Mip.optional().describe("A page the browser is sent to once the login captured the authorization code. Without it the login shows its own page."),errorRedirectUrl:Mip.optional().describe("A page the browser is sent to when the login fails; the error and error_description query parameters are added. Without it the login shows its own page."),authorizationParameters:Swt.optional().describe("Extra parameters added to the authorization request, such as audience."),tokenParameters:Swt.optional().describe("Extra parameters added to the authorization code exchange request."),refreshParameters:Swt.optional().describe("Extra parameters added to the token refresh request.")}).refine(e=>e.redirectUriBackupPorts===void 0||e.redirectUri!==void 0,{message:"redirectUriBackupPorts requires redirectUri",path:["redirectUriBackupPorts"]}),w.strictObject({type:w.literal("client-credentials").describe("Uses the OAuth client credentials flow."),tokenUrl:Yt.describe("The URL used to obtain access tokens."),refreshUrl:Yt.optional().describe("The URL used to refresh access tokens."),scopes:w.array(d$t).optional().describe("The scopes supported by this flow.")}),w.strictObject({type:w.literal("implicit").describe("Uses the OAuth implicit flow."),authorizationUrl:Yt.describe("The URL used to authorize the client."),refreshUrl:Yt.optional().describe("The URL used to refresh access tokens."),scopes:w.array(d$t).optional().describe("The scopes supported by this flow.")}),w.strictObject({type:w.literal("password").describe("Uses the OAuth resource owner password flow."),tokenUrl:Yt.describe("The URL used to obtain access tokens."),refreshUrl:Yt.optional().describe("The URL used to refresh access tokens."),scopes:w.array(d$t).optional().describe("The scopes supported by this flow.")}),w.strictObject({type:w.literal("device-code").describe("Uses the OAuth device authorization flow (RFC 8628) for logins without a browser."),clientId:Qip.describe("The public, non-secret OAuth client ID sent to the device authorization and token endpoints. It is embedded verbatim in generated code, so it must never be a client secret."),deviceAuthorizationUrl:Yt.describe("The URL that issues the device code, the user code and the verification URL."),tokenUrl:Yt.describe("The URL polled to exchange the device code for tokens once the user approved."),refreshUrl:Yt.optional().describe("The URL used to refresh access tokens."),scopes:w.array(d$t).optional().describe("The scopes supported by this flow."),deviceAuthorizationParameters:Swt.optional().describe("Extra parameters added to the device authorization request, such as audience."),tokenParameters:Swt.optional().describe("Extra parameters added to the token polling request."),refreshParameters:Swt.optional().describe("Extra parameters added to the token refresh request.")})]),d2g=w.strictObject({id:Yt.describe("A unique identifier for this authentication scheme."),type:w.literal("oauth2").describe("Identifies an OAuth 2.0 authentication scheme."),flows:w.array(f2g).min(1).describe("The OAuth flows supported by the API."),clientId:fEi.optional().describe("The OAuth client ID parameter exposed by the SDK."),clientSecret:fEi.optional().describe("The OAuth client secret parameter exposed by the SDK."),tokenHeader:Yt.optional().describe("The request header that carries the OAuth access token."),tokenPrefix:Yt.optional().describe('The prefix added before the OAuth access token. Defaults to "Bearer" when omitted.'),omitTokenPrefix:w.boolean().optional().describe('Whether the OAuth access token is sent as-is, with no prefix. Without it, a missing tokenPrefix means "Bearer". Cannot be combined with tokenPrefix.'),refreshBufferSeconds:w.number().nonnegative().optional().describe("How early, in seconds, the client refreshes a token before it expires."),description:w.string().optional().describe("A description of the authentication scheme included in generated SDK documentation.")}),m2g=d2g.refine(e=>!(e.omitTokenPrefix===!0&&e.tokenPrefix!==void 0),{message:"omitTokenPrefix cannot be combined with tokenPrefix",path:["omitTokenPrefix"]}),h2g=w.strictObject({location:w.enum(["header","query","cookie"]).describe("Where the custom authentication value is sent."),name:Yt.describe("The header, query parameter, or cookie name."),prefix:Yt.optional().describe("A prefix added before the parameter value."),environmentVariable:Yt.optional().describe("The default environment variable for the parameter.")}),g2g=w.strictObject({id:Yt.describe("A unique identifier for this authentication scheme."),type:w.literal("custom").describe("Identifies a custom authentication scheme."),parameters:w.array(h2g).min(1).describe("The request parameters that implement the custom scheme."),description:w.string().optional().describe("A description of the authentication scheme included in generated SDK documentation.")}),A2g=w.discriminatedUnion("type",[s2g,a2g,c2g,m2g,g2g]),y2g=w.strictObject({schemes:w.array(Yt).min(1).describe("Scheme identifiers that must be satisfied together.")}),b2g=w.strictObject({schemes:w.array(A2g).min(1).describe("Authentication schemes offered by the API."),requirements:w.array(y2g).optional().describe("Valid combinations of authentication schemes."),endpointSecurity:w.boolean().optional().describe("Whether generated endpoints expose their individual security requirements.")}).superRefine(({requirements:e,schemes:t},r)=>{let n=new Set;t.forEach(({id:i},o)=>{n.has(i)&&r.addIssue({code:"custom",message:`auth scheme id "${i}" must be unique`,path:["schemes",o,"id"]}),n.add(i)}),e?.forEach((i,o)=>{i.schemes.forEach((s,a)=>{n.has(s)||r.addIssue({code:"custom",message:`auth requirement references unknown scheme "${s}"`,path:["requirements",o,"schemes",a]})})})}),E2g=w.strictObject({name:Yt.describe("The display name for this environment URL."),url:Yt.describe("The base URL used for this environment entry."),serverName:Yt.optional().describe("The source server represented by this URL.")}),I2g=w.strictObject({name:Yt.describe("The environment name exposed by the SDK."),urls:w.array(E2g).min(1).describe("The base URLs available in this environment."),description:w.string().optional().describe("A description of the environment included in generated SDK documentation.")}),v2g=w.strictObject({name:Yt.describe("The HTTP header name."),value:w.string().optional().describe("A fixed value for the generated header."),description:w.string().optional().describe("A description of the header included in generated SDK documentation."),environmentVariable:Yt.optional().describe("The environment variable used to populate the header.")}),C2g=w.strictObject({name:Yt.describe("The environment variable name exposed by the SDK."),description:w.string().optional().describe("A description of the environment variable included in generated SDK documentation."),defaultValue:w.string().optional().describe("The default value used when the variable is unset.")}),top=w.strictObject({baseUrl:w.string().default("").describe("The default base URL used by the generated client."),environments:w.array(I2g).default([]).describe("Named API environments and their base URLs."),environmentVariables:w.array(C2g).default([]).describe("Environment variables exposed through generated client configuration."),defaultEnvironment:Yt.optional().describe("The environment selected when a caller does not choose one."),auth:b2g.optional().describe("Authentication supported by the API."),headers:w.array(v2g).optional().describe("Headers added to generated API requests."),audiences:w.array(Yt).optional().describe("Named API audiences included in the generated SDK."),webhookSignature:o2g.optional().describe("How generated helpers verify webhook signatures from the API.")});var x2g=top;var rop={enabled:w.boolean().optional().describe("Whether the generated client retries failed requests."),maxAttempts:w.number().int().min(1).optional().describe("The maximum total request attempts, including the initial attempt."),retryDelayMs:w.number().nonnegative().optional().describe("The initial delay between retry attempts, in milliseconds."),maxDelayMs:w.number().nonnegative().optional().describe("The maximum backoff delay between attempts, in milliseconds."),jitterMs:w.number().nonnegative().optional().describe("The maximum random jitter added to retry delays, in milliseconds."),backoffFactor:w.number().positive().optional().describe("The multiplier applied to the delay after each failed attempt."),statusCodes:w.array(w.number().int().min(100).max(599)).optional().describe("HTTP status codes that are eligible for retries."),methods:w.array(Yt).optional().describe("HTTP methods that are eligible for retries."),statusCodeProfile:w.enum(["legacy","recommended"]).optional().describe("The built-in retryable status-code policy."),maxRetryAfterDelayMs:w.number().nonnegative().optional().describe("The longest Retry-After delay the client will honor, in milliseconds.")};function nop({maxDelayMs:e,retryDelayMs:t},r){e!==void 0&&t!==void 0&&e<t&&r.addIssue({code:"custom",message:"maxDelayMs must be greater than or equal to retryDelayMs",path:["maxDelayMs"]})}var S2g=w.strictObject(rop).superRefine(nop),w2g=w.strictObject({...rop,enabled:w.boolean().default(!0).describe("Whether the generated client retries failed requests."),maxAttempts:w.number().int().min(1).default(3).describe("The maximum total request attempts, including the initial attempt."),retryDelayMs:w.number().nonnegative().default(150).describe("The initial delay between retry attempts, in milliseconds."),maxDelayMs:w.number().nonnegative().default(5e3).describe("The maximum backoff delay between attempts, in milliseconds."),jitterMs:w.number().nonnegative().default(50).describe("The maximum random jitter added to retry delays, in milliseconds."),backoffFactor:w.number().positive().default(2).describe("The multiplier applied to the delay after each failed attempt."),methods:w.array(Yt).default(["GET","PUT","DELETE","HEAD","OPTIONS"]).describe("HTTP methods that are eligible for retries."),maxRetryAfterDelayMs:w.number().nonnegative().default(6e4).describe("The longest Retry-After delay the client will honor, in milliseconds.")}).superRefine(nop),iop=w.strictObject({name:Yt.describe("The parameter name in the generated client constructor."),example:w.string().optional().describe("An example value shown in generated documentation."),description:w.string().optional().describe("A description of the constructor parameter included in generated SDK documentation."),required:w.boolean().optional().describe("Whether callers must provide the parameter.")}),Y1s=w.enum(["wrapped","inline","language-default"]),T2g=w.strictObject({enabled:w.boolean().describe("Whether the client can exchange refresh tokens."),endpoint:Yt.optional().describe("The API endpoint used to refresh tokens."),accessTokenField:Yt.optional().describe("The response field containing the refreshed access token."),refreshTokenField:Yt.optional().describe("The response field containing the refreshed refresh token.")}).superRefine(({enabled:e,endpoint:t},r)=>{e&&t===void 0&&r.addIssue({code:"custom",message:"endpoint is required when tokenRefresh is enabled",path:["endpoint"]})}),O2g=w.strictObject({enabled:w.boolean().describe("Whether the client generates an idempotency key when the caller supplies none."),headerName:Yt.optional().describe("The header that carries the generated key. Generators default to Idempotency-Key."),methods:w.array(Yt).optional().describe("HTTP methods that receive a generated key. Generators default to POST and PUT.")}),P2g=w.strictObject({template:Yt.optional().describe("The User-Agent product token, resolved at generation time. Supports the {packageName}, {version}, {language}, {generatorVersion}, {organization}, and {apiName} placeholders."),includePlatformInfo:w.boolean().optional().describe("Whether the User-Agent carries operating system, architecture, and runtime details, as `{product} ({os}; {arch}) {runtime}/{runtimeVersion}`."),allowAppInfo:w.boolean().optional().describe("Whether callers can pass application info that is appended to the User-Agent as a `{name}/{version} ({comment})` product token.")}),oop={retry:S2g.optional().describe("Retry behavior for generated API requests."),responseHeaders:w.boolean().optional().describe("Whether generated operations expose HTTP response headers."),responseValidation:w.boolean().optional().describe("Whether the client validates API responses against the schema."),multiTenant:w.boolean().optional().describe("Whether the client exposes configuration for tenant-specific API access."),additionalConstructorParameters:w.array(iop).optional().describe("Additional parameters added to the generated client constructor."),timeoutMs:w.union([w.number().nonnegative(),w.literal("infinity")]).optional().describe('The default request timeout in milliseconds, or "infinity" for no timeout.'),requestParameterStyle:Y1s.optional().describe("Whether generated operation parameters are wrapped or passed inline."),pathParameterStyle:Y1s.optional().describe("Whether generated path parameters are wrapped or passed inline."),filePropertyStyle:Y1s.optional().describe("Whether generated file properties are wrapped or passed inline."),useDefaultRequestParameterValues:w.boolean().optional().describe("Whether schema defaults are applied to omitted request parameters."),respectOptionalRequestBody:w.boolean().optional().describe("Whether an optional request body remains optional in generated methods."),tokenRefresh:T2g.optional().describe("Refresh-token behavior for the generated client."),idempotencyKeyGeneration:O2g.optional().describe("Automatic idempotency keys on eligible requests."),userAgent:P2g.optional().describe("The User-Agent header the generated client sends."),offsetSemantics:w.enum(["item-index","page-index"]).optional().describe("How an offset-paginated endpoint advances: by the number of items returned, or by one page.")},B2g=w.strictObject(oop),sop=w.strictObject({...oop,retry:w2g.prefault({}).describe("Retry behavior for generated API requests."),responseHeaders:w.boolean().default(!1).describe("Whether generated operations expose HTTP response headers."),multiTenant:w.boolean().default(!1).describe("Whether the client exposes configuration for tenant-specific API access."),additionalConstructorParameters:w.array(iop).default([]).describe("Additional parameters added to the generated client constructor.")}),D2g=sop,R2g=B2g,aop=Vae.regex(/^(?!.*(?:^|\/)\.{1,2}(?:\/|$))[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*$/,"Go module path must use letters, numbers, dots, dashes, underscores or tildes, in slash-delimited segments"),cop=Yt.regex(/^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]?|-{0,2})[a-z0-9]+)*$/,'Composer package name must be a lowercase "vendor/package" name'),k2g=w.strictObject({name:Yt.describe("The package author name."),email:w.email().optional().describe("The package author email address."),url:Yt.optional().describe("The package author website.")}),F2g=w.strictObject({name:Yt.describe("The package developer name."),email:w.email().optional().describe("The package developer email address."),organization:Yt.optional().describe("The developer organization name."),organizationUrl:Yt.optional().describe("The developer organization website.")}),N2g=w.strictObject({type:Yt.describe("The license identifier or license type."),name:Yt.optional().describe("The human-readable license name."),url:Yt.optional().describe("The URL containing the license text."),path:Yt.optional().describe("The path to a custom license file.")}),j2g=w.discriminatedUnion("type",[w.strictObject({type:w.literal("registry").describe("Resolves the dependency from a package registry."),registry:Yt.optional().describe("The registry used to resolve the dependency.")}),w.strictObject({type:w.literal("git").describe("Resolves the dependency from a Git repository."),url:Yt.describe("The Git repository URL."),ref:Yt.optional().describe("The Git branch, tag, or commit to use."),subdirectory:Yt.optional().describe("The package subdirectory within the Git repository.")}),w.strictObject({type:w.literal("path").describe("Resolves the dependency from a local path."),path:Yt.describe("The local path containing the dependency.")})]),X1s=w.strictObject({name:Yt.describe("The dependency name used by the package manager."),version:Yt.optional().describe("The dependency version requirement."),source:j2g.optional().describe("A non-default source for the dependency."),packageName:Yt.optional().describe("The source package name when it differs from the dependency alias."),features:w.array(Yt).optional().describe("Cargo features enabled for this dependency."),extras:w.array(Yt).optional().describe("Python extras enabled for this dependency."),optional:w.boolean().optional().describe("Whether the dependency is optional."),defaultFeatures:w.boolean().optional().describe("Whether the dependency enables its default Cargo features."),environmentMarker:Yt.optional().describe("A Python environment marker that conditions this dependency.")}).refine(({source:e,version:t})=>e!==void 0||t!==void 0,{message:"dependency must define a version or a source"}),z2g=w.strictObject({url:Yt.optional().describe("The issue tracker URL."),email:Yt.optional().describe("The address for reporting issues.")}).refine(({url:e,email:t})=>e!==void 0||t!==void 0,{message:"bugs must define a url or an email"}),Q2g=w.strictObject({label:Yt.describe("The label displayed for the project link."),url:Yt.describe("The project link URL.")}),lop=w.strictObject({packageName:Yt.optional().describe("The package name used by the target language registry."),moduleName:Yt.optional().describe("The generated module or import name when it differs from the package name."),modulePath:aop.optional().describe("The Go module path used for imports and publishing."),namespace:Yt.optional().describe("The namespace or package prefix for generated code."),groupId:Yt.optional().describe("The Maven group identifier."),artifactId:Yt.optional().describe("The Maven artifact identifier."),description:w.string().optional().describe("The package description used in generated metadata."),repository:Yt.optional().describe("The source repository for the generated SDK."),homepage:Yt.optional().describe("The package homepage URL."),bugs:z2g.optional().describe("Where issues with the package are reported."),documentationUrl:Yt.optional().describe("The package documentation URL."),authors:w.array(k2g).optional().describe("Authors credited in package metadata."),developers:w.array(F2g).optional().describe("Developers credited in package metadata."),license:N2g.optional().describe("License metadata for the generated package."),keywords:w.array(Yt).optional().describe("Search keywords for package metadata."),classifiers:w.array(Yt).optional().describe("Package classifiers used by registries such as PyPI."),projectUrls:w.array(Q2g).optional().describe("Labeled project links for package metadata."),extraDependencies:w.array(X1s).optional().describe("Additional runtime dependencies added to the generated package."),extraDevDependencies:w.array(X1s).optional().describe("Additional development dependencies added to the generated package."),extraPeerDependencies:w.array(X1s).optional().describe("Additional peer dependencies added to the generated package."),extraPeerDependenciesMeta:w.record(Yt,Twt).optional().describe("npm peerDependenciesMeta entries keyed by peer dependency name, such as { optional: true }.")}),M2g=/^[A-Z][A-Z0-9_]*$/,L2g=/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/,_2g=/^[a-z][a-z0-9-]*$/,dEi=w.string({error:"must be the name of a GitHub Actions secret"}).regex(M2g,{error:"must be the name of a GitHub Actions secret: start with an uppercase letter and contain only A-Z, 0-9, or _. Secret values and ${...} expressions are not accepted."}).refine(e=>e!=="GITHUB_TOKEN",{error:"GITHUB_TOKEN cannot be used: it is the workflow's built-in token, scoped to the generated repository. Store the credential under a different secret name."}),uop=w.string({error:'must be a GitHub repository in "<owner>/<repo>" form'}).regex(L2g,{error:'must be a GitHub repository in "<owner>/<repo>" form, for example "acme/homebrew-tap"'}),U2g=w.string({error:"must be a Homebrew formula name"}).regex(_2g,{error:"must be a Homebrew formula name: start with a lowercase letter and contain only a-z, 0-9, or -"}),V2g=w.strictObject({appIdSecretName:dEi.describe("The name of the GitHub Actions secret holding the GitHub App ID or client ID."),privateKeySecretName:dEi.describe("The name of the GitHub Actions secret holding the GitHub App private key in PEM form.")}),pop="The name of the GitHub Actions secret holding a token with write access to the channel repository. Takes precedence over githubApp for this channel.",G2g=w.strictObject({tap:uop.describe('The Homebrew tap repository in "<owner>/<repo>" form that receives the formula.'),formula:U2g.optional().describe("The Homebrew formula name; the generator defaults it to the CLI binary name."),tokenSecretName:dEi.optional().describe(pop)}),q2g=w.strictObject({bucket:uop.describe('The Scoop bucket repository in "<owner>/<repo>" form that receives the manifest.'),tokenSecretName:dEi.optional().describe(pop)}),fop=w.strictObject({githubApp:V2g.optional().describe("A GitHub App used to mint short-lived tokens for every channel without its own tokenSecretName."),homebrew:G2g.optional().describe("Publishes a Homebrew formula to a tap repository on each tagged release."),scoop:q2g.optional().describe("Publishes a Scoop manifest to a bucket repository on each tagged release."),githubAttestations:w.union([w.literal("auto"),w.boolean()],{error:'must be "auto", true, or false'}).optional().describe('Whether the generated release workflow attests build provenance. "auto" (the generator default) attests only on public repositories; true always attests, for private repositories on GitHub Enterprise Cloud; false omits the attestation step and its permissions.')}).superRefine((e,t)=>{if(!(e.homebrew!==void 0||e.scoop!==void 0)){if(e.githubApp!==void 0){t.addIssue({code:"custom",message:"githubApp requires at least one distribution channel: homebrew or scoop",path:["githubApp"]});return}e.githubAttestations===void 0&&t.addIssue({code:"custom",message:"distribution must configure at least one channel: homebrew or scoop"})}}),dop='distribution requires output.delivery "github": Homebrew and Scoop publish from a tagged GitHub Release produced by the generated release workflow. Set delivery to "github" or remove distribution.',mop='package publication for target language "cli" requires output.delivery "github": the CLI generator publishes npm packages only from its generated GitHub workflow.';var W2g=w.enum(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE","CONNECT"]),Lip=w.strictObject({method:W2g.describe("The HTTP method of the documented endpoint."),path:Yt.describe("The endpoint path used in generated examples."),stream:w.boolean().optional().describe("Whether the example uses the streaming response API.")}),H2g=w.strictObject({title:Yt.describe("The heading displayed for this README section."),content:w.string().describe("The Markdown content of this README section.")}),K2g=w.strictObject({apiName:Yt.optional().describe("The API name displayed in the README."),introduction:w.string().optional().describe("Custom introductory Markdown for the README."),apiReferenceLink:Yt.optional().describe("The URL linked as the API reference."),bannerLink:Yt.optional().describe("The destination URL for the README banner."),disabledSections:w.array(Yt).optional().describe("Generated README sections to omit."),customSections:w.array(H2g).optional().describe("Additional sections inserted into the README."),defaultEndpoint:Lip.optional().describe("The endpoint used for the primary README example."),features:w.record(w.string(),w.array(Lip)).optional().describe("Named feature groups and the endpoints demonstrated by each group.")}),J2g=w.strictObject({enabled:w.boolean().describe("Whether standalone usage snippets are generated."),format:w.enum(["md","json"]).optional().describe("The output format for generated snippets."),outputPath:Yt.optional().describe("The output path for generated snippet files.")}),hop=w.strictObject({readme:K2g.optional().describe("README content and example configuration."),snippets:J2g.optional().describe("Standalone usage snippet generation."),referenceBaseUrl:Yt.optional().describe("The base URL used for links to generated API reference files."),includeApiReference:w.boolean().optional().describe("Whether API reference documentation is included in the SDK output.")});var gop=hop;var Y2g=/[A-Za-z0-9]/,X2g=/^[a-z][a-z0-9_-]*$/,Aop=/^[a-z][a-z0-9-]*$/,Z2g=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/,eTs=/^[A-Za-z0-9_.-]+$/,$2g=new Set(["params","output","json","format","dry-run","base-url","page-all","page-limit","page-delay","no-pager","no-extract","no-retry","no-stream","quiet","query","help","debug","schema"]),eNg=new Set(["auth","completion","man","errors","generate-skills","help"]),tNg=Yt.regex(Y2g,{message:"binaryName must contain at least one ASCII letter or digit"}),rNg=w.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,{message:"crateName must start with a letter, contain only letters, digits, hyphens, and underscores, and be at most 64 characters"}),nNg=w.string().regex(X2g,{message:"rootGroup must start with a lowercase letter and contain only lowercase letters, digits, hyphens, and underscores"}),iNg=w.string().superRefine((e,t)=>{e.startsWith("-")?t.addIssue({code:"custom",message:'userAgentSuffixFlag must be the long flag name without the leading "--"'}):Aop.test(e)?$2g.has(e)&&t.addIssue({code:"custom",message:`userAgentSuffixFlag "${e}" collides with a built-in global flag`}):t.addIssue({code:"custom",message:"userAgentSuffixFlag must start with a lowercase letter and contain only lowercase letters, digits, and hyphens"})}),oNg=w.string().superRefine((e,t)=>{Aop.test(e)?eNg.has(e)&&t.addIssue({code:"custom",message:`profiles.commandName "${e}" collides with a built-in command group`}):t.addIssue({code:"custom",message:"profiles.commandName must start with a lowercase letter and contain only lowercase letters, digits, and hyphens"})});function yop(e){return w.string().regex(Z2g,{message:`${e} must be a dotted command path such as "iam.keys.create"`})}function _ip(e){let t=`${e} keys and values must be field names containing only [A-Za-z0-9_.-]`;return w.record(w.string(),w.string().regex(eTs,{message:t})).superRefine((r,n)=>{for(let i of Object.keys(r))eTs.test(i)||n.addIssue({code:"custom",message:t,path:[i]})})}var sNg=w.strictObject({operation:yop("profiles.provisionOperation.operation").describe("The dotted command path of the operation that mints a profile credential."),credential:_ip("profiles.provisionOperation.credential").refine(e=>Object.keys(e).length>0,{message:"profiles.provisionOperation.credential must map at least one credential field"}).describe("Maps each stored credential field to the response field that supplies it."),revokeParameters:_ip("profiles.provisionOperation.revokeParameters").optional().describe("Maps each revoke-operation parameter to the response field that supplies it.")}),aNg=w.strictObject({enabled:w.boolean().describe("Whether the CLI emits profile commands and the global --profile flag."),commandName:oNg.optional().describe('The profile command group name. The generator defaults to "profiles".'),revokeOperation:yop("profiles.revokeOperation").optional().describe('The dotted command path called by "profiles remove --revoke".'),provisionOperation:sNg.optional().describe('The operation called by "profiles create --provision" and its response mapping.')}),x9e=w.string().regex(eTs,{message:'must be a property name, or a dotted path to a nested property, such as "data.token"'}).regex(/^[^.]+(\.[^.]+)*$/,{message:"must not have an empty path segment"}),cNg=w.strictObject({clientId:x9e.optional().describe('The request property that carries the client ID. Defaults to "client_id".'),clientSecret:x9e.optional().describe('The request property that carries the client secret. Defaults to "client_secret".'),scopes:x9e.optional().describe('The request property that carries the scopes. Defaults to "scope".')}),Uip=w.strictObject({accessToken:x9e.optional().describe('The response property that holds the access token. Defaults to "access_token".'),expiresIn:x9e.optional().describe('The response property that holds the lifetime in seconds. Defaults to "expires_in".'),refreshToken:x9e.optional().describe('The response property that holds the refresh token. Defaults to "refresh_token".')}),lNg=w.strictObject({token:w.strictObject({requestProperties:cNg.optional().describe("The names of the properties of the token request."),responseProperties:Uip.optional().describe("The names of the properties of the token response.")}).optional().describe("The token endpoint of the client credentials flow (its tokenUrl)."),refresh:w.strictObject({requestProperties:w.strictObject({refreshToken:x9e.optional().describe('The request property that carries the refresh token. Defaults to "refresh_token".')}).optional().describe("The names of the properties of the refresh request."),responseProperties:Uip.optional().describe("The names of the properties of the refresh response.")}).optional().describe("The refresh endpoint of the client credentials flow (its refreshUrl).")});function bop(e,t,r){let n=new Map;for(let i of t??[]){let o=i.type==="oauth2"?i.flows?.find(s=>s.type==="client-credentials"):void 0;o!==void 0&&n.set(i.id,o)}return Object.entries(e??{}).flatMap(([i,o])=>{let s=n.get(i);return s===void 0?[{message:`oauthTokenEndpoints "${i}" must name an OAuth scheme with a client-credentials flow`,path:[...r,i]}]:o.refresh!==void 0&&s.refreshUrl===void 0?[{message:`oauthTokenEndpoints "${i}" has refresh settings, but its flow has no refreshUrl`,path:[...r,i,"refresh"]}]:[]})}var Eop=w.strictObject({paginationParameters:w.array(Yt).optional().describe("Request parameter names treated as pagination controls by the CLI."),skills:w.boolean().optional().describe("Whether the generated CLI includes skills that teach AI agents to invoke commands."),binaryName:tNg.optional().describe("The CLI executable name. The generator kebab-cases it and also uses it for the source directory and env-var prefix."),crateName:rNg.optional().describe("The name of the generated Cargo package, which release archives and installers are named after. The generator defaults it to the binary name when the output is delivered to GitHub."),customCommands:w.boolean().optional().describe("Whether hand-written command support is generated. The generator defaults to true."),rootGroup:nNg.optional().describe("A command group that every spec-derived command is nested under."),profiles:aNg.optional().describe("Named profile command configuration."),splitTypeCrates:w.boolean().optional().describe("Whether generated types are split into one crate per API behind a facade crate."),userAgentSuffixFlag:iNg.optional().describe('The long flag name, without "--", that appends a product token to the User-Agent.'),oauthTokenEndpoints:w.record(Yt,lNg).optional().describe("Per OAuth scheme id (api.auth.schemes[].id), the names of the properties of the token and refresh requests and responses, for the client credentials flow of an API whose token endpoint does not use the RFC 6749 names.")});var Iop=lop,hhO=w.email();var wwt=Symbol("omit");function vop(e){return w.toJSONSchema(e,{io:"input",unrepresentable:"any"})}function uNg(e,t){let r=pEi(e,t,t,!0);return r===wwt?void 0:r}function pEi(e,t,r,n){let i=tTs(t,r);if(n&&Object.hasOwn(i,"default")&&S9e(e,i.default))return wwt;let o=fNg(e,i,r);if(n&&o!==i&&Object.hasOwn(o,"default")&&S9e(e,o.default))return wwt;if(Array.isArray(e))return o.items?e.map(l=>{let u=pEi(l,o.items,r,n);return u===wwt?l:u}):e;if(!mEi(e)||o.type!=="object")return e;let s=[],a=o.properties??{},c=n?a:pNg(i,r);for(let[l,u]of Object.entries(a)){if(!Object.hasOwn(e,l))continue;let p=pEi(e[l],u,r,n);p!==wwt&&s.push([l,p])}for(let[l,u]of Object.entries(e))if(!Object.hasOwn(a,l)){if(Object.hasOwn(c,l)){s.push([l,u]);continue}if(o.additionalProperties!==!1){let p=typeof o.additionalProperties=="object"?pEi(u,o.additionalProperties,r,n):u;p!==wwt&&s.push([l,p])}else if(n)throw new Error(`Cannot serialize property unknown to the wire schema: ${l}`)}return Object.fromEntries(s)}function pNg(e,t){let r=e.oneOf??e.anyOf;return r?Object.assign({},...r.map(n=>tTs(n,t).properties??{})):e.properties??{}}function fNg(e,t,r){let n=t.oneOf??t.anyOf;if(!n||n.length===0)return t;let i=n.map((o,s)=>{let a=tTs(o,r);return{index:s,schema:a,score:dNg(e,a)}}).sort((o,s)=>s.score-o.score||o.index-s.index)[0];return i.score===Number.NEGATIVE_INFINITY?t:i.schema}function dNg(e,t){if(Object.hasOwn(t,"const")&&!S9e(e,t.const)||t.enum&&!t.enum.some(r=>S9e(e,r)))return Number.NEGATIVE_INFINITY;if(t.type==="object"){if(!mEi(e))return Number.NEGATIVE_INFINITY;let r=t.properties??{};for(let[n,i]of Object.entries(r))if(Object.hasOwn(e,n)&&Object.hasOwn(i,"const")&&!S9e(e[n],i.const))return Number.NEGATIVE_INFINITY;return Object.keys(e).filter(n=>Object.hasOwn(r,n)).length}return t.type==="array"?Array.isArray(e)?1:Number.NEGATIVE_INFINITY:t.type==="string"?typeof e=="string"?1:Number.NEGATIVE_INFINITY:t.type==="number"||t.type==="integer"?typeof e=="number"?1:Number.NEGATIVE_INFINITY:t.type==="boolean"?typeof e=="boolean"?1:Number.NEGATIVE_INFINITY:t.type==="null"?e===null?1:Number.NEGATIVE_INFINITY:0}function tTs(e,t){if(!e.$ref||!e.$ref.startsWith("#/$defs/"))return e;let r=e.$ref.slice(8).replaceAll("~1","/").replaceAll("~0","~");return t.$defs?.[r]??e}function mEi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function S9e(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,n)=>S9e(r,t[n]));if(mEi(e)&&mEi(t)){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>Object.hasOwn(t,i)&&S9e(e[i],t[i]))}return!1}var Cop=w.strictObject({clientName:Yt.optional().describe("The generated client class name."),exportedClientName:Yt.optional().describe("The client name exported from the generated package."),environmentTypeName:Yt.optional().describe("The generated type name for API environments."),apiErrorName:Yt.optional().describe("The generated API error class name."),baseErrorName:Yt.optional().describe("The generated base error class name."),pagerName:Yt.optional().describe("The generated pagination helper name."),smartCasing:w.boolean().optional().describe("Whether generated identifiers use initialism-aware casing."),smartCasingDigitWordBoundary:w.boolean().optional().describe("Whether smart casing preserves a word boundary after digits.")}),mNg=w.discriminatedUnion("type",[w.strictObject({type:w.literal("path").describe("Loads the generation asset from a relative path."),location:Vae.describe("The relative path to the generation asset.")}),w.strictObject({type:w.literal("url").describe("Loads the generation asset from a URL."),location:Yt.describe("The URL of the generation asset.")})]),hNg=w.strictObject({enabled:w.boolean().describe("Whether customer-authored code is merged into generated output."),source:mNg.optional().describe("The source containing customer-authored code."),conflictStrategy:w.enum(["mark","ours","theirs"]).optional().describe("How merge conflicts between generated and custom code are handled."),trackChanges:w.boolean().optional().describe("Whether custom-code changes are tracked between builds."),protectedFiles:w.array(Yt).optional().describe("Generated file paths that custom-code merging must not overwrite.")}),gNg=w.strictObject({name:Yt.describe("The exported telemetry header name."),value:w.string().describe("The literal telemetry header value.")}),ANg=w.strictObject({enabled:w.boolean().describe("Whether generated clients export usage telemetry."),endpoint:Yt.optional().describe("The telemetry export endpoint."),exporter:w.enum(["otlp-http","console"]).optional().describe("The telemetry exporter implementation."),headers:w.array(gNg).optional().describe("Headers sent by the telemetry exporter."),batchSize:w.number().int().positive().optional().describe("The maximum spans in each export batch."),scheduledDelayMs:w.number().nonnegative().optional().describe("The delay between scheduled exports, in milliseconds."),exportTimeoutMs:w.number().nonnegative().optional().describe("The maximum time allowed for an export, in milliseconds.")}).superRefine(({enabled:e,endpoint:t},r)=>{e&&t===void 0&&r.addIssue({code:"custom",message:"endpoint is required when analytics is enabled",path:["endpoint"]})}),yNg=w.strictObject({enabled:w.boolean().describe("Whether wire-level request and response tests are generated."),exclusions:w.array(Yt).optional().describe("Operations excluded from wire tests."),fallbackToGeneratedErrorExamples:w.boolean().optional().describe("Whether missing error fixtures are synthesized from generated examples."),fixtureSource:w.enum(["synthetic","recorded","auto"]).optional().describe("Where wire-test fixtures are obtained.")}),bNg=w.strictObject({enabled:w.boolean().describe("Whether SDK unit tests are generated."),exclusions:w.array(Yt).optional().describe("Operations excluded from unit tests.")}),ENg=w.strictObject({enabled:w.boolean().describe("Whether generated clients expose streaming response APIs."),responseType:w.enum(["wrapper","native","web"]).optional().describe("The streaming response abstraction exposed by generated clients."),fileResponseType:w.enum(["stream","binary-response"]).optional().describe("The response type used for file downloads."),defaultChunkSizeBytes:w.number().int().positive().optional().describe("The default number of bytes yielded by streaming iterators.")}),INg=w.strictObject({outputDirectory:w.enum(["project-root","source-root"]).optional().describe("Whether generated source is rooted at the project or its source directory."),packagePath:Yt.optional().describe("The package-relative path for generated source files.")}),vNg=w.strictObject({enumRepresentation:w.enum(["enum","union","literal","forward-compatible-enum","language-default"]).optional().describe("How schema enums are represented in generated code."),additionalProperties:w.enum(["allow","forbid","ignore","language-default"]).optional().describe("How undeclared object properties are handled."),inlineTypes:w.boolean().optional().describe("Whether inline schemas remain nested under their parent types."),omitUndefined:w.boolean().optional().describe("Whether undefined properties are omitted during serialization.")}),rTs={includeOptionalSnippetParameters:w.boolean().optional().describe("Whether usage snippets include optional request parameters."),buildAllModels:w.boolean().optional().describe("Whether models not referenced by operations are also generated."),inferServiceNames:w.boolean().optional().describe("Whether service names are inferred from API structure."),includeDeprecatedOperations:w.boolean().optional().describe("Whether deprecated API operations are generated."),multipleResponses:w.boolean().optional().describe("Whether operations model multiple successful response types."),devContainer:w.boolean().optional().describe("Whether development-container configuration is generated."),allowMockClient:w.boolean().optional().describe("Whether a mock API client is included in the generated SDK."),ignoreFiles:w.array(Yt).optional().describe("Generated paths excluded from the final output."),reservedKeywords:w.array(Yt).optional().describe("Additional identifiers treated as reserved words."),customCode:hNg.optional().describe("Customer-authored code merge configuration."),customQueryPaths:w.array(Vae).optional().describe("Relative paths to custom query definitions."),analytics:ANg.optional().describe("Generated client telemetry configuration."),wireTests:yNg.optional().describe("Wire-level request and response test generation."),unitTests:bNg.optional().describe("SDK unit-test generation."),webSockets:w.boolean().optional().describe("Whether WebSocket clients are generated for supported channels."),streams:ENg.optional().describe("Streaming response generation behavior."),naming:Cop.optional().describe("Names and casing used by generated code."),layout:INg.optional().describe("Generated project and source layout."),serialization:vNg.optional().describe("Generated model serialization behavior.")},q_=w.strictObject(rTs),CNg=w.strictObject({...rTs,buildAllModels:w.boolean().default(!1).describe("Whether models not referenced by operations are also generated."),inferServiceNames:w.boolean().default(!1).describe("Whether service names are inferred from API structure."),includeDeprecatedOperations:w.boolean().default(!0).describe("Whether deprecated API operations are generated."),multipleResponses:w.boolean().default(!1).describe("Whether operations model multiple successful response types."),devContainer:w.boolean().default(!1).describe("Whether development-container configuration is generated."),allowMockClient:w.boolean().default(!1).describe("Whether a mock API client is included in the generated SDK.")}),ghO=new Set(Object.keys(rTs));var AhO=w.enum(["npm","pypi","maven","nuget","rubygems","crates","go","composer"]),xNg=w.strictObject({keyId:Yt.describe("The signing key identifier, or an environment expression that resolves to it."),password:Yt.describe("The signing key password, or an environment expression that resolves to it."),secretKey:Yt.describe("The armored secret key, or an environment expression that resolves to it.")});function Vip(e,t){return Yt.regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/,`${e} apiKey must be an environment expression naming a secret, such as ${t}`)}function Gip(e,t){return`An environment expression naming the repository secret that the generated release workflow reads the ${e} API key from, such as ${t}. This is a secret name, never the key itself.`}function qip(e){return w.boolean().optional().describe(`Whether ${e} publication uses trusted publishing (OIDC) instead of an API key secret.`)}function Wip(e,t){e.trustedPublishing===!0&&e.apiKey!==void 0&&t.addIssue({code:"custom",message:"apiKey must be omitted when trustedPublishing is true",path:["apiKey"]})}var i2e={url:Yt.optional().describe("A custom package registry URL."),releaseBranch:Yt.optional().describe("The branch used by generated package release workflows."),tolerateRepublish:w.boolean().optional().describe("Whether an already-published package version is treated as non-fatal.")},nTs=w.discriminatedUnion("registry",[w.strictObject({registry:w.literal("npm").describe("Publishes the package to an npm-compatible registry."),token:Yt.optional().describe("The npm registry token, or an environment expression that resolves to it."),trustedPublishing:w.boolean().optional().describe("Whether npm publication uses trusted publishing (OIDC) instead of a token."),...i2e}).superRefine((e,t)=>{e.trustedPublishing===!0&&e.token!==void 0&&t.addIssue({code:"custom",message:"token must be omitted when trustedPublishing is true",path:["token"]})}),w.strictObject({registry:w.literal("pypi").describe("Publishes the package to a PyPI-compatible registry."),username:Yt.optional().describe("The PyPI username, or an environment expression that resolves to it."),password:Yt.optional().describe("The PyPI password or token, or an environment expression that resolves to it."),...i2e}),w.strictObject({registry:w.literal("maven").describe("Publishes the package to a Maven-compatible repository."),username:Yt.optional().describe("The Maven username, or an environment expression that resolves to it."),password:Yt.optional().describe("The Maven password, or an environment expression that resolves to it."),signature:xNg.optional().describe("Credentials used to sign Maven artifacts."),...i2e}),w.strictObject({registry:w.literal("nuget").describe("Publishes the package to a NuGet-compatible registry."),apiKey:Vip("NuGet","${NUGET_API_KEY}").optional().describe(Gip("NuGet","${NUGET_API_KEY}")),trustedPublishing:qip("NuGet"),...i2e}).superRefine(Wip),w.strictObject({registry:w.literal("rubygems").describe("Publishes the package to a RubyGems-compatible registry."),apiKey:Vip("RubyGems","${RUBYGEMS_API_KEY}").optional().describe(Gip("RubyGems","${RUBYGEMS_API_KEY}")),trustedPublishing:qip("RubyGems"),...i2e}).superRefine(Wip),w.strictObject({registry:w.literal("crates").describe("Publishes the crate to a Cargo-compatible registry."),token:Yt.optional().describe("The Cargo registry token, or an environment expression that resolves to it."),...i2e}),w.strictObject({registry:w.literal("go").describe("Publishes the SDK as a Go module."),...i2e}),w.strictObject({registry:w.literal("composer").describe("Publishes the package to a Composer-compatible registry."),...i2e})]),SNg=w.strictObject({teams:w.array(Yt).optional().describe("GitHub teams requested as reviewers."),users:w.array(Yt).optional().describe("GitHub users requested as reviewers.")}),wNg=w.strictObject({username:Yt.optional().describe("The username used to authenticate with the GitHub host."),password:Yt.optional().describe("The password used to authenticate with the GitHub host."),token:Yt.optional().describe("A token used to authenticate with the GitHub host."),apiKey:Yt.optional().describe("An API key used to authenticate with the GitHub host.")}),TNg=w.strictObject({repository:Yt.describe("The GitHub repository that receives generated files."),host:Yt.optional().describe("The GitHub host for enterprise installations."),branch:Yt.optional().describe("The target branch for generated changes."),mode:w.enum(["release","pull-request","push","commit","commit-and-release"]).optional().describe("How generated changes are delivered to the repository."),reviewers:SNg.optional().describe("Reviewers requested for generated pull requests."),credentials:wNg.optional().describe("Credentials used to authenticate GitHub delivery."),privateRepository:w.boolean().optional().describe("Whether the destination repository is private."),workflows:w.boolean().optional().describe("Whether generated .github/workflows files are delivered. Defaults to true. When false, newly generated workflow files are skipped and existing ones in the repository are left untouched.")}),iTs=w.strictObject({delivery:w.literal("files").describe("Writes the generated SDK to a directory."),path:Yt.optional().describe("The destination directory for generated files."),publish:nTs.optional().describe("Optional package registry publication.")}),hEi=w.strictObject({delivery:w.literal("zip").describe("Packages the generated SDK as a ZIP archive."),fileName:Yt.optional().describe("The generated ZIP archive file name."),publish:nTs.optional().describe("Optional package registry publication.")}),oTs=hEi.extend({delivery:w.literal("local").describe('Alias of "zip": the package on the local machine.')}).transform(xop);function xop(e){return{...e,delivery:"zip"}}var sTs=w.strictObject({delivery:w.literal("github").describe("Delivers the generated SDK to GitHub."),github:TNg.describe("GitHub repository delivery settings."),publish:nTs.optional().describe("Optional package registry publication.")}),Sop=w.discriminatedUnion("delivery",[iTs,hEi,sTs,oTs],{error:'output.delivery must be one of "files", "zip", "local", or "github"'}),ONg=w.strictObject({delivery:w.literal("hosted").describe("Deploys the generated MCP server to Fern-hosted infrastructure."),slug:Yt.describe("The server slug. The hosted URL is https://{organization}.fernmcp.dev/{slug}. May be an environment expression that resolves to the slug.")}),PNg=w.discriminatedUnion("delivery",[iTs,hEi,sTs,ONg,oTs],{error:'output.delivery must be one of "files", "zip", "local", "github", or "hosted"'}),lEi={distribution:fop.optional().describe("CLI release channels and build attestation settings for the generated release workflow; credentials are GitHub Actions secret names.")};function Z1s(e,t){e.distribution!==void 0&&t.addIssue({code:"custom",message:dop,path:["distribution"]})}var BNg=w.discriminatedUnion("delivery",[iTs.extend(lEi).superRefine(Z1s),hEi.extend(lEi).superRefine(Z1s),sTs.extend(lEi),oTs.in.extend(lEi).superRefine(Z1s).transform(xop)],{error:'output.delivery must be one of "files", "zip", "local", or "github"'}),DNg=w.strictObject({enabled:w.boolean().describe("Whether regeneration reapplies customer-authored repository changes.")}),gEi=w.strictObject({respectNullableSchemas:w.boolean().optional().describe("Whether nullable schemas remain nullable in generated types."),titleAsSchemaName:w.boolean().optional().describe("Whether a schema title can determine the generated type name."),coerceEnumsToLiterals:w.boolean().optional().describe("Whether single-value enums are imported as literal values."),idiomaticRequestNames:w.boolean().optional().describe("Whether request types use concise, idiomatic generated names."),wrapReferencesToNullableInOptional:w.boolean().optional().describe("Whether nullable schema references are also treated as optional."),coerceOptionalSchemasToNullable:w.boolean().optional().describe("Whether optional properties are represented as nullable required properties."),pathParameterOrder:w.enum(["url-order","spec-order"]).optional().describe("Whether path parameters follow their URL order or specification order."),onlyIncludeReferencedSchemas:w.boolean().optional().describe("Whether unreferenced schemas are omitted from the generated SDK."),objectQueryParameters:w.boolean().optional().describe("Whether object-valued query parameters are preserved as objects."),typeDatesAsStrings:w.boolean().optional().describe("Whether date and date-time schemas are generated as strings."),groupMultiApiEnvironments:w.boolean().optional().describe("Whether environments from multiple API sources are merged into shared named groups."),ignoreTags:w.boolean().optional().describe("Whether API tags are ignored when organizing generated resources."),disambiguateRequestNames:w.boolean().optional().describe("Whether colliding request type names are automatically disambiguated."),respectReadonlySchemas:w.boolean().optional().describe("Whether read-only properties are modeled separately for request and response types."),discriminatedUnionV2:w.boolean().optional().describe("Whether oneOf and anyOf schemas use the newer discriminator inference rules."),undiscriminatedUnionsWithLiterals:w.boolean().optional().describe("Whether literal-bearing unions remain undiscriminated during import."),inlineAllOfSchemas:w.boolean().optional().describe("Whether schemas composed with allOf are inlined when possible."),inferDiscriminatedUnionBaseProperties:w.boolean().optional().describe("Whether properties every discriminated-union variant shares are lifted onto the union."),resolveSchemaCollisions:w.boolean().optional().describe("Whether colliding imported schema names are resolved automatically."),asyncApiMessageNaming:w.enum(["v1","v2"]).optional().describe("The naming strategy used for messages imported from AsyncAPI."),defaultIntegerFormat:w.enum(["int32","int64","uint32","uint64"]).optional().describe("The integer format used when a schema does not declare one."),respectByteFormat:w.boolean().optional().describe("Whether string schemas with format byte are imported as base64-encoded bytes.")}),wop=w.enum(["openapi","swagger","postman","asyncapi","graphql"]),Top={id:Yt.describe("A unique identifier for this API source."),name:Yt.optional().describe("A human-readable name for this API source."),namespace:Yt.optional().describe("A namespace used to isolate this source in a multi-source SDK."),apiImportSettings:gEi.optional().describe("Import behavior that overrides the source-level defaults for this spec.")},Hip={...Top,type:wop.describe("The API description format of this source."),overlays:w.array(Vae).optional().describe("Relative paths to overlays applied to this source in order."),overrides:w.array(Vae).optional().describe("Relative paths to source override files applied in order.")},RNg=w.strictObject({repo:Yt.describe("The git repository URL."),ref:Yt.optional().describe("The branch, tag, or commit SHA. Defaults to the repository's default branch."),path:Vae.describe("The path to the directory within the repository.")}),kNg=w.union([$1s.describe("The relative path to the .proto directory root."),w.strictObject({git:RNg.describe("The git remote holding the .proto files.")}).describe("A .proto directory root in a remote git repository.")]),FNg=w.strictObject({root:kNg.describe("The .proto directory root, as a relative path or a git remote."),target:$1s.optional().describe("The relative path to the single .proto file that defines the API."),overrides:w.array($1s).optional().describe("Relative paths to override files applied to the converted API in order."),dependencies:w.array(Yt).optional().describe("Buf Schema Registry modules the .proto files depend on."),localGeneration:w.boolean().optional().describe("Whether the .proto files are compiled locally instead of remotely."),fromOpenApi:w.boolean().default(!1).describe("Whether SDKs are generated from the OpenAPI converted from the .proto files.")}),NNg=[w.strictObject({...Hip,path:Vae.describe("The relative path to the API source file.")}),w.strictObject({...Hip,url:w.url({protocol:/^https?$/}).describe("The HTTP or HTTPS URL of the API source file.")}),w.strictObject({...Top,proto:FNg.describe("The protobuf definitions of this source.")})],jNg=2;function zNg(e){return typeof e=="object"&&e!==null&&"proto"in e}var QNg=w.union(NNg,{error:e=>e.code!=="invalid_union"||!zNg(e.input)?"source spec must contain exactly one locator: path, HTTP(S) url, or proto":`protobuf source spec is invalid: ${(e.errors[jNg]??[]).map(({path:r,message:n})=>r.length?`${r.join(".")}: ${n}`:n).join("; ")}`}),MNg=w.strictObject({specs:w.array(QNg).min(1,"source.specs must contain at least one source spec").describe("API source files in authoritative processing order."),apiImportSettings:gEi.optional().describe("Default import behavior shared by every source spec.")}).superRefine(({specs:e},t)=>{let r=new Set;e.forEach(({id:n},i)=>{r.has(n)&&t.addIssue({code:"custom",message:`source spec id "${n}" must be unique`,path:["specs",i,"id"]}),r.add(n)})}),Oop=w.strictObject({useOptionalWrapper:w.boolean().optional().describe("Whether optional values use an explicit Optional wrapper."),simplifyObjectDictionaries:w.boolean().optional().describe("Whether object schemas with arbitrary values use simplified dictionary types."),explicitNamespaces:w.boolean().optional().describe("Whether generated resource groups use explicit nested namespaces."),rootNamespaceForCoreClasses:w.boolean().optional().describe("Whether shared client classes are emitted in the root namespace."),includeExceptionHandler:w.boolean().optional().describe("Whether generated client operations use a configurable exception handler."),experimentalExplicitNullableOptional:w.boolean().optional().describe("Whether optional nullable properties distinguish omitted values from explicit nulls.")}),Pop=w.strictObject({legacyComplexModels:w.boolean().optional().describe("Whether complex models use the legacy Go representation."),smartCasing:w.boolean().optional().describe("Whether generated Go names capitalize common initialisms."),clientConstructorName:Yt.optional().describe("The generated root-client constructor name."),unionVersion:w.enum(["v0","v1"]).optional().describe("The representation used for generated Go unions."),includeLegacyClientOptions:w.boolean().optional().describe("Whether the client retains legacy constructor option helpers."),packageLayout:w.enum(["root","types"]).optional().describe("Where the generated Go schema types are declared.")}),Bop=w.strictObject({packageLayout:w.enum(["flat","nested"]).optional().describe("Whether generated JVM packages use a flat or nested resource layout."),useLocalDateForDates:w.boolean().optional().describe("Whether date-only values use LocalDate instead of OffsetDateTime."),collapseOptionalNullable:w.boolean().optional().describe("Whether optional nullable values collapse into a single nullable representation."),gradleDistributionUrl:w.string().min(1).optional().describe("The Gradle distribution URL written to the generated wrapper."),gradlePluginManagement:w.string().optional().describe("Plugin management configuration added to the generated Gradle settings."),gradleCentralDependencyManagement:w.boolean().optional().describe("Whether dependency versions are managed centrally in the Gradle project."),asyncStyle:w.enum(["dedicated-client","twin-methods"]).optional().describe("Whether asynchronous operations use a separate client or co-located methods.")}),Dop=Bop.extend({includeKotlinSnippets:w.boolean().optional().describe("Whether Java SDK documentation includes Kotlin usage snippets.")}),Rop=Bop,LNg=w.strictObject({target:Yt.optional().describe("The JavaScript language target passed to TypeScript."),module:Yt.optional().describe("The module format passed to TypeScript."),lib:w.array(Yt).optional().describe("The runtime library definitions passed to TypeScript.")}),_Ng=w.strictObject({name:Yt.describe("The package script name."),command:Yt.describe("The command executed by the package script.")}),UNg=w.strictObject({name:w.enum(["axios","fetch","node-fetch"]).describe("The HTTP client used by generated TypeScript code.")}),aTs=w.strictObject({typescriptVersion:Yt.optional().describe("The TypeScript version used by the generated project."),zodVersion:Yt.optional().describe("The Zod version used by generated runtime schemas."),compilerOptions:LNg.optional().describe("TypeScript compiler options for the generated project."),httpClient:UNg.optional().describe("The HTTP client used by generated TypeScript code."),packageManager:w.enum(["pnpm","yarn"]).optional().describe("The package manager used by the generated project."),packageManagerVersion:Yt.optional().describe("The package manager version used by the generated project."),testFramework:w.enum(["jest","vitest"]).optional().describe("The test framework used by generated tests."),namingStrategy:w.enum(["base","originalPropertyNames"]).optional().describe("How schema property names are converted into TypeScript identifiers."),bundle:w.boolean().optional().describe("Whether the generated package includes bundled output."),exportClassDefault:w.boolean().optional().describe("Whether the client class is also exported as the default export."),namespaceExportName:Yt.optional().describe("The top-level namespace export name."),consolidateTypeFiles:w.boolean().optional().describe("Whether generated types are consolidated into fewer source files."),formDataSupport:w.enum(["Node16","Node18"]).optional().describe("The multipart form-data implementation: Node16 uses the form-data packages, Node18 uses the platform FormData."),allowExtraFields:w.boolean().optional().describe("Whether response parsing keeps unrecognized object keys and accepts unrecognized union members and enum values."),generateSubpackageExports:w.boolean().optional().describe("Whether the package manifest exports each subpackage client as its own entry point."),exportAllRequestsAtRoot:w.boolean().optional().describe("Whether every request type is also exported from the package root."),generateEndpointMetadata:w.boolean().optional().describe("Whether generated clients expose metadata for each endpoint."),outputEsm:w.boolean().optional().describe("Whether the package is marked as an ES module while still shipping its CommonJS build."),neverThrowErrors:w.boolean().optional().describe("Whether client methods return a wrapped response instead of throwing on a non-2xx status."),includeOtherInUnionTypes:w.boolean().optional().describe("Whether union types gain a member for variants the SDK does not recognize."),includeUtilsOnUnionMembers:w.boolean().optional().describe("Whether helper utilities are generated on each member of a union type."),omitFernHeaders:w.boolean().optional().describe("Whether requests omit the SDK identification headers and the User-Agent header."),linter:w.enum(["biome","oxlint","none"]).optional().describe("The linter configured in the generated project."),formatter:w.enum(["prettier","biome","oxfmt","none"]).optional().describe("The formatter configured in the generated project."),exports:Twt.optional().describe("package.json exports entries, keyed by subpath, applied over the generated exports. Each subpath replaces the generated one."),files:w.array(Yt).optional().describe("package.json files entries, listed ahead of the generated ones."),engines:w.record(Yt,Yt).optional().describe("package.json engines version ranges, keyed by engine name such as node."),lintStaged:w.record(Yt,w.array(Yt).min(1)).optional().describe("lint-staged commands to run, keyed by file glob."),browser:w.record(Yt,w.union([w.boolean(),Yt])).optional().describe("package.json browser field: a module or file is excluded (false) or replaced by another path."),allowCustomFetcher:w.boolean().optional().describe("Whether callers can supply a custom fetch implementation."),useBrandedStringAliases:w.boolean().optional().describe("Whether string aliases are emitted as distinct branded types."),useLegacyExports:w.boolean().optional().describe("Whether the package emits the legacy export layout."),useBigInt:w.boolean().optional().describe("Whether 64-bit integer values are represented with bigint."),serdeLayer:w.boolean().optional().describe("Whether generated models use Fern serialization and deserialization helpers."),esmOnly:w.boolean().optional().describe("Whether the package emits only ECMAScript modules."),scripts:w.array(_Ng).optional().describe("Additional scripts added to the generated package manifest.")}),VNg=["IN_DEVELOPMENT","PRE_RELEASE","GENERAL_AVAILABILITY","DEPRECATED","ALPHA","BETA","PREVIEW","LEGACY"],Kip=w.strictObject({include:w.array(Yt).optional().describe("Operations explicitly included as MCP tools."),exclude:w.array(Yt).optional().describe("Operations explicitly excluded from MCP tools.")}),GNg=Yt.refine(e=>e!=="default"&&/^[a-z0-9-]+$/.test(e),'toolset names must match [a-z0-9-]+ and cannot be "default"'),kop=aTs.extend({serverName:Yt.optional().describe("The name advertised by the generated MCP server."),serverDescription:Yt.optional().describe("The description advertised by the generated MCP server."),excludeAvailability:w.array(w.enum(VNg)).optional().describe("Operation availability statuses excluded from MCP tool generation."),tools:Kip.optional().describe("Global operation filters for generated MCP tools."),toolsets:w.record(GNg,Kip).optional().describe("Named MCP toolsets and the operation filters for each toolset.")}),Fop=w.strictObject({propertyAccess:w.enum(["public","private"]).optional().describe("The visibility of generated PHP model properties."),generateClientInterfaces:w.boolean().optional().describe("Whether interfaces are generated for PHP client classes.")}),qNg=w.strictObject({fileName:Yt.optional().describe("The source file name for the Python client."),exportedFileName:Yt.optional().describe("The file name used when exporting the Python client.")}),WNg=w.strictObject({versionCompatibility:w.enum(["v1","v2","both","v1-on-v2"]).optional().describe("The Pydantic major versions supported by generated models."),frozen:w.boolean().optional().describe("Whether generated Pydantic models are immutable."),requireOptionalFields:w.boolean().optional().describe("Whether Optional fields remain required unless they declare a default."),unionNaming:w.enum(["v0","v1"]).optional().describe("The naming strategy for generated union types."),useFieldAliases:w.boolean().optional().describe("Whether Pydantic field aliases preserve wire names.")}),HNg=w.strictObject({from:Yt.describe("The module from which names are re-exported."),imports:w.array(Yt).min(1).describe("Names re-exported from the module.")}),Nop=w.strictObject({pythonVersion:Yt.optional().describe("The Python version targeted by the generated project."),pydanticVersion:Yt.optional().describe("The Pydantic dependency version requirement."),pydantic:WNg.optional().describe("Pydantic model-generation behavior."),client:qNg.optional().describe("Python client file naming."),followRedirectsByDefault:w.boolean().optional().describe("Whether generated HTTP clients follow redirects by default."),defaultBytesStreamChunkSize:w.number().int().positive().optional().describe("The default byte-stream iterator chunk size."),recursionLimit:w.number().int().gt(1e3).optional().describe("The Python recursion limit installed when the generated package is imported."),extras:w.record(Yt,w.array(Yt)).optional().describe("Published Python extras and their dependency names."),alwaysInitializeOptionals:w.boolean().optional().describe("Whether optional model fields are initialized even when omitted."),useTypedDictRequests:w.boolean().optional().describe("Whether request bodies are generated as TypedDict types."),streamAbstraction:w.boolean().optional().describe("Whether streaming endpoints return Stream and AsyncStream objects instead of plain iterators."),additionalInitExports:w.array(HNg).optional().describe("Additional names re-exported from the package initializer.")}),jop=w.strictObject({requirePaths:w.array(Yt).optional().describe("Files the generated entry file loads with `require`.")}),zop=w.strictObject({dateTimeType:w.enum(["offset","utc"]).optional().describe("Whether datetime values preserve their offset or normalize to UTC."),capitalizeInitialisms:w.boolean().optional().describe("Whether generated Rust names capitalize common initialisms."),features:w.record(w.string(),w.array(Yt)).optional().describe("Cargo features and the dependencies or features each enables."),defaultFeatures:w.array(Yt).optional().describe("Cargo features included in the crate default feature set.")}),Qop=w.strictObject({moduleName:Yt.optional().describe("The Swift module name for the generated package."),nullableAsOptional:w.boolean().optional().describe("Whether nullable values are represented as Swift optionals.")}),Jip=w.discriminatedUnion("enabled",[w.strictObject({enabled:w.literal(!0).describe("Enables custom Terraform plan modifiers."),sourceDir:Yt.describe("The directory containing custom plan modifier source files.")}),w.strictObject({enabled:w.literal(!1).describe("Disables custom Terraform plan modifiers.")})]),KNg=w.strictObject({resources:Jip.describe("Custom plan modifiers for generated resources."),attributes:Jip.describe("Custom plan modifiers for generated attributes.")}),JNg=w.strictObject({addressKey:Yt.describe("The provider attribute used to configure the API address."),authTokenKey:Yt.describe("The provider attribute used to configure the authentication token.")}),Mop=w.strictObject({providerName:Yt.optional().describe("The Terraform provider name."),providerVersion:Yt.optional().describe("The generated Terraform provider version."),providerModulePath:aop.optional().describe("The Go module path for the generated provider."),mockAcceptance:w.boolean().optional().describe("Whether acceptance tests use a mock API server."),hideComputedDiff:w.boolean().optional().describe("Whether computed-only changes are hidden from Terraform plans."),providerSchema:JNg.optional().describe("Names of provider-level configuration attributes."),planModifiers:KNg.optional().describe("Custom plan modifier source configuration.")}),W_={generatorVersion:Xip.optional().describe("The exact generator version used for this target."),sdkName:Yt.optional().describe("An SDK name that overrides the root value for this target."),sdkVersion:Yt.optional().describe("An SDK version that overrides the root value for this target."),client:R2g.optional().describe("Client settings that override root client configuration for this target."),docs:gop.optional().describe("Documentation settings that override root documentation for this target."),package:Iop.optional().describe("Package metadata that overrides root package configuration for this target."),output:Sop.optional().describe("Output configuration that replaces the root output for this target.")},YNg=w.discriminatedUnion("language",[w.strictObject({language:w.literal("typescript").describe("Generates a TypeScript SDK."),generation:q_.extend(aTs.shape).optional().describe("Common and TypeScript-specific generation settings for this target."),...W_}),w.strictObject({language:w.literal("python").describe("Generates a Python SDK."),generation:q_.extend(Nop.shape).optional().describe("Common and Python-specific generation settings for this target."),...W_}),w.strictObject({language:w.literal("java").describe("Generates a Java SDK."),generation:q_.extend(Dop.shape).optional().describe("Common and Java-specific generation settings for this target."),...W_}),w.strictObject({language:w.literal("kotlin").describe("Generates a Kotlin SDK."),generation:q_.extend(Rop.shape).optional().describe("Common and Kotlin-specific generation settings for this target."),...W_}),w.strictObject({language:w.literal("go").describe("Generates a Go SDK."),generation:q_.extend(Pop.shape).optional().describe("Common and Go-specific generation settings for this target."),...W_}),w.strictObject({language:w.literal("csharp").describe("Generates a C# SDK."),generation:q_.extend(Oop.shape).optional().describe("Common and C#-specific generation settings for this target."),...W_}),w.strictObject({language:w.literal("php").describe("Generates a PHP SDK."),generation:q_.extend(Fop.shape).optional().describe("Common and PHP-specific generation settings for this target."),...W_}),w.strictObject({language:w.literal("ruby").describe("Generates a Ruby SDK."),generation:q_.extend(jop.shape).optional().describe("Common and Ruby-specific generation settings for this target."),...W_}),w.strictObject({language:w.literal("rust").describe("Generates a Rust SDK."),generation:q_.extend(zop.shape).optional().describe("Common and Rust-specific generation settings for this target."),...W_}),w.strictObject({language:w.literal("swift").describe("Generates a Swift SDK."),generation:q_.extend(Qop.shape).optional().describe("Common and Swift-specific generation settings for this target."),...W_}),w.strictObject({language:w.literal("cli").describe("Generates a command-line interface."),generation:q_.extend(Eop.shape).optional().describe("Common and CLI-specific generation settings for this target."),...W_,output:BNg.optional().describe("Output configuration, including optional CLI distribution channels, that replaces the root output for this target.")}),w.strictObject({language:w.literal("mcp").describe("Generates an MCP server."),generation:q_.extend(kop.shape).optional().describe("Common and MCP-specific generation settings for this target."),...W_,output:PNg.optional().describe("Output configuration, including Fern-hosted deployment, that replaces the root output for this target.")}),w.strictObject({language:w.literal("terraform").describe("Generates a Terraform provider."),generation:q_.extend(Mop.shape).optional().describe("Common and Terraform-specific generation settings for this target."),...W_})]),XNg="sdk-config/v1",ZNg={npm:["typescript","mcp","cli"],pypi:["python"],maven:["java","kotlin"],nuget:["csharp"],rubygems:["ruby"],crates:["rust"],go:["go"],composer:["php"]},$Ng=new Set(["npm","pypi","nuget","rubygems","crates","composer"]);function ejg(e,t,r,n){let i=["targets",r,"package"];if($Ng.has(t)&&!e.packageName&&n.addIssue({code:"custom",message:`packageName is required when publishing to "${t}"`,path:[...i,"packageName"]}),t==="composer"&&e.packageName){let o=cop.safeParse(e.packageName);o.success||n.addIssue({code:"custom",message:o.error.issues[0]?.message??"Invalid Composer package name",path:[...i,"packageName"]})}t==="go"&&!e.modulePath&&n.addIssue({code:"custom",message:"modulePath is required when publishing a Go module",path:[...i,"modulePath"]}),t==="maven"&&["groupId","artifactId"].forEach(o=>{e[o]||n.addIssue({code:"custom",message:`${o} is required when publishing to Maven`,path:[...i,o]})})}function tjg(e,t,r,n,i){let o=e.output??n;if(!o){i.addIssue({code:"custom",message:"output is required on the target when no global output is configured",path:["targets",t,"output"]});return}if(o.delivery==="hosted"||!o.publish)return;let s=o.publish.registry;if(!ZNg[s].some(a=>a===e.language)){i.addIssue({code:"custom",message:`registry "${s}" is not supported for target language "${e.language}"`,path:["targets",t,e.output?"output":"language"]});return}e.language==="cli"&&o.delivery!=="github"&&i.addIssue({code:"custom",message:mop,path:e.output?["targets",t,"output","delivery"]:["output","delivery"]}),ejg({...r,...e.package},s,t,i)}var rjg=w.strictObject({schemaVersion:w.literal(XNg).describe("The version of the customer-facing SDK Config schema."),sdkName:Yt.describe("The default name used for generated SDKs."),sdkVersion:Yt.default("1.0.0").describe("The default version assigned to generated SDKs."),apiVersion:Yt.optional().describe("The version of the API represented by the generated SDKs."),source:MNg.describe("The API descriptions used to generate the SDKs."),api:x2g.prefault({}).describe("Shared API behavior for every target."),client:D2g.prefault({}).describe("Shared generated-client behavior for every target."),package:Iop.prefault({}).describe("Package metadata inherited by every target."),output:Sop.optional().describe("The default output delivery and publication configuration."),replay:DNg.optional().describe("Generation replay behavior shared by every target."),docs:gop.prefault({}).describe("Documentation settings inherited by every target."),generation:CNg.prefault({}).describe("Generation settings inherited by every target."),targets:w.array(YNg).min(1).describe("Language targets to generate; each language may appear once.")}).superRefine(({api:e,output:t,package:r,targets:n},i)=>{let o=new Set;n.forEach((s,a)=>{o.has(s.language)&&i.addIssue({code:"custom",message:`target language "${s.language}" must be unique`,path:["targets",a,"language"]}),o.add(s.language),tjg(s,a,r,t,i),s.language==="cli"&&bop(s.generation?.oauthTokenEndpoints,e.auth?.schemes,["targets",a,"generation","oauthTokenEndpoints"]).forEach(c=>i.addIssue({code:"custom",...c}))})});var yhO=vop(rjg);var njg=w.strictObject({source:w.enum(["fern","postman","sdk-config-ir"]).describe("The configuration surface containing the unsupported field."),path:w.array(w.union([Yt,w.number().int().nonnegative()])).min(1).describe("The property path to the unsupported field in its source configuration."),code:Yt.optional().describe("A stable diagnostic code for the unsupported field."),reason:Yt.describe("Why the field could not be represented in normalized configuration."),severity:w.enum(["error","warning","info"]).describe("The diagnostic severity."),risk:w.enum(["high","medium","low"]).describe("The migration risk of omitting this field."),owner:Yt.describe("The component or team responsible for resolving the gap."),suggestedAction:Yt.describe("Recommended action for preserving the intended behavior.")}),ijg=w.strictObject({kind:w.literal("postman-build-parameters").describe("Identifies legacy Postman build parameters."),value:Twt.describe("A debugging copy of the original Postman build parameters.")}),ojg=w.strictObject({kind:w.literal("fern-generator-invocation").describe("Identifies a legacy Fern generator invocation."),value:Twt.describe("A debugging copy of the original Fern generator invocation.")}),sjg=w.discriminatedUnion("kind",[ijg,ojg]),ajg=w.strictObject({outputProfile:w.enum(["converged","postman-legacy","fern-legacy"]).describe("The output-default profile retained while legacy producers converge."),legacyInput:sjg.optional().describe("Original producer input retained only for migration debugging."),unsupportedFields:w.array(njg).optional().describe("Legacy fields that could not be represented in normalized configuration.")});var Lop=w.discriminatedUnion("type",[w.strictObject({type:w.literal("path").describe("Loads the generation asset from a relative path."),location:Vae.describe("The relative path to the generation asset.")}),w.strictObject({type:w.literal("url").describe("Loads the generation asset from a URL."),location:Yt.describe("The URL of the generation asset.")}),w.strictObject({type:w.literal("artifact").describe("Loads the generation asset from stored build output."),location:Yt.describe("The artifact identifier or location.")})]),cjg=w.strictObject({name:Yt.describe("The hook dependency name."),version:Yt.describe("The hook dependency version requirement."),groupId:Yt.optional().describe("The Maven group identifier for the dependency.")}),ljg=w.strictObject({enabled:w.boolean().describe("Whether custom request and response hooks are generated."),source:Lop.optional().describe("The source containing custom hook implementations."),dependencies:w.array(cjg).optional().describe("Dependencies required by custom hooks.")}),ujg=w.strictObject({enabled:w.boolean().describe("Whether customer-authored code is merged into generated output."),source:Lop.optional().describe("The source containing customer-authored code."),conflictStrategy:w.enum(["mark","ours","theirs"]).optional().describe("How merge conflicts between generated and custom code are handled."),trackChanges:w.boolean().optional().describe("Whether custom-code changes are tracked between builds."),previousBuildId:w.number().int().positive().optional().describe("The previous build used as the merge baseline."),protectedFiles:w.array(Yt).optional().describe("Generated file paths that custom-code merging must not overwrite.")}),pjg=w.strictObject({path:Vae.describe("The relative path to the workflow definition."),outputName:Yt.optional().describe("The file name used for the generated workflow.")}),fjg=w.union([w.strictObject({name:Yt.describe("The exported telemetry header name."),value:w.string().describe("The literal telemetry header value.")}),w.strictObject({name:Yt.describe("The exported telemetry header name."),valueRef:Yt.describe("A reference to the telemetry header value.")})]),djg=w.strictObject({enabled:w.boolean().describe("Whether generated clients export usage telemetry."),endpoint:Yt.optional().describe("The telemetry export endpoint."),exporter:w.enum(["otlp-http","console"]).optional().describe("The telemetry exporter implementation."),headers:w.array(fjg).optional().describe("Headers sent by the telemetry exporter."),batchSize:w.number().int().positive().optional().describe("The maximum spans in each export batch."),scheduledDelayMs:w.number().nonnegative().optional().describe("The delay between scheduled exports, in milliseconds."),exportTimeoutMs:w.number().nonnegative().optional().describe("The maximum time allowed for an export, in milliseconds.")}).superRefine(({enabled:e,endpoint:t},r)=>{e&&t===void 0&&r.addIssue({code:"custom",message:"endpoint is required when analytics is enabled",path:["endpoint"]})}),mjg=w.strictObject({enabled:w.boolean().describe("Whether wire-level request and response tests are generated."),exclusions:w.array(Yt).optional().describe("Operations excluded from wire tests."),fallbackToGeneratedErrorExamples:w.boolean().optional().describe("Whether missing error fixtures are synthesized from generated examples."),fixtureSource:w.enum(["synthetic","recorded","auto"]).optional().describe("Where wire-test fixtures are obtained.")}),hjg=w.strictObject({enabled:w.boolean().describe("Whether SDK unit tests are generated."),mode:w.enum(["core-runtime","schema-driven","both"]).optional().describe("The unit-test generation strategy."),exclusions:w.array(Yt).optional().describe("Operations excluded from unit tests.")}),gjg=w.strictObject({definitionS3DownloadUrl:Yt.describe("The download URL for the materialized Fern definition archive."),outputPath:Yt.optional().describe("The destination path for Fern definition support files."),cliVersion:Yt.optional().describe("The Fern CLI version associated with the definition.")}),Ajg=w.strictObject({enabled:w.boolean().describe("Whether generated clients expose streaming response APIs."),responseType:w.enum(["wrapper","native","web"]).optional().describe("The streaming response abstraction exposed by generated clients."),fileResponseType:w.enum(["stream","binary-response"]).optional().describe("The response type used for file downloads."),defaultChunkSizeBytes:w.number().int().positive().optional().describe("The default number of bytes yielded by streaming iterators.")}),yjg=w.strictObject({outputDirectory:w.enum(["project-root","source-root"]).optional().describe("Whether generated source is rooted at the project or its source directory."),packagePath:Yt.optional().describe("The package-relative path for generated source files.")}),bjg=w.strictObject({enumRepresentation:w.enum(["enum","union","literal","forward-compatible-enum","language-default"]).optional().describe("How schema enums are represented in generated code."),additionalProperties:w.enum(["allow","forbid","ignore","language-default"]).optional().describe("How undeclared object properties are handled."),inlineTypes:w.boolean().optional().describe("Whether inline schemas remain nested under their parent types."),omitUndefined:w.boolean().optional().describe("Whether undefined properties are omitted during serialization.")}),Ejg=w.strictObject({typescript:aTs.optional().describe("TypeScript-specific generation settings."),python:Nop.optional().describe("Python-specific generation settings."),java:Dop.optional().describe("Java-specific generation settings."),kotlin:Rop.optional().describe("Kotlin-specific generation settings."),go:Pop.optional().describe("Go-specific generation settings."),csharp:Oop.optional().describe("C#-specific generation settings."),php:Fop.optional().describe("PHP-specific generation settings."),ruby:jop.optional().describe("Ruby-specific generation settings."),rust:zop.optional().describe("Rust-specific generation settings."),cli:Eop.optional().describe("CLI-specific generation settings."),mcp:kop.optional().describe("MCP-specific generation settings."),swift:Qop.optional().describe("Swift-specific generation settings."),terraform:Mop.optional().describe("Terraform-specific generation settings.")}),Ijg=w.strictObject({includeWatermark:w.boolean().default(!1).describe("Whether generated files include a generator watermark."),ai:w.boolean().default(!1).describe("Whether the SDK includes generated AI service helpers."),includeOptionalSnippetParameters:w.boolean().optional().describe("Whether usage snippets include optional request parameters."),buildAllModels:w.boolean().default(!1).describe("Whether models not referenced by operations are also generated."),inferServiceNames:w.boolean().default(!1).describe("Whether service names are inferred from API structure."),includeDeprecatedOperations:w.boolean().default(!0).describe("Whether deprecated API operations are generated."),multipleResponses:w.boolean().default(!1).describe("Whether operations model multiple successful response types."),generateFullProject:w.boolean().default(!1).describe("Whether generation emits a complete publishable project."),devContainer:w.boolean().default(!1).describe("Whether development-container configuration is generated."),allowMockClient:w.boolean().default(!1).describe("Whether a mock API client is included in the generated SDK."),ignoreFiles:w.array(Yt).optional().describe("Generated paths excluded from the final output."),fernignoreContents:w.string().optional().describe("The raw .fernignore contents retained for external publishers."),fernDefinitionMetadata:gjg.optional().describe("Materialized Fern definition metadata used by external publishers."),reservedKeywords:w.array(Yt).optional().describe("Additional identifiers treated as reserved words."),hooks:ljg.optional().describe("Custom SDK request and response hook configuration."),customCode:ujg.optional().describe("Customer-authored code merge configuration."),workflows:w.array(pjg).optional().describe("Workflow definitions included in generated output."),customQueryPaths:w.array(Vae).optional().describe("Relative paths to custom query definitions."),analytics:djg.optional().describe("Generated client telemetry configuration."),wireTests:mjg.optional().describe("Wire-level request and response test generation."),unitTests:hjg.optional().describe("SDK unit-test generation."),webSockets:w.boolean().optional().describe("Whether WebSocket clients are generated for supported channels."),streams:Ajg.optional().describe("Streaming response generation behavior."),naming:Cop.optional().describe("Names and casing used by generated code."),layout:yjg.optional().describe("Generated project and source layout."),serialization:bjg.optional().describe("Generated model serialization behavior."),language:Ejg.optional().describe("Settings specific to the selected target language.")}),bhO=w.enum(["npm","pypi","maven","nuget","rubygems","crates","go","composer"]),vjg=w.enum(["refs-only","resolved-by-orchestrator","resolved-by-fiddle"]),_op=w.strictObject({username:Yt.optional().describe("The resolved credential username."),password:Yt.optional().describe("The resolved credential password."),token:Yt.optional().describe("The resolved credential token."),apiKey:Yt.optional().describe("The resolved credential API key.")}),o2e={url:Yt.optional().describe("A custom package registry URL."),credentialsRef:Yt.optional().describe("A reference to registry publishing credentials."),credentials:_op.optional().describe("Resolved registry publishing credentials."),version:Yt.optional().describe("A registry-specific package version override."),releaseBranch:Yt.optional().describe("The branch used by generated package release workflows."),tolerateRepublish:w.boolean().optional().describe("Whether publishing succeeds when this package version already exists."),shouldGeneratePublishWorkflow:w.boolean().optional().describe("Whether GitHub delivery includes a registry publishing workflow.")},uEi={trustedPublishing:w.boolean().optional().describe("Whether registry publication uses trusted publishing or OIDC.")},Cjg=Yt.regex(/^[A-Za-z0-9_.-]+:[A-Za-z0-9_.-]+$/,"Maven coordinate must be in groupId:artifactId form"),xjg=w.strictObject({keyIdEnvironmentVariable:Yt.optional().describe("The environment variable containing the signing key ID."),passwordEnvironmentVariable:Yt.optional().describe("The environment variable containing the signing key password."),secretKeyEnvironmentVariable:Yt.optional().describe("The environment variable containing the armored secret key.")}),Sjg=w.strictObject({keyId:Yt.describe("The resolved signing key identifier."),password:Yt.describe("The resolved signing key password."),secretKey:Yt.describe("The resolved armored secret key.")}),cTs=w.discriminatedUnion("registry",[w.strictObject({registry:w.literal("npm").describe("Publishes the package to an npm-compatible registry."),tokenEnvironmentVariable:Yt.optional().describe("The environment variable containing the npm registry token."),isPackagePrivate:w.boolean().optional().describe("Whether generated npm package metadata marks the package as private."),publishToJsr:w.boolean().optional().describe("Whether the npm publishing flow also publishes the package to JSR."),...uEi,...o2e}),w.strictObject({registry:w.literal("pypi").describe("Publishes the package to a PyPI-compatible registry."),usernameEnvironmentVariable:Yt.optional().describe("The environment variable containing the PyPI username."),passwordEnvironmentVariable:Yt.optional().describe("The environment variable containing the PyPI password or token."),...uEi,...o2e}),w.strictObject({registry:w.literal("nuget").describe("Publishes the package to a NuGet-compatible registry."),apiKeyEnvironmentVariable:Yt.optional().describe("The environment variable containing the NuGet API key."),...uEi,...o2e}),w.strictObject({registry:w.literal("rubygems").describe("Publishes the package to a RubyGems-compatible registry."),apiKeyEnvironmentVariable:Yt.optional().describe("The environment variable containing the RubyGems API key."),...uEi,...o2e}),w.strictObject({registry:w.literal("crates").describe("Publishes the crate to a Cargo-compatible registry."),tokenEnvironmentVariable:Yt.optional().describe("The environment variable containing the Cargo registry token."),...o2e}),w.strictObject({registry:w.literal("go").describe("Publishes the SDK as a Go module."),...o2e}),w.strictObject({registry:w.literal("composer").describe("Publishes the package to a Composer-compatible registry."),...o2e}),w.strictObject({registry:w.literal("maven").describe("Publishes the package to a Maven-compatible repository."),coordinate:Cjg.optional().describe("The Maven coordinate in groupId:artifactId form."),usernameEnvironmentVariable:Yt.optional().describe("The environment variable containing the Maven username."),passwordEnvironmentVariable:Yt.optional().describe("The environment variable containing the Maven password."),mavenUrlEnvironmentVariable:Yt.optional().describe("The environment variable containing the Maven repository URL."),signatureEnvironmentVariables:xjg.optional().describe("Environment variables containing Maven signing material."),signingCredentialsRef:Yt.optional().describe("A reference to Maven signing credentials."),signature:Sjg.optional().describe("Resolved Maven signing material."),...o2e})]),wjg=w.strictObject({teams:w.array(Yt).optional().describe("GitHub teams requested as reviewers."),users:w.array(Yt).optional().describe("GitHub users requested as reviewers.")}),Tjg=w.strictObject({enabled:w.boolean().describe("Whether regeneration reapplies customer-authored repository changes.")}),Ojg=w.strictObject({type:Yt.optional().describe("The SPDX identifier or license key for the repository license."),customPath:Yt.optional().describe("The path to a custom license file committed to the repository.")}).refine(e=>e.type!==void 0||e.customPath!==void 0,{message:"GitHub license must set type or customPath"}),Pjg=w.strictObject({repository:Yt.describe("The GitHub repository that receives generated files."),host:Yt.optional().describe("The GitHub host for enterprise installations."),branch:Yt.optional().describe("The target branch for generated changes."),mode:w.enum(["release","pull-request","push","commit","commit-and-release"]).optional().describe("How generated changes are delivered to the repository."),reviewers:wjg.optional().describe("Reviewers requested for generated pull requests."),credentialsRef:Yt.optional().describe("A reference to GitHub credentials."),credentials:_op.optional().describe("Resolved GitHub credentials."),privateRepository:w.boolean().optional().describe("Whether the destination repository is private."),workflows:w.boolean().optional().describe("Whether generated .github/workflows files are delivered. Defaults to true. When false, newly generated workflow files are skipped and existing ones in the repository are left untouched."),license:Ojg.optional().describe("License configuration for the destination repository."),replay:Tjg.optional().describe("Replay behavior for the external GitHub publisher."),verify:w.boolean().default(!1).describe("Whether the GitHub publisher verifies the generated result."),skipIfNoDiff:w.boolean().default(!1).describe("Whether GitHub publication is skipped when no generated files changed."),autoMerge:w.boolean().default(!1).describe("Whether the GitHub publisher automatically merges its pull request.")}),lTs={distribution:fop.optional().describe("CLI release channels and build attestation settings for the generated release workflow; credentials are GitHub Actions secret names.")},uTs={credentialResolution:vjg.default("refs-only").describe("Where output credential references are resolved.")},Bjg=w.strictObject({delivery:w.literal("files").describe("Writes the generated SDK to a directory."),path:Yt.optional().describe("The destination directory for generated files."),publish:cTs.optional().describe("Optional package registry publication."),...lTs,...uTs}),Uop=w.strictObject({delivery:w.literal("zip").describe("Packages the generated SDK as a ZIP archive."),fileName:Yt.optional().describe("The generated ZIP archive file name."),publish:cTs.optional().describe("Optional package registry publication."),...lTs,...uTs}),Djg=Uop.extend({delivery:w.literal("local").describe('Alias of "zip": the package on the local machine.')}).transform(e=>({...e,delivery:"zip"})),Rjg=w.strictObject({delivery:w.literal("github").describe("Delivers the generated SDK to GitHub."),github:Pjg.describe("GitHub repository delivery settings."),publish:cTs.optional().describe("Optional package registry publication."),...lTs,...uTs}),kjg=w.discriminatedUnion("delivery",[Bjg,Uop,Rjg,Djg],{error:'output.delivery must be one of "files", "zip", "local", or "github"'}),Fjg=w.strictObject({enabled:w.boolean().describe("Whether regeneration reapplies customer-authored repository changes.")}),Njg=w.enum(["protobuf"]),jjg=w.strictObject({id:Yt.optional().describe("A unique identifier for this API source."),name:Yt.optional().describe("A human-readable name for this API source."),namespace:Yt.optional().describe("A namespace used to isolate this source in a multi-source SDK."),specUrl:Yt.describe("The materialized URL from which the generator retrieves the API source."),specType:wop.describe("The API description format of this source."),origin:Njg.optional().describe("The format this source was authored in before it was converted to specType."),apiImportSettings:gEi.optional().describe("Import behavior that overrides the source-level defaults for this spec."),overlays:w.array(Yt).optional().describe("Materialized overlays applied to this source in order."),overrides:w.array(Yt).optional().describe("Materialized source overrides applied in order.")}).superRefine(({specType:e,origin:t},r)=>{t==="protobuf"&&e!=="openapi"&&r.addIssue({code:"custom",message:'origin "protobuf" is only allowed on openapi specs',path:["origin"]})}),zjg=w.strictObject({specs:w.array(jjg).min(1,"source.specs must contain at least one source spec").describe("Materialized API sources in authoritative processing order."),apiImportSettings:gEi.optional().describe("Default import behavior shared by every source spec.")}).superRefine(({specs:e},t)=>{let r=new Set;e.forEach(({id:n},i)=>{n&&r.has(n)&&t.addIssue({code:"custom",message:`source spec id "${n}" must be unique`,path:["specs",i,"id"]}),n&&r.add(n)})}),pTs=w.enum(["typescript","python","java","kotlin","go","csharp","php","ruby","rust","swift","cli","mcp","terraform"]),Qjg=w.strictObject({language:pTs.describe("The language or platform generated by this single-target request."),generatorVersion:Xip.optional().describe("The exact generator version requested for this target."),sourceOrigin:w.enum(["postman","fern"]).describe("The configuration system from which this IR was normalized."),sdkName:Yt.describe("The name used for the generated SDK."),apiName:Yt.optional().describe("The stable API identity used for external publishing."),organization:Yt.optional().describe("Source organization metadata retained for generation."),organizationName:Yt.optional().describe("The stable organization identity used for external publishing."),sdkVersion:Yt.default("1.0.0").describe("The version of the generated SDK."),apiVersion:Yt.optional().describe("The version of the API represented by the SDK.")}),fTs="sdk-config-ir/v1",Mjg={npm:["typescript","mcp","cli"],pypi:["python"],maven:["java","kotlin"],nuget:["csharp"],rubygems:["ruby"],crates:["rust"],go:["go"],composer:["php"]},Ljg=new Set(["npm","pypi","nuget","rubygems","crates","composer"]);function _jg(e,t,r){if(Ljg.has(t)&&!e.packageName){r.addIssue({code:"custom",message:`package.packageName is required when publishing to "${t}"`,path:["package","packageName"]});return}if(t==="composer"&&e.packageName){let n=cop.safeParse(e.packageName);n.success||r.addIssue({code:"custom",message:n.error.issues[0]?.message??"Invalid Composer package name",path:["package","packageName"]})}t==="go"&&!e.modulePath&&r.addIssue({code:"custom",message:"package.modulePath is required when publishing a Go module",path:["package","modulePath"]}),t==="maven"&&["groupId","artifactId"].forEach(n=>{e[n]||r.addIssue({code:"custom",message:`package.${n} is required when publishing to Maven`,path:["package",n]})})}function Ujg(e,t,r){e.distribution!==void 0&&t!=="cli"?r.addIssue({code:"custom",message:`output.distribution is supported only for target language "cli", not "${t}"`,path:["output","distribution"]}):e.distribution!==void 0&&e.delivery!=="github"&&r.addIssue({code:"custom",message:dop,path:["output","distribution"]}),t==="cli"&&e.publish&&e.delivery!=="github"&&r.addIssue({code:"custom",message:mop,path:["output","publish"]})}var h$t=w.strictObject({schemaVersion:w.literal(fTs).describe("The version of the normalized SDK Config IR schema."),source:zjg.describe("Materialized API descriptions consumed by generation."),target:Qjg.describe("Identity and provenance for this single generation target."),api:top.describe("API behavior exposed by the generated SDK."),client:sop.describe("Behavior of the generated API client."),package:lop.describe("Package identity and metadata for the generated SDK."),output:kjg.describe("Artifact delivery and optional package publication."),replay:Fjg.optional().describe("Generation replay behavior."),docs:hop.describe("Generated documentation settings."),generation:Ijg.describe("Shared and language-specific generation behavior."),compatibility:ajg.optional().describe("Temporary provenance and diagnostics retained during legacy migration.")}).superRefine(({api:e,compatibility:t,generation:r,output:n,package:i,target:o},s)=>{let a=Object.keys(r.language??{});if((n.delivery==="github"||n.publish!==void 0)&&[["apiName","target.apiName is required for external publishing"],["organizationName","target.organizationName is required for external publishing"]].forEach(([l,u])=>{o[l]||s.addIssue({code:"custom",message:u,path:["target",l]})}),bop(r.language?.cli?.oauthTokenEndpoints,e.auth?.schemes,["generation","language","cli","oauthTokenEndpoints"]).forEach(l=>s.addIssue({code:"custom",...l})),a.forEach(l=>{l!==o.language&&s.addIssue({code:"custom",message:`generation.language.${l} does not match target language "${o.language}"`,path:["generation","language",l]})}),n.publish&&!Mjg[n.publish.registry].some(l=>l===o.language)&&s.addIssue({code:"custom",message:`registry "${n.publish.registry}" is not supported for target language "${o.language}"`,path:["output","publish","registry"]}),n.publish&&(_jg(i,n.publish.registry,s),n.delivery!=="github"&&n.publish.shouldGeneratePublishWorkflow===!0&&s.addIssue({code:"custom",message:"output.publish.shouldGeneratePublishWorkflow requires GitHub delivery",path:["output","publish","shouldGeneratePublishWorkflow"]})),Ujg(n,o.language,s),t?.legacyInput){let l=o.sourceOrigin==="postman"?"postman-build-parameters":"fern-generator-invocation";t.legacyInput.kind!==l&&s.addIssue({code:"custom",message:`compatibility.legacyInput kind "${t.legacyInput.kind}" does not match target.sourceOrigin "${o.sourceOrigin}"`,path:["compatibility","legacyInput","kind"]})}});function g$t(e){return h$t.parse(e)}var EhO=w.enum(["generation.generateFullProject"]),Vjg=vop(h$t);function AEi(e){let t=g$t(e),r=uNg(t,Vjg),n=[];if(r===void 0)throw new Error("SDK Config IR v1 root cannot be omitted from its wire payload");t.generation.generateFullProject&&n.push("generation.generateFullProject");let i=JSON.stringify(r);if(i===void 0)throw new Error("SDK Config IR v1 could not be serialized as JSON");return{body:new TextEncoder().encode(i),requiredCapabilities:n}}Co();vQ();var Gjg=50,qjg=6e4;async function Vop({origin:e,token:t,organization:r,sdkName:n,version:i,languages:o}){let s=new URLSearchParams({sdkName:n,version:i,status:"SUCCESS",limit:String(Gjg)});for(let l of o)s.append("language",l);let{data:a}=await Ld.get(`${e}/v1/fern/artifacts?${s}`,{headers:{Authorization:`Bearer ${t}`,"X-Fern-Organization-Id":r},timeout:qjg}),c=new Map;for(let{language:l,placeholdersSnippetsUrl:u}of a.data)u!=null&&!c.has(l)&&c.set(l,u);return c}gt();Vwt();vQ();function $hp(e){let t=JSON.parse(e),r=oi(t)&&oi(t.snippets)?t.snippets.endpoints:void 0,n=oi(t)?t.endpoints??r:void 0;return oi(n)?Object.entries(n).flatMap(([i,o])=>Object.entries(oi(o)?o:{}).flatMap(([s,a])=>{let c=NL.safeParse(s.toUpperCase());return c.success&&typeof a=="string"&&a.trim()!==""?[{path:i,method:c.data,code:a}]:[]})):[]}async function egp(e){return(await Ld.get(e,{responseType:"text",transformResponse:r=>r})).data}var _3g=["cli","mcp","terraform"],tgp=new Set(pTs.options);for(let e of _3g)tgp.delete(e);function rgp(e){let t=e;return[...tgp].flatMap(r=>{let n=Lar(t[`${r}Sdk`]?.version);return n==null?[]:[{type:r,version:n}]})}function ngp({snippetsConfig:e,sdkNames:t={},error:r}){let n=Zn(r),i=rgp(e);return i.length===0?[`Failed to read sdk snippets, error: ${n}`]:i.map(({type:o,version:s})=>{let a=t[o]??[];return`Failed to read sdk snippets for sdk: ${a.length>0?a.join(", "):"unknown"}, language: ${o}, version: ${s}, error: ${n}`})}var U3g=e=>e.type==="literal"?e.value:`{${e.value}}`;function V3g({method:e,path:t}){return`${e} ${t.parts.map(U3g).join("")}`}function G3g(e=[],t){return[...e,...t.filter(r=>!e.some(({language:n})=>n===r.language))]}function q3g(e,t){let r=V3g(e),n=[...t].flatMap(([o,s])=>{let a=s.get(r);return a==null?[]:[{language:o,code:a}]});if(n.length===0)return e;let i=e.examples.map(o=>({...o,codeSamples:G3g(o.codeSamples??void 0,n)}));return{...e,examples:i}}function ABs(e,t){return jji(e,...[...t].map(r=>`${r}Sdk`))}function igp({sdkGenLanguages:e,dynamicIrLanguages:t}){let r=[...[...e].map(n=>`${n}: sdk-gen`),...[...t].map(n=>`${n}: Fern dynamic IR`)];return r.length===0?void 0:`SDK snippet sources (${r.join(", ")})`}function W3g(e,t){let r=i=>({...i,endpoints:i.endpoints.map(t)}),n=Object.entries(e.subpackages).map(([i,o])=>[i,r(o)]);return{...e,rootPackage:r(e.rootPackage),subpackages:Object.fromEntries(n)}}var ogp=(e,t)=>`${e}
4118
4118
  ${t}`;function H3g(e,t){let r=new Map;for(let{type:n,version:i}of e)for(let o of t[n]??[]){let s=ogp(o,i),a=r.get(s)??{sdkName:o,version:i,languages:[]};r.set(s,{...a,languages:[...a.languages,n]})}return r}function K3g(e,t){try{let r=e();return r==null&&t.warn("FERN_SDK_GEN_API_ORIGIN is not set, so the SDK snippets cannot be read (the docs are not affected)"),r}catch(r){t.warn(`The sdk-gen-api origin is not usable, so the SDK snippets cannot be read (the docs are not affected): ${Zn(r)}`);return}}async function sgp({token:e,organization:t,snippetsConfig:r,sdkNames:n={},logger:i},{getOrigin:o=Kse,findSnippetsUrls:s=c=>Vop(c),readSnippets:a=egp}={}){let c=rgp(r);if(c.length===0)return new Map;let l=K3g(o,i);if(l==null)return new Map;let u=new Map(await Promise.all([...H3g(c,n)].map(async([f,m])=>{try{return[f,await s({origin:l,token:e,organization:t,...m})]}catch(g){return i.warn(`Could not find the snippets of SDK "${m.sdkName}" ${m.version} in the sdk-gen-api (the docs are not affected): ${Zn(g)}`),[f,new Map]}}))),p=new Map(await Promise.all(c.map(async({type:f,version:m})=>{let g=n[f]??[],A=g.map(b=>u.get(ogp(b,m))?.get(f)).find(b=>b!=null);if(A==null)return g.length>0&&i.warn(`No built ${f} SDK ${m} with snippets was found (the docs are not affected)`),[f,new Map];try{let b=$hp(await a(A));return[f,new Map(b.map(({method:I,path:C,code:x})=>[`${I} ${C}`,x]))]}catch(b){return i.warn(`Could not read the ${f} snippets (the docs are not affected): ${Zn(b)}`),[f,new Map]}}))),d=new Map([...p].filter(([,f])=>f.size>0));if(d.size>0){let f=[...d].map(([m,g])=>`${m}: ${g.size}`);i.info(`Loaded SDK snippets (${f.join(", ")})`)}return d}function agp(e,t){if(t.size===0)return e;let{snippetsConfiguration:r}=e;return{...W3g(e,n=>q3g(n,t)),snippetsConfiguration:r==null?void 0:ABs(r,t.keys())}}var J3g=new Set(["legacy","ledger"]);function c0i(){if(process.env.FERN_SELF_HOSTED==="true")return"legacy";let e=process.env.FERN_DOCS_DEPLOY_MODE?.toLowerCase().trim();return e==null||e===""?"ledger":Y3g(e)?e:(console.warn(`[fern] Unrecognized FERN_DOCS_DEPLOY_MODE="${e}" \u2014 falling back to "ledger". Valid values: ledger, legacy.`),"ledger")}function Y3g(e){return J3g.has(e)}rr();var ugp=require("child_process"),f2e=require("fs/promises"),p2e=Ae(require("path"),1),pgp=require("util"),yBs=20*1024*1024,cgp=5e3,fgp=new Set([".git","node_modules",".guest-session",".DS_Store",".envrc",".npmrc",".netrc"]),X3g="fern.config.json",Z3g="fern";async function dgp(e){let t=e;for(let r=0;r<4;r++){if(await i_g(p2e.default.join(t,X3g)))return t;let n=p2e.default.dirname(t);if(n===t)break;t=n}return e}async function mgp({fernRoot:e}){let t=await n_g(e);if(t==="failed")return{type:"skipped",reason:"git couldn't list the fern/ folder, so Fern can't tell which files it ignores"};let r=(t??await hgp(e)).map(a=>aA(a)).filter(a=>e_g(a)&&!$3g(a)).sort();if(r.length===0)return{type:"skipped",reason:"the fern/ folder has no files"};if(r.length>cgp)return{type:"skipped",reason:`the fern/ folder has more than ${cgp.toLocaleString()} files`};let n=[],i=[],o=0;for(let a of r){let c;try{if(!(await(0,f2e.lstat)(p2e.default.join(e,a))).isFile()){i.push(a);continue}c=await(0,f2e.readFile)(p2e.default.join(e,a))}catch{i.push(a);continue}let l=`${Z3g}/${a}`,u=r_g(c),p=u!=null?{path:l,content:u}:{path:l,content:c.toString("base64"),encoding:"base64"};if(o+=Buffer.byteLength(JSON.stringify(p),"utf-8")+1,o>yBs)return{type:"skipped",reason:lgp()};n.push(p)}let s=Buffer.from(JSON.stringify(n),"utf-8");return s.length>yBs?{type:"skipped",reason:lgp()}:{type:"ok",buffer:s,fileCount:n.length,unreadable:i}}function $3g(e){return e.split("/").some(t=>fgp.has(t)||t===".env"||t.startsWith(".env."))}function lgp(){return`the fern/ folder is larger than ${yBs/(1024*1024)} MB once packed`}function e_g(e){return e!==""&&!p2e.default.posix.isAbsolute(e)&&!e.split("/").some(t=>t===".."||t==="")}var t_g=new TextDecoder("utf-8",{fatal:!0});function r_g(e){if(!e.includes(0))try{return t_g.decode(e)}catch{return}}async function n_g(e){let t=(0,pgp.promisify)(ugp.execFile);try{await t("git",["rev-parse","--is-inside-work-tree"],{cwd:e})}catch{return}try{let{stdout:r}=await t("git",["-c","core.quotePath=false","ls-files","--cached","--others","--exclude-standard","-z","--","."],{cwd:e,maxBuffer:67108864});return[...new Set(r.split("\0").filter(n=>n!==""))]}catch{return"failed"}}async function hgp(e,t=""){let r=await(0,f2e.readdir)(p2e.default.join(e,t),{withFileTypes:!0}),n=[];for(let i of r){if(fgp.has(i.name))continue;let o=t===""?i.name:p2e.default.join(t,i.name);i.isDirectory()?n.push(...await hgp(e,o)):i.isFile()&&n.push(o)}return n}async function i_g(e){try{return await(0,f2e.access)(e),!0}catch{return!1}}function l0i(){return process.env.FERN_FDR_ORIGIN??process.env.OVERRIDE_FDR_ORIGIN??"https://registry.buildwithfern.com"??"https://registry.buildwithfern.com"}function o_g(e){if(typeof e!="object"||e==null)return!1;let t=e;return typeof t.siteId=="string"&&typeof t.orgId=="string"&&typeof t.domain=="string"&&typeof t.url=="string"&&typeof t.status=="string"&&typeof t.expiresAt=="string"}async function ggp({fdrOrigin:e,token:t}){let r=new URL("/v2/registry/docs/anonymous/guest-site",e);r.searchParams.set("orgId",t.organizationId);let n=await fetch(r,{headers:{Authorization:`Bearer ${t.value}`},signal:AbortSignal.timeout(15e3)});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`FDR answered ${n.status} when resolving the guest docs site: ${o}`)}let i=await n.json().catch(()=>{});if(!o_g(i))throw new Error("FDR returned an unexpected guest docs site payload");return i}function Agp(e){if(typeof e!="object"||e==null)return{};let t=e,r=typeof t.expiresAt=="string"?new Date(t.expiresAt):void 0;return{claimUrl:typeof t.claimUrl=="string"?t.claimUrl:void 0,expiresAt:r!=null&&!Number.isNaN(r.getTime())?r:void 0}}gt();c0();nm();Zhe();var vgp=require("crypto"),Cgp=require("fs/promises"),xgp=Ae(WX(),1);var a_g=10,c_g=4,EBs=3,l_g=1e3;function IBs(e){return(0,vgp.createHash)("sha256").update(e).digest("hex")}var Sgp=/file:([^\s"'<>)}\]]+)/g;function u_g(e){let t=new Set;for(let r of e.matchAll(Sgp)){let n=r[1];n!=null&&t.add(n)}return[...t]}function p_g(e,t){return t==null||t.size===0?e:e.replace(Sgp,(r,n)=>`file:${t.get(n)??n}`)}function f_g(e){return JSON.stringify(e,(t,r)=>hr(r)?Object.fromEntries(Object.entries(r).sort(([n],[i])=>n<i?-1:n>i?1:0)):r)}function Egp(e){let t=Buffer.from(f_g(e),"utf-8"),r=IBs(t);return{ref:{hash:r,contentType:"application/json",contentLength:t.length},hash:r,buf:t}}var d_g={robotsTxt:"robots.txt",llmsTxt:"llms.txt",llmsFullTxt:"llms-full.txt"};function m_g({agents:e,fileManifest:t,fileIdToPath:r}){if(e==null||t==null)return t;let n;for(let[i,o]of Object.entries(d_g)){let s=e[i];if(s==null)continue;let a=r?.get(s)??s,c=t[a];a===o||c==null||(n??={...t},n[o]={...c,filename:o})}return n??t}function B9e({docsDefinition:e,git:t,apiDefinitions:r,fileManifest:n,fileIdToPath:i,editThisPage:o,locale:s}){let a=new Map,c={};for(let[f,m]of Object.entries(e.pages)){if(m==null)continue;let g=p_g(m.markdown,i),A=Buffer.from(g,"utf-8"),b=IBs(A),I=u_g(g);c[f]={hash:b,contentType:"text/markdown",contentLength:A.length,...I.length>0?{referencedFiles:I}:{}},a.set(b,A)}let l=NXt({docsConfig:e.config,fileManifest:n,fileIdToPath:i,editThisPage:o}),u=null;if(r.size>0){let f=Object.fromEntries(r),m=Egp(f);a.set(m.hash,m.buf),u=m.ref}let p=null;if(e.jsFiles!=null&&Object.keys(e.jsFiles).length>0){let f=Egp(e.jsFiles);a.set(f.hash,f.buf),p=f.ref}return{localeEntry:{root:e.config.root??e.config.navigation,pages:c,config:l,apiManifest:u,jsFiles:p,fileManifest:m_g({agents:e.config.agents,fileManifest:n,fileIdToPath:i}),redirects:null,locale:s??e.config.translations?.defaultLocale??"en",git:t},blobs:a}}async function wgp({docsDefinition:e,publishStartedAt:t,organization:r,domain:n,basepath:i,basepathAware:o,previewId:s,customDomains:a,git:c,token:l,fdrOrigin:u,headers:p,context:d,apiDefinitions:f,fileManifest:m,filePaths:g,fileIdToPath:A,editThisPage:b,resolver:I,source:C,globalTheme:x}){let{localeEntry:S,blobs:B}=B9e({docsDefinition:e,git:c,apiDefinitions:f,fileManifest:m,fileIdToPath:A,editThisPage:b}),D=await Gwt({docsDefinition:e,git:c,apiDefinitions:f,fileManifest:m,fileIdToPath:A,editThisPage:b,resolver:I,context:d});for(let Te of D)for(let[pe,ue]of Te.blobs)B.set(pe,ue);let{createDocsLedgerClient:R}=await Promise.resolve().then(()=>(Vwt(),Zhp)),O=R({baseUrl:u,token:l,headers:p}),z=[S,...D.map(Te=>Te.localeEntry)],X;if(C!=null){let Te=IBs(C);B.set(Te,C),X={hash:Te,contentType:"application/octet-stream",contentLength:C.length}}let ee={orgId:r,domain:n,basepath:i??"",...o&&{basepathAware:!0},customDomains:a??[],previewId:s??null,defaultLocale:S.locale,locales:z,...X!=null&&{source:X},...t!=null&&{publishStartedAt:t},...x!=null&&{globalTheme:x}};d.logger.debug("[ledger] Registering deployment...");let te=performance.now(),ae=await O.register(ee),ce=performance.now()-te;d.logger.debug(`[ledger] Registered in ${ce.toFixed(0)}ms \u2014 hash=${ae.deploymentHash}, missing=${ae.missingContent.length} blobs`),await vBs(ae.missingContent,B,d,g),d.logger.debug("[ledger] Finishing deployment...");let se=performance.now(),he=await O.finish(ee),xe=performance.now()-se;if(d.logger.debug(`[ledger] Finished in ${xe.toFixed(0)}ms \u2014 deploymentId=${he.deploymentId}, reused=${he.reusedDeployment}`),he.translationsProcessed!=null)for(let Te of he.translationsProcessed)d.logger.debug(`[ledger] Locale "${Te.locale}": ${Te.segmentsAdded} segment(s) added`);return he}async function vBs(e,t,r,n){if(e.length>0){r.logger.debug(`[ledger] Uploading ${e.length} missing blobs...`);let i=performance.now(),o=await eD(a_g,[...e],async({hash:l,uploadUrl:u})=>{let p=t.get(l),d="application/octet-stream";if(p==null&&n!=null){let f=n.get(l);if(f!=null){p=await(0,Cgp.readFile)(f);let m=xgp.lookup(f);m!==!1&&(d=m)}}return p==null?(r.logger.warn(`[ledger] Server requested blob ${l} but we don't have it \u2014 skipping`),"skipped"):h_g(p,u,l,d,r)}),s=o.filter(l=>l==="uploaded").length,a=o.filter(l=>l==="already_exists").length,c=performance.now()-i;r.logger.debug(`[ledger] Upload complete in ${c.toFixed(0)}ms \u2014 ${s} uploaded, ${a} already in store`)}else r.logger.debug("[ledger] All content already in CAS \u2014 no uploads needed")}async function h_g(e,t,r,n,i){let o=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);for(let s=0;s<=EBs;s++){let a=await fetch(t,{method:"PUT",headers:{"Content-Type":n},body:o});if(a.ok)return"uploaded";if(a.status===412)return i.logger.debug(`[ledger] Blob ${r} already exists in store \u2014 skipping`),"already_exists";if(a.status===403){let u=await a.text();throw new Error(`[ledger] Presigned URL rejected for ${r} (expired or signature mismatch): ${u}`)}if(a.status===400){let u=await a.text();throw new Error(`[ledger] Content integrity check failed for ${r}: ${u}`)}if((a.status===429||a.status>=500)&&s<EBs){let u=l_g*2**s;i.logger.debug(`[ledger] Upload ${r} got ${a.status}, retrying in ${u}ms (attempt ${s+1}/${EBs})`),await ef(u);continue}let l=await a.text();throw new Error(`[ledger] S3 upload failed for ${r}: ${a.status} ${l}`)}throw new Error(`[ledger] Upload exhausted retries for ${r}`)}function Igp(e,t,r){try{let n=D7(e,tn.ApiDefinitionId(t),new R7({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}}));return k7(n)}catch(n){r.logger.debug(`[ledger] Failed to convert API definition "${t}" to read form: ${String(n)}`);return}}function g_g({baseApiDefinitions:e,translatedSpecs:t,context:r}){let n=new Map(e);for(let[i,o]of t)try{let s=yO({ir:o.ir,snippetsConfig:o.snippetsConfig,playgroundConfig:o.playgroundConfig,graphqlOperations:o.graphqlOperations,graphqlTypes:o.graphqlTypes,context:r,apiNameOverride:o.apiName});n.set(i,s)}catch(s){r.logger.warn(`[ledger] Failed to convert translated API definition for API "${i}": ${String(s)}. Falling back to base (untranslated) API.`)}return n}async function Gwt({docsDefinition:e,git:t,apiDefinitions:r,fileManifest:n,fileIdToPath:i,editThisPage:o,resolver:s,context:a}){if(s==null)return[];let c=s.getTranslationPages(),l=s.getTranslationNavigationOverlays();if(c==null||Object.keys(c).length===0)return[];let u=s.getTranslatedApiSpecs(),p={};if(u.size>0)for(let[m,g]of r){let A=Igp(g,m,a);A!=null&&(p[m]=A)}let d=Object.entries(c);a.logger.debug(`[ledger] Building ${d.length} translation locale(s)...`);let{buildTranslatedDocsDefinition:f}=await Promise.resolve().then(()=>(bgp(),ygp));return eD(c_g,d,async([m,g])=>{let A=await f({docsDefinition:e,locale:m,localePages:g,translationNavigationOverlays:l,resolver:s,context:a}),b=u.get(m),I=r,C=new Set;if(b!=null&&b.size>0&&(I=g_g({baseApiDefinitions:r,translatedSpecs:b,context:a}),A.config.root!=null)){let B={};for(let[O]of b){let z=I.get(O);if(z!=null){let X=Igp(z,O,a);X!=null&&(B[O]=X)}}let D=I5e(A.config.root,p,B);if(D.size>0){a.logger.warn(`Translated API definition(s) [${Array.from(D).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`);for(let O of D){let z=r.get(O);z!=null&&I.set(O,z)}}let R=new Set(Object.keys(B).filter(O=>!D.has(O)));C=new Set(Array.from(R).filter(O=>I.get(O)!==r.get(O))),Object.keys(B).length>0&&(A.config.root=v5e(A.config.root,p,B,{rewritableApiIds:R}))}A.config.root=O5e(A.config.root,{translatedApiDefinitionIds:C});let{localeEntry:x,blobs:S}=B9e({docsDefinition:A,git:t,apiDefinitions:I,fileManifest:n,fileIdToPath:i,editThisPage:o,locale:m});return{locale:m,localePages:g,translatedDefinition:A,localeEntry:x,blobs:S}})}Vwt();async function Tgp({docsDefinition:e,organization:t,basePath:r,previewId:n,git:i,token:o,fdrOrigin:s,headers:a,context:c,apiDefinitions:l,fileManifest:u,filePaths:p,fileIdToPath:d,editThisPage:f,resolver:m,globalTheme:g}){let{localeEntry:A,blobs:b}=B9e({docsDefinition:e,git:i,apiDefinitions:l,fileManifest:u,fileIdToPath:d,editThisPage:f}),I=await Gwt({docsDefinition:e,git:i,apiDefinitions:l,fileManifest:u,fileIdToPath:d,editThisPage:f,resolver:m,context:c});for(let ee of I)for(let[te,ae]of ee.blobs)b.set(te,ae);let C=[A,...I.map(ee=>ee.localeEntry)],x=i0i({baseUrl:s,token:o,headers:a});c.logger.debug("[ledger-preview] Registering preview deployment...");let S=performance.now(),B={orgId:t,previewId:n??null,basePath:r??"",defaultLocale:A.locale,locales:C,root:A.root,pages:A.pages,apiManifest:A.apiManifest,config:A.config,fileManifest:A.fileManifest,jsFiles:A.jsFiles,redirects:A.redirects,locale:A.locale,...g!=null&&{globalTheme:g},version:A.version,repo:A.repo,git:i},D=await x.previewRegister(B),R=performance.now()-S;c.logger.debug(`[ledger-preview] Registered in ${R.toFixed(0)}ms \u2014 hash=${D.deploymentHash}, preview=${D.previewUrl}, missing=${D.missingContent.length} blobs`),await vBs(D.missingContent,b,c,p),c.logger.debug("[ledger-preview] Finishing preview deployment...");let O=performance.now(),z=await x.finish({orgId:t,domain:D.domain,basepath:D.basepath,customDomains:[],previewId:D.previewId,defaultLocale:A.locale,locales:C,...g!=null&&{globalTheme:g}}),X=performance.now()-O;if(c.logger.debug(`[ledger-preview] Finished in ${X.toFixed(0)}ms \u2014 deploymentId=${z.deploymentId}, reused=${z.reusedDeployment}`),z.translationsProcessed!=null)for(let ee of z.translationsProcessed)c.logger.debug(`[ledger-preview] Locale "${ee.locale}": ${ee.segmentsAdded} segment(s) added`);return{previewUrl:D.previewUrl,deploymentId:z.deploymentId}}gt();async function Ogp({fn:e,maxRetries:t,baseDelayMs:r,jitterFactor:n=0,isRetryable:i=()=>!0,logger:o,label:s,delayFn:a=ef}){let c;for(let l=0;l<=t;l++)try{return await e()}catch(u){if(c=u,!i(u)||l>=t)throw u;let p=n>0?1+(Math.random()-.5)*n:1,d=Math.round(r*2**l*p);s!=null&&o.warn(`${s} (attempt ${l+1}/${t+1}), retrying in ${d}ms...`),await a(d)}throw c}var A_g=10,Pgp=10,u0i=parseInt(process.env.FERN_DOCS_ASSET_HASH_CONCURRENCY??"32",10),y_g=3,b_g=1e3,E_g=.5;function I_g(e){if(e==null)return"Unknown error";let t=Zn(e),r=e.data;if(r?.issues!=null&&Array.isArray(r.issues)&&r.issues.length>0){let n=r.issues.map(i=>{let o=i.path?.join(".")??"",s=i.message??"invalid";return o?` - ${o}: ${s}`:` - ${s}`}).join(`
@@ -4145,7 +4145,7 @@ ${ut.stack}`),ee&&m?.({event:"reload",ok:!1,durationMs:Date.now()-we,error:en(ut
4145
4145
 
4146
4146
  `),o.add(u),l.on("close",()=>o.delete(u));return}s.requestStarted(),u.once("close",()=>s.requestFinished());let d=mIp(l.url,i),f=iRs.default.request(d!=null?{host:"127.0.0.1",port:n,method:l.method,path:d,headers:l.headers}:{host:"127.0.0.1",port:t,method:l.method,path:l.url,headers:{...l.headers,[yIp]:r}},m=>{let g={...m.headers};if(!((g["content-type"]??"").includes("text/html")&&g["content-encoding"]==null)){u.writeHead(m.statusCode??502,g),m.pipe(u);return}let b=[];m.on("data",I=>b.push(I)),m.on("end",()=>{let I=Buffer.concat(b).toString("utf-8"),C=I.lastIndexOf("</body>"),x=C>=0?`${I.slice(0,C)}${gIp}${I.slice(C)}`:`${I}${gIp}`,S=Buffer.from(x,"utf-8");delete g["transfer-encoding"],g["content-length"]=S.byteLength.toString(),u.writeHead(m.statusCode??502,g),u.end(S)}),m.on("error",()=>u.destroy())});f.on("error",m=>{u.headersSent||u.writeHead(502,{"content-type":"text/plain"}),u.end(`Astro preview server unavailable: ${m.message}
4147
4147
  `)}),l.pipe(f)})}function OWg({req:e,res:t,pathname:r,port:n,serverInfo:i,onShutdownRequest:o}){let s=(c,l,u={})=>{t.writeHead(c,{"content-type":"application/json","cache-control":"no-store",...u}),t.end(`${JSON.stringify(l)}
4148
- `)},a=_ju({remoteAddress:e.socket.remoteAddress,host:e.headers.host,origin:e.headers.origin,controlHeader:e.headers[axt],serverPort:n});if(a!=null){s(403,{error:a});return}if(r===oxt){if(e.method!=="GET"){s(405,{error:"use GET"},{allow:"GET"});return}s(200,i);return}if(e.method!=="POST"){s(405,{error:"use POST"},{allow:"POST"});return}t.once("finish",o),s(202,{stopping:!0},{connection:"close"})}function PWg(){return new Promise((e,t)=>{let r=oRs.default.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),i=typeof n=="object"&&n!=null?n.port:void 0;r.close(()=>i!=null?e(i):t(new Error("could not allocate a port")))})})}function BWg(e,t,r){let n=Date.now()+r;return new Promise((i,o)=>{let s=!1;t.on("exit",c=>{s=!0,o(new Error(`Astro preview server exited with code ${c} before becoming ready`))});let a=()=>{if(s)return;if(Date.now()>n){o(new Error("timed out waiting for the Astro preview server to become ready"));return}let c=oRs.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}gt();Pt();var vIp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,EIp="docs.buildwithfern.com",IIp=62;function L9e(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),vIp.test(t)}function yer({orgId:e,previewId:t}){let r=sX(t),n=`${e}-preview-${r}.${EIp}`;if(n.length<=IIp)return n;let i=`${e}-preview-`,o=IIp-i.length;if(o<8)throw new T({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:T.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${EIp}`}gt();c0();nm();rr();NE();Pt();ln();var FRs=require("child_process"),Nvp=Ae(xIp(),1),NRs=Ae(aIi(),1),jRs=Ae(require("fs"),1),QRs=require("fs/promises"),jvp=Ae(require("http"),1),zvp=Ae(require("os"),1),SIi=Ae(require("path"),1);PRs();c0();rr();var BRs=require("fs/promises");async function DRs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:l}=e,u=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!u&&!p)return r;let d=n.config.translations?.defaultLocale,f=new Set([...Object.keys(i??{}),...Object.keys(s??{})]);for(let m of f){if(m===d)continue;let g=i?.[m]??{};try{let A=async ce=>{let se=go(c,ce),he=Rn(c,Ee.of(`translations/${m}/${se}`));return await Gt(he)?he:ce},b=async ce=>{let se=await A(ce),he=await(0,BRs.readFile)(se,"utf-8"),xe=he.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return xe!=null?he.slice(xe[0].length):he},I=async ce=>{let se=await A(ce);return(0,BRs.readFile)(se,"utf-8")},C={};for(let[ce,se]of Object.entries(n.pages))se!=null&&(C[ce]=se);for(let[ce,se]of Object.entries(g))try{let he=C[ce],xe=Rn(c,Ee.of(ce)),{markdown:Te}=await Bk({markdown:se,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,markdownLoader:b}),pe=await E_({markdown:Te,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,fileLoader:I}),ue=I_({markdown:pe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t}),Pe=AO(ue);Pe=h_(Pe,a,l,{absolutePathToMarkdownFile:xe,absolutePathToFernFolder:c},t),C[ce]={markdown:Pe,rawMarkdown:Pe,editThisPageUrl:he?.editThisPageUrl,editThisPageLaunch:he?.editThisPageLaunch}}catch(he){t.logger.warn(`Failed to process translated page "${ce}" for locale "${m}": ${String(he)}. Falling back to base page.`)}let x=C5e(n.config.root,g,t),S=o?.[m],B=n.config.announcement,D=n.config.navbarLinks;S!=null&&(x=S5e(x,S),B=w5e(S)??B,S.navbarLinks!=null&&(D=S.navbarLinks));let R=n.apis,O=s?.[m],z=O,X;if(O!=null&&x!=null){let ce=I5e(x,R,O);ce.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(ce).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`),z=Object.fromEntries(Object.entries(O).filter(([se])=>!ce.has(se)))),X=new Set(Object.keys(O).filter(se=>!ce.has(se)))}let te=z!=null&&Object.keys(z).length>0?{...n.apis,...z}:n.apis;O!=null&&Object.keys(O).length>0&&x!=null&&(x=v5e(x,R,O,{rewritableApiIds:X}));let ae={...n,apis:te,pages:C,config:{...n.config,root:x,announcement:B,navbarLinks:D,settings:T5e(n.config.settings,S)}};r.set(m,ae),t.logger.debug(`Computed translated definition for locale "${m}"`+(O!=null?` (with ${Object.keys(O).length} translated API(s))`:""))}catch(A){t.logger.warn(`Failed to compute translation for locale "${m}": ${String(A)}`)}}return r}rr();var iW=require("fs/promises"),Pvp=require("os"),kRs=Ae(require("path"),1),nHg=".fern",iHg="logs",RRs=100*1024*1024;function oHg(){return"cli@5.217.0"}var W9e=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t,r){if(this.initialized)return;this.consoleLogger=t;let n=r??ke(ke(Xt.of((0,Pvp.homedir)()),Ee.of(nHg)),Ee.of(iHg));await Gt(n)||await(0,iW.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ke(n,Ee.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${kRs.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
4148
+ `)},a=_ju({remoteAddress:e.socket.remoteAddress,host:e.headers.host,origin:e.headers.origin,controlHeader:e.headers[axt],serverPort:n});if(a!=null){s(403,{error:a});return}if(r===oxt){if(e.method!=="GET"){s(405,{error:"use GET"},{allow:"GET"});return}s(200,i);return}if(e.method!=="POST"){s(405,{error:"use POST"},{allow:"POST"});return}t.once("finish",o),s(202,{stopping:!0},{connection:"close"})}function PWg(){return new Promise((e,t)=>{let r=oRs.default.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),i=typeof n=="object"&&n!=null?n.port:void 0;r.close(()=>i!=null?e(i):t(new Error("could not allocate a port")))})})}function BWg(e,t,r){let n=Date.now()+r;return new Promise((i,o)=>{let s=!1;t.on("exit",c=>{s=!0,o(new Error(`Astro preview server exited with code ${c} before becoming ready`))});let a=()=>{if(s)return;if(Date.now()>n){o(new Error("timed out waiting for the Astro preview server to become ready"));return}let c=oRs.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}gt();Pt();var vIp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,EIp="docs.buildwithfern.com",IIp=62;function L9e(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),vIp.test(t)}function yer({orgId:e,previewId:t}){let r=sX(t),n=`${e}-preview-${r}.${EIp}`;if(n.length<=IIp)return n;let i=`${e}-preview-`,o=IIp-i.length;if(o<8)throw new T({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:T.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${EIp}`}gt();c0();nm();rr();NE();Pt();ln();var FRs=require("child_process"),Nvp=Ae(xIp(),1),NRs=Ae(aIi(),1),jRs=Ae(require("fs"),1),QRs=require("fs/promises"),jvp=Ae(require("http"),1),zvp=Ae(require("os"),1),SIi=Ae(require("path"),1);PRs();c0();rr();var BRs=require("fs/promises");async function DRs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:l}=e,u=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!u&&!p)return r;let d=n.config.translations?.defaultLocale,f=new Set([...Object.keys(i??{}),...Object.keys(s??{})]);for(let m of f){if(m===d)continue;let g=i?.[m]??{};try{let A=async ce=>{let se=go(c,ce),he=Rn(c,Ee.of(`translations/${m}/${se}`));return await Gt(he)?he:ce},b=async ce=>{let se=await A(ce),he=await(0,BRs.readFile)(se,"utf-8"),xe=he.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return xe!=null?he.slice(xe[0].length):he},I=async ce=>{let se=await A(ce);return(0,BRs.readFile)(se,"utf-8")},C={};for(let[ce,se]of Object.entries(n.pages))se!=null&&(C[ce]=se);for(let[ce,se]of Object.entries(g))try{let he=C[ce],xe=Rn(c,Ee.of(ce)),{markdown:Te}=await Bk({markdown:se,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,markdownLoader:b}),pe=await E_({markdown:Te,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,fileLoader:I}),ue=I_({markdown:pe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t}),Pe=AO(ue);Pe=h_(Pe,a,l,{absolutePathToMarkdownFile:xe,absolutePathToFernFolder:c},t),C[ce]={markdown:Pe,rawMarkdown:Pe,editThisPageUrl:he?.editThisPageUrl,editThisPageLaunch:he?.editThisPageLaunch}}catch(he){t.logger.warn(`Failed to process translated page "${ce}" for locale "${m}": ${String(he)}. Falling back to base page.`)}let x=C5e(n.config.root,g,t),S=o?.[m],B=n.config.announcement,D=n.config.navbarLinks;S!=null&&(x=S5e(x,S),B=w5e(S)??B,S.navbarLinks!=null&&(D=S.navbarLinks));let R=n.apis,O=s?.[m],z=O,X;if(O!=null&&x!=null){let ce=I5e(x,R,O);ce.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(ce).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`),z=Object.fromEntries(Object.entries(O).filter(([se])=>!ce.has(se)))),X=new Set(Object.keys(O).filter(se=>!ce.has(se)))}let te=z!=null&&Object.keys(z).length>0?{...n.apis,...z}:n.apis;O!=null&&Object.keys(O).length>0&&x!=null&&(x=v5e(x,R,O,{rewritableApiIds:X}));let ae={...n,apis:te,pages:C,config:{...n.config,root:x,announcement:B,navbarLinks:D,settings:T5e(n.config.settings,S)}};r.set(m,ae),t.logger.debug(`Computed translated definition for locale "${m}"`+(O!=null?` (with ${Object.keys(O).length} translated API(s))`:""))}catch(A){t.logger.warn(`Failed to compute translation for locale "${m}": ${String(A)}`)}}return r}rr();var iW=require("fs/promises"),Pvp=require("os"),kRs=Ae(require("path"),1),nHg=".fern",iHg="logs",RRs=100*1024*1024;function oHg(){return"cli@5.217.1"}var W9e=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t,r){if(this.initialized)return;this.consoleLogger=t;let n=r??ke(ke(Xt.of((0,Pvp.homedir)()),Ee.of(nHg)),Ee.of(iHg));await Gt(n)||await(0,iW.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ke(n,Ee.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${kRs.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
4149
4149
  `);await(0,iW.writeFile)(this.logFilePath,s,"utf-8"),this.initialized=!0,this.enforceLogSizeLimit(n)}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
4150
4150
  `;try{await(0,iW.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let n={timestamp:t.timestamp,source:oHg(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(n)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let n={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliDocsGeneration(t,r){let n={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliValidation(t,r){let n={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(n)}async enforceLogSizeLimit(t){try{let n=(await(0,iW.readdir)(t)).filter(c=>c.endsWith(".log")),i=[];for(let c of n){let l=kRs.default.join(t,c);try{let u=await(0,iW.stat)(l);i.push({name:c,fullPath:l,size:u.size,mtimeMs:u.mtimeMs})}catch{}}let o=i.reduce((c,l)=>c+l.size,0),s=Math.round(o/1024/1024*100)/100,a=RRs/1024/1024;if(o<=RRs){this.consoleLogger?.debug(`Log directory size ${s} MB does not exceed ${a} MB cap`);return}this.consoleLogger?.info(`Rotating logs: total size ${s} MB exceeds ${a} MB cap`),i.sort((c,l)=>c.mtimeMs-l.mtimeMs);for(let c of i){if(o<=RRs)break;if(!(this.logFilePath!=null&&c.fullPath===this.logFilePath))try{await(0,iW.unlink)(c.fullPath),o-=c.size}catch{}}}catch{}}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var xIi={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function Bvp(e){let t=sHg();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i,extractLocaleFromPath:o}=e,s=new Map;function a(l){let u=JSON.stringify(l),p=[];for(let[d]of s)try{d.send(u)}catch{p.push(d)}for(let d of p){let f=s.get(d);f&&(clearInterval(f.pingInterval),s.delete(d))}}let c=t.serve({port:r,async fetch(l,u){if(l.method==="OPTIONS")return new Response(null,{status:204,headers:xIi});let p=new URL(l.url);if(l.headers.get("upgrade")?.toLowerCase()==="websocket"){u.upgrade(l,{data:{connectionId:`${Date.now()}`}});return}if(l.method==="POST"&&p.pathname==="/v2/registry/docs/load-with-url")try{let f=await l.json(),m=o?.(f?.url);return new Response(JSON.stringify(i(m)),{headers:{"Content-Type":"application/json",...xIi}})}catch{return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...xIi}})}let d=/^\/_local\/(.*)/.exec(p.pathname);return l.method==="GET"&&d!=null?new Response(t.file(`/${d[1]}`),{headers:xIi}):new Response("Not Found",{status:404})},websocket:{open(l){let{connectionId:u}=l.data,p=setInterval(()=>{let d=s.get(l);if(!d)return;let f=Date.now();if(f-d.lastPong>9e4){l.close();return}try{l.send(JSON.stringify({type:"ping",timestamp:f}))}catch{l.close()}},3e4);s.set(l,{pingInterval:p,lastPong:Date.now()});try{l.send(JSON.stringify({type:"connected",connectionId:u}))}catch{}},message(l,u){try{let p=JSON.parse(u.toString());if(p.type==="pong"){let d=s.get(l);d&&(d.lastPong=Date.now())}else W9e.isMetricsMessage(p)&&n.logFrontendMetrics(p)}catch{}},close(l){let u=s.get(l);u&&(clearInterval(u.pingInterval),s.delete(l))}}});return{sendData:a,stop:l=>c.stop(l)}}function sHg(){return globalThis.Bun}var Dvp=require("fs"),Rvp=Ae(require("path"),1),aHg=`"use strict";
4151
4151
 
@@ -4483,7 +4483,7 @@ ${A}
4483
4483
 
4484
4484
  Add a 'docs:' section to your fern.yml to get started.`,code:T.Code.ConfigError});let i=n.docs.raw.libraries;if(i==null)throw new T({message:`No libraries configured in docs.yml.
4485
4485
 
4486
- Add a 'libraries' section to configure library documentation.`,code:T.Code.ConfigError});let o=await t.getTokenOrPrompt();await t.verifyOrgAccess({organization:n.org,token:o});let s=n.docs.absoluteFilePath??n.absoluteFilePath??t.cwd,a=Xt.of(Vr(s)),c=new bd({context:t,logLevel:Un.Info});await Frr({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:UO,docsConfig:n.docs.raw})}};function ULs(e){let t=new _Ls;ni(e,"generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",(r,n)=>t.handle(r,n),r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}))}function VLs(e){gA({cli:e,name:"md",subcommands:[ULs,lLs]})}Pt();function G1i(e,t,r,n,i,o){e.command(t,r,s=>{for(let a of o)a(s);return s.command("$0",!1,a=>{let c=a.version(!1);return i!=null?i(c):c},Jtn(n)),s.version(!1).usage(r)})}gt();c0();Pt();ln();gt();Pt();var q1i=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new bd({context:this.context,task:this.task});try{let s=await H$t({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"5.217.0",loginCommand:"fern auth login"});return o.getResult()===mf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:en(s)}}}};gt();ln();var nPt=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
4486
+ Add a 'libraries' section to configure library documentation.`,code:T.Code.ConfigError});let o=await t.getTokenOrPrompt();await t.verifyOrgAccess({organization:n.org,token:o});let s=n.docs.absoluteFilePath??n.absoluteFilePath??t.cwd,a=Xt.of(Vr(s)),c=new bd({context:t,logLevel:Un.Info});await Frr({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:UO,docsConfig:n.docs.raw})}};function ULs(e){let t=new _Ls;ni(e,"generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",(r,n)=>t.handle(r,n),r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}))}function VLs(e){gA({cli:e,name:"md",subcommands:[ULs,lLs]})}Pt();function G1i(e,t,r,n,i,o){e.command(t,r,s=>{for(let a of o)a(s);return s.command("$0",!1,a=>{let c=a.version(!1);return i!=null?i(c):c},Jtn(n)),s.version(!1).usage(r)})}gt();c0();Pt();ln();gt();Pt();var q1i=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new bd({context:this.context,task:this.task});try{let s=await H$t({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"5.217.1",loginCommand:"fern auth login"});return o.getResult()===mf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:en(s)}}}};gt();ln();var nPt=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
4487
4487
  `),this.stream.write(`${le.cyan("\u25C6")} ${le.bold(t.title)}
4488
4488
  `),t.subtitle!=null&&this.stream.write(` ${le.dim(t.subtitle)}
4489
4489
  `),this.stream.write(`
@@ -5550,7 +5550,7 @@ ${r}`}function cBi(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
5550
5550
  `),g="";return c&&(g=u.style.error(c)),[`${p} ${f} ${s}`,[m,g].filter(Boolean).join(`
5551
5551
  `)]});var rZA=ex((e,t)=>{let{validate:r=()=>!0}=e,n=OI(e.theme),[i,o]=sl("idle"),[s,a]=sl(),[c,l]=sl(""),u=ZC({status:i,theme:n});$C(async(g,A)=>{if(i==="idle")if(XC(g)){let b=c;o("loading");let I=await r(b);I===!0?(l(b),o("done"),t(b)):(A.write(c),a(I||"You must provide a valid value"),o("idle"))}else l(A.line),a(void 0)});let p=n.style.message(e.message,i),d="",f;e.mask?d=(typeof e.mask=="string"?e.mask:"*").repeat(c.length):i!=="done"&&(f=`${n.style.help("[input is masked]")}${cBt}`),i==="done"&&(d=n.style.answer(d));let m="";return s&&(m=n.style.error(s)),[[u,p,e.mask?d:f].join(" "),m]});var o7e=Ae(Iw(),1);var nZA={icon:{cursor:Vx.pointer},style:{disabled:e=>o7e.default.dim(`- ${e}`),searchTerm:e=>o7e.default.cyan(e),description:e=>o7e.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${o7e.default.bold(t)} ${o7e.default.dim(r)}`).join(o7e.default.dim(" \u2022 "))},helpMode:"always"};function hYs(e){return!Td.isSeparator(e)&&!e.disabled}function iZA(e){return e.map(t=>{if(Td.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var oZA=ex((e,t)=>{let{pageSize:r=7,validate:n=()=>!0}=e,i=OI(nZA,e.theme),[o,s]=sl("loading"),[a,c]=sl(""),[l,u]=sl([]),[p,d]=sl(),f=ZC({status:o,theme:i}),m=i6(()=>{let z=l.findIndex(hYs),X=l.findLastIndex(hYs);return{first:z,last:X}},[l]),[g=m.first,A]=sl();E4(()=>{let z=new AbortController;return s("loading"),d(void 0),(async()=>{try{let ee=await e.source(a||void 0,{signal:z.signal});z.signal.aborted||(A(void 0),d(void 0),u(iZA(ee)),s("idle"))}catch(ee){!z.signal.aborted&&ee instanceof Error&&d(ee.message)}})(),()=>{z.abort()}},[a]);let b=l[g];$C(async(z,X)=>{if(XC(z))if(b){s("loading");let ee=await n(b.value);s("idle"),ee===!0?(s("done"),t(b.value)):b.name===a?d(ee||"You must provide a valid value"):(X.write(b.name),c(b.name))}else X.write(a);else if(xye(z)&&b)X.clearLine(0),X.write(b.name),c(b.name);else if(o!=="loading"&&(JB(z)||n6(z))){if(X.clearLine(0),JB(z)&&g!==m.first||n6(z)&&g!==m.last){let ee=JB(z)?-1:1,te=g;do te=(te+ee+l.length)%l.length;while(!hYs(l[te]));A(te)}}else c(X.line)});let I=i.style.message(e.message,o),C;if(i.helpMode!=="never")if(e.instructions){let{pager:z,navigation:X}=e.instructions;C=i.style.help(l.length>r?z:X)}else C=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let x=t7e({items:l,active:g,renderItem({item:z,isActive:X}){if(Td.isSeparator(z))return` ${z.separator}`;if(z.disabled){let ae=typeof z.disabled=="string"?z.disabled:"(disabled)";return i.style.disabled(`${z.name} ${ae}`)}let ee=X?i.style.highlight:ae=>ae,te=X?i.icon.cursor:" ";return ee(`${te} ${z.name}`)},pageSize:r,loop:!1}),S;p?S=i.style.error(p):l.length===0&&a!==""&&o==="idle"&&(S=i.style.error("No results found"));let B;if(o==="done"&&b)return[f,I,i.style.answer(b.short)].filter(Boolean).join(" ").trimEnd();B=i.style.searchTerm(a);let D=b?.description,R=[f,I,B].filter(Boolean).join(" ").trimEnd(),O=[S??x," ",D?i.style.description(D):"",C].filter(Boolean).join(`
5552
5552
  `).trimEnd();return[R,O]});var uBt=Ae(Iw(),1);var sZA={icon:{cursor:Vx.pointer},style:{disabled:e=>uBt.default.dim(`- ${e}`),description:e=>uBt.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${uBt.default.bold(t)} ${uBt.default.dim(r)}`).join(uBt.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function lBt(e){return!Td.isSeparator(e)&&!e.disabled}function aZA(e){return e.map(t=>{if(Td.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var gYs=ex((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=OI(sZA,e.theme),{keybindings:o}=i,[s,a]=sl("idle"),c=ZC({status:s,theme:i}),l=e7e(),u=!o.includes("vim"),p=i6(()=>aZA(e.choices),[e.choices]),d=i6(()=>{let D=p.findIndex(lBt),R=p.findLastIndex(lBt);if(D===-1)throw new Ole("[select prompt] No selectable choices. All choices are disabled.");return{first:D,last:R}},[p]),f=i6(()=>"default"in e?p.findIndex(D=>lBt(D)&&D.value===e.default):-1,[e.default,p]),[m,g]=sl(f===-1?d.first:f),A=p[m];$C((D,R)=>{if(clearTimeout(l.current),XC(D))a("done"),t(A.value);else if(JB(D,o)||n6(D,o)){if(R.clearLine(0),r||JB(D,o)&&m!==d.first||n6(D,o)&&m!==d.last){let O=JB(D,o)?-1:1,z=m;do z=(z+O+p.length)%p.length;while(!lBt(p[z]));g(z)}}else if(uir(D)&&!Number.isNaN(Number(R.line))){let O=Number(R.line)-1,z=-1,X=p.findIndex(te=>Td.isSeparator(te)?!1:(z++,z===O)),ee=p[X];ee!=null&&lBt(ee)&&g(X),l.current=setTimeout(()=>{R.clearLine(0)},700)}else if(XWe(D))R.clearLine(0);else if(u){let O=R.line.toLowerCase(),z=p.findIndex(X=>Td.isSeparator(X)||!lBt(X)?!1:X.name.toLowerCase().startsWith(O));z!==-1&&g(z),l.current=setTimeout(()=>{R.clearLine(0)},700)}}),E4(()=>()=>{clearTimeout(l.current)},[]);let b=i.style.message(e.message,s),I;if(i.helpMode!=="never")if(e.instructions){let{pager:D,navigation:R}=e.instructions;I=i.style.help(p.length>n?D:R)}else I=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let C=0,x=t7e({items:p,active:m,renderItem({item:D,isActive:R,index:O}){if(Td.isSeparator(D))return C++,` ${D.separator}`;let z=i.indexMode==="number"?`${O+1-C}. `:"";if(D.disabled){let te=typeof D.disabled=="string"?D.disabled:"(disabled)";return i.style.disabled(`${z}${D.name} ${te}`)}let X=R?i.style.highlight:te=>te,ee=R?i.icon.cursor:" ";return X(`${ee} ${z}${D.name}`)},pageSize:n,loop:r});if(s==="done")return[c,b,i.style.answer(A.short)].filter(Boolean).join(" ");let{description:S}=A;return`${[[c,b].filter(Boolean).join(" "),x," ",S?i.style.description(S):"",I].filter(Boolean).join(`
5553
- `).trimEnd()}${cBt}`});ln();Co();var Ple={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},cZA={[Ple.GENERATION_STARTED]:!1,[Ple.GENERATION_COMPLETED]:!1,[Ple.GENERATION_FAILED]:!0,[Ple.VERIFICATION_FAILED]:!0,[Ple.SDK_PR_CREATED]:!1,[Ple.UPGRADE_APPLIED]:!1,[Ple.MAJOR_VERSION_BUMP]:!1};function l9p(e){return cZA[e]}function u9p(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function p9p(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function f9p(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function d9p(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function m9p(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?Ple.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?Ple.VERIFICATION_FAILED:Ple.GENERATION_FAILED}var lZA="",uZA="FERN_AUTOMATION_EVENTS_ORIGIN",pZA=3e3,GBi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[uZA]??lZA)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),pZA);try{let s={"content-type":"application/json"},a=await Az();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(d9p(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function h9p(){let{fern_run_id:e,github_run_id:t}=Wpe();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.217.0"}}function g9p(){return process.env.FERN_AUTOMATION==="true"}var fZA=3e3,qBi=class{constructor(t,r=GBi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=h9p()}reporter;automationEventApiClient;context;setOrganization(t){this.context={...this.context,org:t}}emit(t,r){let n=this.captureSentryForFailure({event:t,context:this.context,error:r?.error}),i=n==null?t:{...t,attributes:{...t.attributes??{},sentry_event_id:n}};this.capturePostHogEvent({event:i,context:this.context}),this.captureAutomationEventApiEvent(i,this.context)}async flush(){let t;try{await Promise.race([this.automationEventApiClient.shutdown(),new Promise(r=>{t=setTimeout(r,fZA)})])}finally{clearTimeout(t)}}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:u9p(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!l9p(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:p9p(t,r),context:{automation:f9p(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Pt();function WBi(e,t,r){if(t instanceof ec)return;let n=zpe(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new T({message:s,code:n});g9p()?mZA(i,e,n,s,a):dZA(e,o,n,a)}function dZA(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),_Me(r)&&e.captureException(n,{tags:{"error.code":r}})}function mZA(e,t,r,n,i){let o=m9p(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Pt();function s7e(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function HBi({cliName:e,packageVersion:t,isLocal:r}){return s7e()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var KBi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(HBi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new T({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:T.Code.ConfigError});this.sentry=MLt({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[LZe(),wIe(),TIe(),uIe(),SIe()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),LLt()}}captureException(t,r){if(this.sentry!=null)try{let n=r?.tags,i=r?.context,o=n!=null&&Object.keys(n).length>0,s=i!=null&&Object.values(i).some(a=>a!=null);return!o&&!s?this.sentry.captureException(t):BP(a=>{if(o&&a.setTags(n),i!=null)for(let[c,l]of Object.entries(i))l!=null&&a.setContext(c,l);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Pt();var JBi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new T({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:T.Code.InternalError});this.originalWrite=process.stdout.write,process.stdout.write=process.stderr.write.bind(process.stderr),this.redirected=!0}restore(){!this.redirected||this.originalWrite==null||(process.stdout.write=this.originalWrite,this.originalWrite=void 0,this.redirected=!1)}async withRedirect(t){this.redirect();try{return await t()}finally{this.restore()}}};F$();gt();hy();Pt();ln();var mir=class{result=mf.Success;lastFailureMessage=void 0;logImmediately;logPrefix;title;subtasks=[];shouldBufferLogs;bufferedLogs=[];status="notStarted";onResult;instrumentPostHogEventImpl;captureExceptionImpl;emitAutomationTelemetryEventImpl;constructor({logImmediately:t,logPrefix:r,title:n,takeOverTerminal:i,onResult:o,shouldBufferLogs:s,instrumentPostHogEvent:a,captureException:c,emitAutomationTelemetryEvent:l}){this.logImmediately=t,this.logPrefix=r??"",this.title=n,this.takeOverTerminal=i,this.onResult=o,this.shouldBufferLogs=s,this.instrumentPostHogEventImpl=a,this.captureExceptionImpl=c,this.emitAutomationTelemetryEventImpl=l}start(){return this.status="running",this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.status="finished",this.flushLogs(),this.onResult?.(this.getResult()))}isFinished(){return this.status==="finished"}takeOverTerminal;failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),this.finish(),new ec(t??(r instanceof ec?r.failureMessage:this.lastFailureMessage))}failWithoutThrowing(t,r,n){this.result=mf.Failure,!(r instanceof ec)&&(t!=null&&(this.lastFailureMessage=t),oLe({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),WBi(this,r,{...n,message:t}))}getLastFailureMessage(){return this.lastFailureMessage}captureException(t,r){return this.captureExceptionImpl?.(t,r)}emitAutomationTelemetryEvent(t,r){this.emitAutomationTelemetryEventImpl(t,r)}getResult(){return this.result}instrumentPostHogEvent(t){this.instrumentPostHogEventImpl(t)}logAtLevel(t,...r){this.logAtLevelWithOverrides(t,r)}logAtLevelWithOverrides(t,r,n={}){this.log({parts:r,level:t,time:new Date,...n})}log(t){this.bufferedLogs.push({...t,prefix:this.logPrefix}),this.shouldBufferLogs||this.flushLogs()}flushLogs(){this.logImmediately(this.bufferedLogs),this.bufferedLogs=[]}logger=k0(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new AYs({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${le.blackBright(t)} `,takeOverTerminal:this.takeOverTerminal,onResult:this.onResult,shouldBufferLogs:this.shouldBufferLogs,instrumentPostHogEvent:i=>this.instrumentPostHogEventImpl(i),captureException:this.captureExceptionImpl,emitAutomationTelemetryEvent:this.emitAutomationTelemetryEventImpl});return this.subtasks.push(n),n}async runInteractiveTask(t,r){let n=this.addInteractiveTask(t).start();try{await r(n)}catch(o){n.failWithoutThrowing(void 0,o)}finally{n.finish()}let i=n.getResult()===mf.Success;return i||(this.lastFailureMessage=n.getLastFailureMessage()??this.lastFailureMessage),i}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
5553
+ `).trimEnd()}${cBt}`});ln();Co();var Ple={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},cZA={[Ple.GENERATION_STARTED]:!1,[Ple.GENERATION_COMPLETED]:!1,[Ple.GENERATION_FAILED]:!0,[Ple.VERIFICATION_FAILED]:!0,[Ple.SDK_PR_CREATED]:!1,[Ple.UPGRADE_APPLIED]:!1,[Ple.MAJOR_VERSION_BUMP]:!1};function l9p(e){return cZA[e]}function u9p(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function p9p(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function f9p(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function d9p(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function m9p(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?Ple.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?Ple.VERIFICATION_FAILED:Ple.GENERATION_FAILED}var lZA="",uZA="FERN_AUTOMATION_EVENTS_ORIGIN",pZA=3e3,GBi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[uZA]??lZA)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),pZA);try{let s={"content-type":"application/json"},a=await Az();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(d9p(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function h9p(){let{fern_run_id:e,github_run_id:t}=Wpe();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.217.1"}}function g9p(){return process.env.FERN_AUTOMATION==="true"}var fZA=3e3,qBi=class{constructor(t,r=GBi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=h9p()}reporter;automationEventApiClient;context;setOrganization(t){this.context={...this.context,org:t}}emit(t,r){let n=this.captureSentryForFailure({event:t,context:this.context,error:r?.error}),i=n==null?t:{...t,attributes:{...t.attributes??{},sentry_event_id:n}};this.capturePostHogEvent({event:i,context:this.context}),this.captureAutomationEventApiEvent(i,this.context)}async flush(){let t;try{await Promise.race([this.automationEventApiClient.shutdown(),new Promise(r=>{t=setTimeout(r,fZA)})])}finally{clearTimeout(t)}}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:u9p(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!l9p(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:p9p(t,r),context:{automation:f9p(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Pt();function WBi(e,t,r){if(t instanceof ec)return;let n=zpe(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new T({message:s,code:n});g9p()?mZA(i,e,n,s,a):dZA(e,o,n,a)}function dZA(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),_Me(r)&&e.captureException(n,{tags:{"error.code":r}})}function mZA(e,t,r,n,i){let o=m9p(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Pt();function s7e(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function HBi({cliName:e,packageVersion:t,isLocal:r}){return s7e()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var KBi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(HBi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new T({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:T.Code.ConfigError});this.sentry=MLt({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[LZe(),wIe(),TIe(),uIe(),SIe()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),LLt()}}captureException(t,r){if(this.sentry!=null)try{let n=r?.tags,i=r?.context,o=n!=null&&Object.keys(n).length>0,s=i!=null&&Object.values(i).some(a=>a!=null);return!o&&!s?this.sentry.captureException(t):BP(a=>{if(o&&a.setTags(n),i!=null)for(let[c,l]of Object.entries(i))l!=null&&a.setContext(c,l);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Pt();var JBi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new T({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:T.Code.InternalError});this.originalWrite=process.stdout.write,process.stdout.write=process.stderr.write.bind(process.stderr),this.redirected=!0}restore(){!this.redirected||this.originalWrite==null||(process.stdout.write=this.originalWrite,this.originalWrite=void 0,this.redirected=!1)}async withRedirect(t){this.redirect();try{return await t()}finally{this.restore()}}};F$();gt();hy();Pt();ln();var mir=class{result=mf.Success;lastFailureMessage=void 0;logImmediately;logPrefix;title;subtasks=[];shouldBufferLogs;bufferedLogs=[];status="notStarted";onResult;instrumentPostHogEventImpl;captureExceptionImpl;emitAutomationTelemetryEventImpl;constructor({logImmediately:t,logPrefix:r,title:n,takeOverTerminal:i,onResult:o,shouldBufferLogs:s,instrumentPostHogEvent:a,captureException:c,emitAutomationTelemetryEvent:l}){this.logImmediately=t,this.logPrefix=r??"",this.title=n,this.takeOverTerminal=i,this.onResult=o,this.shouldBufferLogs=s,this.instrumentPostHogEventImpl=a,this.captureExceptionImpl=c,this.emitAutomationTelemetryEventImpl=l}start(){return this.status="running",this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.status="finished",this.flushLogs(),this.onResult?.(this.getResult()))}isFinished(){return this.status==="finished"}takeOverTerminal;failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),this.finish(),new ec(t??(r instanceof ec?r.failureMessage:this.lastFailureMessage))}failWithoutThrowing(t,r,n){this.result=mf.Failure,!(r instanceof ec)&&(t!=null&&(this.lastFailureMessage=t),oLe({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),WBi(this,r,{...n,message:t}))}getLastFailureMessage(){return this.lastFailureMessage}captureException(t,r){return this.captureExceptionImpl?.(t,r)}emitAutomationTelemetryEvent(t,r){this.emitAutomationTelemetryEventImpl(t,r)}getResult(){return this.result}instrumentPostHogEvent(t){this.instrumentPostHogEventImpl(t)}logAtLevel(t,...r){this.logAtLevelWithOverrides(t,r)}logAtLevelWithOverrides(t,r,n={}){this.log({parts:r,level:t,time:new Date,...n})}log(t){this.bufferedLogs.push({...t,prefix:this.logPrefix}),this.shouldBufferLogs||this.flushLogs()}flushLogs(){this.logImmediately(this.bufferedLogs),this.bufferedLogs=[]}logger=k0(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new AYs({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${le.blackBright(t)} `,takeOverTerminal:this.takeOverTerminal,onResult:this.onResult,shouldBufferLogs:this.shouldBufferLogs,instrumentPostHogEvent:i=>this.instrumentPostHogEventImpl(i),captureException:this.captureExceptionImpl,emitAutomationTelemetryEvent:this.emitAutomationTelemetryEventImpl});return this.subtasks.push(n),n}async runInteractiveTask(t,r){let n=this.addInteractiveTask(t).start();try{await r(n)}catch(o){n.failWithoutThrowing(void 0,o)}finally{n.finish()}let i=n.getResult()===mf.Success;return i||(this.lastFailureMessage=n.getLastFailureMessage()??this.lastFailureMessage),i}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
5554
5554
  `)}},AYs=class extends mir{name;subtitle;constructor({name:t,subtitle:r,...n}){super(n),this.name=t,this.subtitle=r}start(){return super.start(),this.logAtLevelWithOverrides(Un.Info,["Started."],{omitOnTTY:!0}),this.flushLogs(),this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.result===mf.Success?this.logAtLevelWithOverrides(Un.Info,["Finished."],{omitOnTTY:!0}):this.logAtLevelWithOverrides(Un.Error,["Failed."],{omitOnTTY:!0}),super.finish())}setSubtitle(t){this.subtitle=t}print({spinner:t}){let r=[this.name];return this.subtitle!=null&&r.push(le.dim(this.subtitle)),r.push(...this.subtasks.map(n=>n.print({spinner:t}))),Pj({prefix:this.getIcon({spinner:t}),content:r.join(`
5555
5555
  `)})}printInteractiveTasks({spinner:t}){return this.print({spinner:t})}getIcon({spinner:t}){let r=this.subtasks.length>0;switch(this.status){case"notStarted":return r?le.dim("\u25B8 "):le.dim("\u25E6 ");case"running":return r?le.cyan("\u25BE "):t;case"finished":switch(this.getResult()){case mf.Success:return r?le.green("\u25BE "):le.green("\u2713 ");case mf.Failure:return r?le.red("\u25BE "):le.red("x ")}}}getResult(){if(this.result===mf.Failure)return mf.Failure;for(let t of this.subtasks)if(t.getResult()===mf.Failure)return mf.Failure;return mf.Success}};Pt();var A9p=Ae(hMe(),1);ln();function y9p(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function hZA(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||y9p(e.generatorUpgradeInfo)}async function b9p({cliEnvironment:e,upgradeInfo:t}){if(!hZA(t)||e.packageVersion==t.cliUpgradeInfo?.latestVersion)return;let r=`${le.underline("Upgrades available")}
5556
5556
 
@@ -5559,7 +5559,7 @@ ${r}`}function cBi(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
5559
5559
  Run ${le.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
5560
5560
  Run ${le.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),Ylt(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function yYs({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!y9p(e))return;let i=t??"",o=e.filter(a=>a.isUpgradeAvailable);r!=null&&(o=o.slice(0,r+1));let s=o.sort((a,c)=>a.generatorName.localeCompare(c.generatorName)||a.currentVersion.localeCompare(c.currentVersion));for(let a of s)i+=`
5561
5561
  ${await gZA(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+le.dim(a.currentVersion)+le.reset(" \u2192 ")+le.green(a.latestVersion);return i+=`
5562
- `,n?Ylt(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function gZA(e){let r=await new A9p.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new T({message:`Generator ${e} not found`,code:T.Code.ConfigError});return r.body.displayName}Wn();qde();Pt();var hir=Ae(FA(),1);function pBt(e){let t;return()=>(t??=e.runTask(r=>Ep(r)),t)}function YBi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!E9p(t)||!E9p(r))throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError});try{return t===r?0:yw(t,r)?1:yw(r,t)?-1:0}catch{let n=hir.default.valid(t),i=hir.default.valid(r);if(n!=null&&i!=null)return Math.sign(hir.default.compare(n,i));throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError})}}function E9p(e){if(e==="latest"||hir.default.valid(e)!=null)return!0;try{return gK(e),!0}catch{return!1}}async function XBi({generatorId:e,currentVersion:t,includeMajor:r,channel:n,organization:i,getToken:o,context:s}){if(n!=null)throw new Error(`SDK Gen API generator version discovery does not support the requested upgrade channel "${n}". Remove --channel to use executable index versions; FDR channel metadata is used only when the ${jZt} feature flag is off for this organization.`);let a=Kse();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=bv(e);if(c==null)return s.logger.error(`SDK Gen API cannot discover versions for unsupported generator ${e}. Use a canonical first-party SDK generator name.`),{};let l=await o(),u=await zbs({origin:a,organization:i,token:l,generatorId:e,language:c,currentVersion:t,includeMajor:r});return u.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${u.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:u.compatibleVersion,withheldMajorVersion:u.withheldMajorVersion}}async function AZA({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,l=s!==!0||await gy().catch(()=>{})!=null?pBt(e):void 0;if(a.length===1){let p={type:"singleApi",versions:{}};return await I9p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(d,f,m,g)=>{p.versions[f]==null&&(p.versions[f]={});let A=V_e(m.name);if(A==null){g.logger.debug(`Skipping unknown generator: ${m.name}`);return}let b=await C9p({generatorName:m.name,normalizedGeneratorName:A,cliVersion:e.environment.packageVersion,currentGeneratorVersion:m.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:g});b!=null&&(p.versions[f][m.name]={previousVersion:m.version,latestVersion:b})},generatorFilter:r,groupFilter:n}),p}let u={type:"multiApi",versions:{}};return await I9p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{if(p==null)return;u.versions[p]==null&&(u.versions[p]={}),u.versions[p][d]==null&&(u.versions[p][d]={});let g=V_e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await C9p({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:m});A!=null&&(u.versions[p][d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),u}async function I9p({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await O3({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?eh(n):void 0;for(let l of a.groups)if(!(i!=null&&l.groupName!==i))for(let u of l.generators)c!=null&&u.name!==c||await r(o.workspaceName,l.groupName,u,s)})}))}function v9p(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c=YBi({generatorId:s,candidateVersion:a.latestVersion,currentVersion:a.previousVersion})===1;r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function C9p({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:l}){return n==="latest"?"latest":await yZA({organization:s,generatorName:eh(e),skipFeatureFlagRequest:a})?c==null?void 0:(await XBi({generatorId:eh(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:l})).compatibleVersion:nB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:l})}async function ZBi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await AZA({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[l,u]of Object.entries(c.versions))a.push(...v9p(u,l,t.logger));else a.push(...v9p(c.versions,void 0,t.logger))}return a}async function yZA({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?Aws({organization:e,generatorName:t})??!1:JSt({organization:e,generatorName:t})}gt();Pt();m6r();async function Sye({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await q3e(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Zn(r)}`,code:T.Code.NetworkError})}}var x9p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],$Bi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Un.Info;isLocal;stdoutRedirector=new JBi;jsonMode=!1;linesAfterTasks=[];static async create(t,r,{isLocal:n}){let i=await dqt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new iQt(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new KBi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new qBi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.217.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${le.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new ec(t??(r instanceof ec?r.failureMessage:r!=null?en(r):void 0))}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof ec)&&(oLe({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),WBi(this,r,{...n,message:t}))}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}get isTTY(){return this.ttyAwareLogger.isTTY}writeJsonToStdout(t){this.writeTextToStdout(JSON.stringify(t,null,2)+`
5562
+ `,n?Ylt(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function gZA(e){let r=await new A9p.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new T({message:`Generator ${e} not found`,code:T.Code.ConfigError});return r.body.displayName}Wn();qde();Pt();var hir=Ae(FA(),1);function pBt(e){let t;return()=>(t??=e.runTask(r=>Ep(r)),t)}function YBi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!E9p(t)||!E9p(r))throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError});try{return t===r?0:yw(t,r)?1:yw(r,t)?-1:0}catch{let n=hir.default.valid(t),i=hir.default.valid(r);if(n!=null&&i!=null)return Math.sign(hir.default.compare(n,i));throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError})}}function E9p(e){if(e==="latest"||hir.default.valid(e)!=null)return!0;try{return gK(e),!0}catch{return!1}}async function XBi({generatorId:e,currentVersion:t,includeMajor:r,channel:n,organization:i,getToken:o,context:s}){if(n!=null)throw new Error(`SDK Gen API generator version discovery does not support the requested upgrade channel "${n}". Remove --channel to use executable index versions; FDR channel metadata is used only when the ${jZt} feature flag is off for this organization.`);let a=Kse();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=bv(e);if(c==null)return s.logger.error(`SDK Gen API cannot discover versions for unsupported generator ${e}. Use a canonical first-party SDK generator name.`),{};let l=await o(),u=await zbs({origin:a,organization:i,token:l,generatorId:e,language:c,currentVersion:t,includeMajor:r});return u.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${u.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:u.compatibleVersion,withheldMajorVersion:u.withheldMajorVersion}}async function AZA({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,l=s!==!0||await gy().catch(()=>{})!=null?pBt(e):void 0;if(a.length===1){let p={type:"singleApi",versions:{}};return await I9p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(d,f,m,g)=>{p.versions[f]==null&&(p.versions[f]={});let A=V_e(m.name);if(A==null){g.logger.debug(`Skipping unknown generator: ${m.name}`);return}let b=await C9p({generatorName:m.name,normalizedGeneratorName:A,cliVersion:e.environment.packageVersion,currentGeneratorVersion:m.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:g});b!=null&&(p.versions[f][m.name]={previousVersion:m.version,latestVersion:b})},generatorFilter:r,groupFilter:n}),p}let u={type:"multiApi",versions:{}};return await I9p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{if(p==null)return;u.versions[p]==null&&(u.versions[p]={}),u.versions[p][d]==null&&(u.versions[p][d]={});let g=V_e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await C9p({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:m});A!=null&&(u.versions[p][d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),u}async function I9p({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await O3({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?eh(n):void 0;for(let l of a.groups)if(!(i!=null&&l.groupName!==i))for(let u of l.generators)c!=null&&u.name!==c||await r(o.workspaceName,l.groupName,u,s)})}))}function v9p(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c=YBi({generatorId:s,candidateVersion:a.latestVersion,currentVersion:a.previousVersion})===1;r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function C9p({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:l}){return n==="latest"?"latest":await yZA({organization:s,generatorName:eh(e),skipFeatureFlagRequest:a})?c==null?void 0:(await XBi({generatorId:eh(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:l})).compatibleVersion:nB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:l})}async function ZBi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await AZA({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[l,u]of Object.entries(c.versions))a.push(...v9p(u,l,t.logger));else a.push(...v9p(c.versions,void 0,t.logger))}return a}async function yZA({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?Aws({organization:e,generatorName:t})??!1:JSt({organization:e,generatorName:t})}gt();Pt();m6r();async function Sye({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await q3e(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Zn(r)}`,code:T.Code.NetworkError})}}var x9p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],$Bi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Un.Info;isLocal;stdoutRedirector=new JBi;jsonMode=!1;linesAfterTasks=[];static async create(t,r,{isLocal:n}){let i=await dqt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new iQt(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new KBi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new qBi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.217.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${le.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new ec(t??(r instanceof ec?r.failureMessage:r!=null?en(r):void 0))}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof ec)&&(oLe({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),WBi(this,r,{...n,message:t}))}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}get isTTY(){return this.ttyAwareLogger.isTTY}writeJsonToStdout(t){this.writeTextToStdout(JSON.stringify(t,null,2)+`
5563
5563
  `)}writeTextToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(t),this.jsonMode&&this.stdoutRedirector.redirect()}async withRealStdout(t){this.stdoutRedirector.restore();try{return await t()}finally{this.jsonMode&&this.stdoutRedirector.redirect()}}logAfterTasks(t){this.isTTY?this.linesAfterTasks.push(t):this.logger.info(t)}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish();for(let r of this.linesAfterTasks)process.stdout.write(`${r}
5564
5564
  `);try{await Promise.all([this.posthogManager.flush(),pHo()])}catch{}await this.sentryClient.flush(),await this.automationTelemetryManager.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable({skipFeatureFlagRequest:!0}),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await b9p({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
5565
5565
  `)||(r+=`