fern-api 3.42.4 → 3.43.0

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
@@ -1146,7 +1146,7 @@ ${bC_.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&Cjc(th
1146
1146
  `+d_n.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?d_n.default.cyan(EC_(t,this.opt.mask)):d_n.default.italic(d_n.default.dim("[hidden]")):this.opt.mask?EC_(t,this.opt.mask):d_n.default.italic(d_n.default.dim("[input is hidden] "))}getSpinningValue(t){return this.getMaskedValue(t)}filterInput(t){return t||(this.opt.default==null?"":this.opt.default)}onEnd(t){this.status="answered",this.answer=t.value,this.render(),this.screen.done(),this.done(t.value)}onError(t){this.render(t.isValid)}onKeypress(){this.opt.default&&=void 0,this.render()}};var l7o=ce(KT(),1);var Eq_=ce(p0c(),1),s7o=require("child_process"),tkn=require("fs"),u7o=ce(require("path"),1),Sq_=ce(require("os"),1),Mq_=require("crypto"),X0c=ce(jq_(),1);var n7o=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var BWa=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var a7o=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var o7o=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function c7o(e="",t,r){let i=new Z0c(e,r);i.runAsync((n,a)=>{if(n)setImmediate(t,n,void 0);else try{i.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function wq_(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function FKM(e){let t=[],r="";for(let i=0;i<e.length;i++){let n=e.charAt(i);i>0&&n===" "&&e[i-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${n}`}return r.length>0&&t.push(r),t}var Z0c=class{text="";tempFile;editor;lastExitStatus=0;fileOptions={};get temp_file(){return console.log("DEPRECATED: temp_file. Use tempFile moving forward."),this.tempFile}get last_exit_status(){return console.log("DEPRECATED: last_exit_status. Use lastExitStatus moving forward."),this.lastExitStatus}constructor(t="",r){this.text=t,r&&(this.fileOptions=r),this.determineEditor(),this.createTemporaryFile()}run(){return this.launchEditor(),this.readTemporaryFile(),this.text}runAsync(t){try{this.launchEditorAsync(()=>{try{this.readTemporaryFile(),setImmediate(t,void 0,this.text)}catch(r){setImmediate(t,r,void 0)}})}catch(r){setImmediate(t,r,void 0)}}cleanup(){this.removeTemporaryFile()}determineEditor(){let t=process.env.VISUAL?process.env.VISUAL:process.env.EDITOR?process.env.EDITOR:process.platform.startsWith("win")?"notepad":"vim",r=FKM(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??Sq_.default.tmpdir(),r=(0,Mq_.randomUUID)(),i=wq_(this.fileOptions.prefix),n=wq_(this.fileOptions.postfix),a=`${i}${r}${n}`,o=u7o.default.resolve(t,a),c=u7o.default.resolve(t)+u7o.default.sep;if(!o.startsWith(c))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=o;let d={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(d.mode=this.fileOptions.mode),(0,tkn.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new n7o(t)}}readTemporaryFile(){try{let t=(0,tkn.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,Eq_.detect)(t)??"utf8";X0c.default.encodingExists(r)||(r="utf8"),this.text=X0c.default.decode(t,r)}}catch(t){throw new a7o(t)}}removeTemporaryFile(){try{(0,tkn.unlinkSync)(this.tempFile)}catch(t){throw new o7o(t)}}launchEditor(){try{let t=(0,s7o.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new BWa(t)}}launchEditorAsync(t){try{(0,s7o.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new BWa(r)}}};var Dq_=ce($be(),1);var IWa=class extends JT{_run(t){this.done=t,this.editorResult=new Dq_.Subject;let r=C4(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?l7o.default.dim("Received"):l7o.default.dim("Press <enter> to launch your preferred editor."),t&&(r=l7o.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),c7o(this.currentText,this.endExternalEditor.bind(this),{postfix:this.opt.postfix??".txt"})}endExternalEditor(t,r){this.rl.resume(),t?this.editorResult.error(t):this.editorResult.next(r)}onEnd(t){this.editorResult.unsubscribe(),this.lineSubscription.unsubscribe(),this.answer=t.value,this.status="answered",this.render(),this.screen.done(),this.done(this.answer)}onError(t){this.render(t.isValid)}};var Tq_=require("stream");var Cq_=ce(require("readline"),1),qq_=ce(Iq_(),1),y_n=class{constructor(t){this.rl||=Cq_.default.createInterface(UKM(t)),this.rl.resume(),this.onForceClose=this.onForceClose.bind(this),process.on("exit",this.onForceClose),this.rl.on("SIGINT",this.onForceClose)}onForceClose(){this.close(),process.kill(process.pid,"SIGINT"),console.log("")}close(){this.rl.removeListener("SIGINT",this.onForceClose),process.removeListener("exit",this.onForceClose),this.rl.output.unmute(),this.activePrompt&&typeof this.activePrompt.close=="function"&&this.activePrompt.close(),this.rl.output.end(),this.rl.pause(),this.rl.close()}};function UKM(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new qq_.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var CWa=class extends y_n{constructor(t={}){super(t),this.log=new Tq_.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return hWa(this.rl,this.bottomBar.split(`
1147
1147
  `).length),this}updateBottomBar(t){return hWa(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+`
1148
1148
  `}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&&CHo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var WO=ce($be(),1),Nq_=ce(z8a(),1);var f7o=ce($be(),1),Rq_=ce(z8a(),1),d7o=function(e,t,r){return typeof e[t]!="function"?(0,f7o.of)(e):(0,f7o.from)((0,Rq_.default)(e[t])(r).then(i=>(e[t]=i,e)))};var zq_={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,o)=>{n==="__proto__"||n==="constructor"||(a===o.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((o,c)=>o!=null?o[c]:o,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},rkn=class extends y_n{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let i;return Array.isArray(t)?i=(0,WO.from)(t):(0,WO.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,WO.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,WO.from)([t]),this.process=i.pipe((0,WO.concatMap)(this.processQuestion.bind(this)),(0,WO.publish)()),this.process.connect(),this.process.pipe((0,WO.reduce)((n,a)=>(zq_.set(n,a.name,a.answer),n),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,WO.defer)(()=>(0,WO.of)(t).pipe((0,WO.concatMap)(this.setDefaultType.bind(this)),(0,WO.concatMap)(this.filterIfRunnable.bind(this)),(0,WO.concatMap)(()=>d7o(t,"message",this.answers)),(0,WO.concatMap)(()=>d7o(t,"default",this.answers)),(0,WO.concatMap)(()=>d7o(t,"choices",this.answers)),(0,WO.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,WO.defer)(()=>(0,WO.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,WO.defer)(()=>(0,WO.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&zq_.get(this.answers,t.name)!==void 0)return WO.EMPTY;if(t.when===!1)return WO.EMPTY;if(typeof t.when!="function")return(0,WO.of)(t);let{answers:r}=this;return(0,WO.defer)(()=>(0,WO.from)((0,Nq_.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,WO.filter)(i=>i!=null)))}};function Fq_(e){let t=function(r,i){let n;try{n=new rkn(t.prompts,e)}catch(o){return Promise.reject(o)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",bWa),this.registerPrompt("input",f_n),this.registerPrompt("number",vWa),this.registerPrompt("confirm",gWa),this.registerPrompt("rawlist",OWa),this.registerPrompt("expand",AWa),this.registerPrompt("checkbox",mWa),this.registerPrompt("password",PWa),this.registerPrompt("editor",IWa)},t.restoreDefaultPrompts(),t}var ewc=Fq_();function VKM(e,t){ewc.registerPrompt(e,t)}function WKM(){ewc.restoreDefaultPrompts()}var GKM={prompt:ewc,ui:{BottomBar:CWa,Prompt:rkn},createPromptModule:Fq_,registerPrompt:VKM,restoreDefaultPrompts:WKM,Separator:o$},p7o=GKM;var ikn=require("path");function Uq_(){let e=HKM();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function HKM(e=process.argv[1]?(0,ikn.dirname)(process.argv[1]):process.cwd(),t=ikn.sep==="\\"){let r=t?Qq_(e):e;return i=>{if(!i)return;let n=t?Qq_(i):i,{dir:a,base:o,ext:c}=ikn.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,-1*c.length));let d=decodeURIComponent(o);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let u=a.slice(r.length+1).replace(/\//g,".");return u?`${u}:${d}`:d}return d}}function Qq_(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var twc=e=>{if("flags"in e){let t=Lq_(e.flags),r=Vq_(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,Wq_(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,xKM(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function xKM(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 Lq_=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,b_n(r)]).filter(([,t])=>t!==void 0)),Vq_=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map(r=>{let i=t[r].metadata?.payload;return[r,i?Wq_(i):void 0]}))};var b_n=e=>e===void 0?void 0:e.variant??e.enabled,Wq_=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var _7o="0123456789abcdef",h7o=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,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/256,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}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 i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=_7o.charAt(this.bytes[r]>>>4),t+=_7o.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+=_7o.charAt(this.bytes[r]>>>4),t+=_7o.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 i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},rwc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??KKM()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}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 h7o.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,h7o.ofInner(t)}},KKM=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),Gq_,zJt=()=>JKM().toString(),JKM=()=>(Gq_||(Gq_=new rwc)).generate();var $KM=["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","pinterest","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"],Hq_=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return $KM.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var s$=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",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.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.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e})({});var XKM=Array.isArray,xq_=Object.prototype,lm9=xq_.hasOwnProperty,iwc=xq_.toString,Kq_=XKM||function(e){return iwc.call(e)==="[object Array]"};var nkn=e=>e===void 0,qWa=e=>iwc.call(e)=="[object String]",Jq_=e=>qWa(e)&&e.trim().length===0;var $q_=e=>iwc.call(e)=="[object Number]";var nwc=e=>e instanceof Error;function ZKM(e,t){try{return e instanceof t}catch{return!1}}function TWa(e){return e===null||typeof e!="object"}function v_n(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function Yq_(e){return v_n(e,"ErrorEvent")}function y7o(e){return!nkn(Event)&&ZKM(e,Event)}function Xq_(e){return v_n(e,"Object")}function RWa(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),$q_(e)?e>r?(i.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),RWa(n||r,t,r,i))}var kKM=864e5,b7o=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=RWa(t.bucketSize,0,100,t._logger),this._refillRate=RWa(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=RWa(t.refillInterval,0,kKM,t._logger)}_applyRefill(t,r){let i=r-t.lastAccess,n=Math.floor(i/this._refillInterval);if(n>0){let a=n*this._refillRate;t.tokens=Math.min(t.tokens+a,this._bucketSize),t.lastAccess=t.lastAccess+n*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),i=String(t),n=this._buckets[i];return n?this._applyRefill(n,r):(n={tokens:this._bucketSize,lastAccess:r},this._buckets[i]=n),n.tokens===0?!0:(n.tokens--,n.tokens===0&&this._onBucketRateLimited?.(t),n.tokens===0)}stop(){this._buckets={}}};var v7o=class{add(t){let r=zJt();return this.promiseByIds[r]=t,t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds),r=t.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function eJM(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var Zq_=(e,t,r)=>{function i(a,...o){t(()=>{let c=r[a];c(e,...o)})}return{info:(...a)=>{i("log",...a)},warn:(...a)=>{i("warn",...a)},error:(...a)=>{i("error",...a)},critical:(...a)=>{r.error(e,...a)},createLogger:a=>Zq_(`${e} ${a}`,t,r)}},tJM=e=>e();function kq_(e,t=tJM){return Zq_(e,t,eJM())}var okn="Mobile",O7o="iOS",akn="Android",e1_="Tablet",mm9=akn+" "+e1_;var rJM="Apple",Pm9=rJM+" Watch",t1_="Safari",A7o="BlackBerry",r1_="Samsung",iJM=r1_+"Browser",nJM=r1_+" Internet",m7o="Chrome",aJM=m7o+" OS",oJM=m7o+" "+O7o,i1_="Internet Explorer",uJM=i1_+" "+okn,owc="Opera",jm9=owc+" Mini",n1_="Edge",sJM="Microsoft "+n1_,uwc="Firefox",cJM=uwc+" "+O7o,swc="Nintendo",cwc="PlayStation",g7o="Xbox",lJM=akn+" "+okn,fJM=okn+" "+t1_,zWa="Windows",dJM=zWa+" Phone";var a1_="Generic",wm9=a1_+" "+okn.toLowerCase(),Em9=a1_+" "+e1_.toLowerCase(),pJM="Konqueror",AG="(\\d+(\\.\\d+)?)",awc=new RegExp("Version/"+AG),Sm9=new RegExp(g7o,"i"),Mm9=new RegExp(cwc+" \\w+","i"),Dm9=new RegExp(swc+" \\w+","i"),_JM=new RegExp(A7o+"|PlayBook|BB10","i"),hJM={"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 Bm9={[uJM]:[new RegExp("rv:"+AG)],[sJM]:[new RegExp(n1_+"?\\/"+AG)],[m7o]:[new RegExp("("+m7o+"|CrMo)\\/"+AG)],[oJM]:[new RegExp("CriOS\\/"+AG)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+AG)],[t1_]:[awc],[fJM]:[awc],[owc]:[new RegExp("("+owc+"|OPR)\\/"+AG)],[uwc]:[new RegExp(uwc+"\\/"+AG)],[cJM]:[new RegExp("FxiOS\\/"+AG)],[pJM]:[new RegExp("Konqueror[:/]?"+AG,"i")],[A7o]:[new RegExp(A7o+" "+AG),awc],[lJM]:[new RegExp("android\\s"+AG,"i")],[nJM]:[new RegExp(iJM+"\\/"+AG)],[i1_]:[new RegExp("(rv:|MSIE )"+AG)],Mozilla:[new RegExp("rv:"+AG)]};var Im9=[[new RegExp(g7o+"; "+g7o+" (.*?)[);]","i"),e=>[g7o,e&&e[1]||""]],[new RegExp(swc,"i"),[swc,""]],[new RegExp(cwc,"i"),[cwc,""]],[_JM,[A7o,""]],[new RegExp(zWa,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[dJM,""];if(new RegExp(okn).test(t)&&!/IEMobile\b/.test(t))return[zWa+" "+okn,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=hJM[i]||"";return/arm/i.test(t)&&(n="RT"),[zWa,n]}return[zWa,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[O7o,t.join(".")]}return[O7o,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=nkn(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+akn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+akn+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[akn,t.join(".")]}return[akn,""]}],[/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/,[aJM,""]],[/Linux|debian/i,["Linux",""]]];var o1_="utf8";function u1_(e,t){if(!e||typeof e!="string"||yJM(e))throw new Error(t)}function yJM(e){return e.trim().length===0}function s1_(e){return e?.replace(/\/+$/,"")}async function c1_(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function P7o(){return new Date().toISOString()}function g_n(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var l1_=e=>e instanceof Error;function lwc(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var j7o=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(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};function f1_(){return"CompressionStream"in globalThis}async function fwc(e,t=!0){try{let i=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(i).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var ukn=class extends Error{constructor(t,r){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},NWa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function d1_(e){if(e instanceof ukn){let t="";try{t=await e.text}catch{}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 dwc(e){return typeof e=="object"&&(e instanceof ukn||e instanceof NWa)}function p1_(e){return typeof e=="object"&&e instanceof ukn&&e.status===413}var FWa=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new v7o,this._events=new j7o,this._isInitialized=!1,u1_(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=s1_(r.host||"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:dwc},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=r.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this.evaluationEnvironments=r?.evaluationEnvironments,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=kq_("[PostHog]",this.logMsgIfDebug.bind(this)),this.disableCompression=!f1_()||(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(s$.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(s$.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(s$.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>this._logger.info(i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(t,r,i){let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",n,i)}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}async captureStatelessImmediate(t,r,i,n){let a=this.buildPayload({distinct_id:t,event:r,properties:i});await this.sendImmediate("capture",a,n)}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}async aliasStatelessImmediate(t,r,i,n){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,n)}groupIdentifyStateless(t,r,i,n,a,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...o||{}}});this.enqueue("capture",c,n)})}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`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this._logger.error("Remote config could not be loaded",n),this._events.emit("error",n)})}async getFlags(t,r={},i={},n={},a={},o=!0){await this._initPromise;let c=o?"&config=true":"",d=`${this.host}/flags/?v=2${c}`,s={token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a};this.evaluationEnvironments&&this.evaluationEnvironments.length>0&&(s.evaluation_environments=this.evaluationEnvironments);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(s)};return this._logger.info("Flags URL",d),this.fetchWithRetry(d,u,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(f=>f.json()).then(f=>twc(f)).catch(f=>{this._events.emit("error",f)})}async getFeatureFlagStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let d=b_n(c.response);return d===void 0&&(d=!1),{response:d,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId,evaluatedAt:c.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,o,[t]);if(!c)return;let d=c[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,o);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),o&&(c.flag_keys_to_evaluate=o);let d=await this.getFlags(t,r,i,n,c);if(d!==void 0)return d.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"),d.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:d?.requestId}):d}async getSurveysStateless(){if(await this._initPromise,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"}},n=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this._logger.error(c),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}))?.surveys;return n&&this._logger.info("Surveys fetched from API: ",JSON.stringify(n)),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(s$.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(s$.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(s$.Props,this.props)})}enqueue(t,r,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 n=this.prepareMessage(t,r,i),a=this.getPersistedProperty(s$.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(s$.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=g_n(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,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 n={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:P7o()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=`${this.host}/batch/`,c=this.disableCompression?null:await fwc(a,this.isDebug),d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||a};try{await this.fetchWithRetry(o,d)}catch(s){this._events.emit("error",s)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:P7o(),uuid:i?.uuid?i.uuid:zJt()};return(i?.disableGeoip??this.disableGeoip)&&(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.flush().catch(async t=>{await d1_(t)})}async flush(){let t=lwc([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),lwc([t]).then(()=>{this.flushPromise===t&&(this.flushPromise=null)}),t}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(s$.Queue)||[];if(!t.length)return;let r=[],i=t.length;for(;t.length>0&&r.length<i;){let n=t.slice(0,this.maxBatchSize),a=n.map(_=>_.message),o=()=>{let h=(this.getPersistedProperty(s$.Queue)||[]).slice(n.length);this.setPersistedProperty(s$.Queue,h),t=h},c={api_key:this.apiKey,batch:a,sent_at:P7o()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await fwc(d,this.isDebug),f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:_=>p1_(_)?!1:dwc(_)};try{await this.fetchWithRetry(s,f,p)}catch(_){if(p1_(_)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw _ instanceof NWa||o(),this._events.emit("error",_),_}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){AbortSignal.timeout??=function(c){let d=new AbortController;return setTimeout(()=>d.abort(),c),d.signal};let a=r.body?r.body:"",o=-1;try{o=a instanceof Blob?a.size:Buffer.byteLength(a,o1_)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await c1_(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new NWa(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new ukn(c,o);return c},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(s$.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!dwc(n))throw n;await d1_(n)}};return Promise.race([new Promise((n,a)=>{g_n(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),i()])}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 c$={};Zt(c$,{DOMExceptionCoercer:()=>_wc,ErrorCoercer:()=>hwc,ErrorEventCoercer:()=>ywc,ErrorPropertiesBuilder:()=>pwc,EventCoercer:()=>gwc,ObjectCoercer:()=>vwc,PrimitiveCoercer:()=>Owc,PromiseRejectionEventCoercer:()=>Awc,ReduceableCache:()=>mwc,StringCoercer:()=>bwc,chromeStackLineParser:()=>y1_,createStackParser:()=>BJM,geckoStackLineParser:()=>v1_,nodeStackLineParser:()=>m1_,opera10StackLineParser:()=>g1_,opera11StackLineParser:()=>O1_,reverseAndStripFrames:()=>w1_,winjsStackLineParser:()=>b1_});var w7o,_1_,E7o;function h1_(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return E7o&&r.length===_1_||(_1_=r.length,E7o=r.reduce((i,n)=>{w7o||(w7o={});let a=w7o[n];if(a)i[a[0]]=a[1];else{let o=e(n);for(let c=o.length-1;c>=0;c--){let s=o[c]?.filename,u=t[n];if(s&&u){i[s]=u,w7o[n]=[s,u];break}}}return i},{})),E7o}var bJM=4,pwc=class{constructor(t,r,i=[]){this.coercers=t,this.stackParser=r,this.modifiers=i}buildFromUnknown(t,r={}){let n=r&&r.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(n,r,0).apply(t),c=this.buildParsingContext(),d=this.parseStacktrace(o,c);return{$exception_list:this.convertToExceptionList(d,n),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&Kq_(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 i;t.cause!=null&&(i=this.parseStacktrace(t.cause,r));let n;return t.stack!=""&&t.stack!=null&&(n=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?1:0),r.chunkIdMap)),{...t,cause:i,stack:n}}applyChunkIds(t,r){return t.map(i=>(i.filename&&r&&(i.chunk_id=r[i.filename]),i))}applyCoercers(t,r){for(let i of this.coercers)if(i.match(t))return i.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let i of this.modifiers)r=await i(r);return r}convertToExceptionList(t,r){let i={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(i.stacktrace={type:"raw",frames:t.stack});let n=[i];return t.cause!=null&&n.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),n}buildParsingContext(){return{chunkIdMap:h1_(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=bJM){let d=this.buildCoercingContext(t,r,c);return this.applyCoercers(o,d)}};return{...r,syntheticException:i==0?r.syntheticException:void 0,mechanism:t,apply:o=>n(o,i),next:o=>n(o,i+1)}}};var T4="?";function NJt(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?T4:r,in_app:!0};return nkn(i)||(a.lineno=i),nkn(n)||(a.colno=n),a}var S7o=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:T4,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var vJM=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,gJM=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,OJM=/\((\S*)(?::(\d+))(?::(\d+))\)/,y1_=(e,t)=>{let r=vJM.exec(e);if(r){let[,n,a,o]=r;return NJt(t,n,T4,+a,+o)}let i=gJM.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=OJM.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=S7o(i[1]||T4,i[2]);return NJt(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var AJM=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,b1_=(e,t)=>{let r=AJM.exec(e);return r?NJt(t,r[2],r[1]||T4,+r[3],r[4]?+r[4]:void 0):void 0};var mJM=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,PJM=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,v1_=(e,t)=>{let r=mJM.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=PJM.exec(r[3]);o&&(r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]="")}let n=r[3],a=r[1]||T4;return[a,n]=S7o(a,n),NJt(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var jJM=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,g1_=(e,t)=>{let r=jJM.exec(e);return r?NJt(t,r[2],r[3]||T4,+r[1]):void 0},wJM=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,O1_=(e,t)=>{let r=wJM.exec(e);return r?NJt(t,r[5],r[3]||r[4]||T4,+r[1],+r[2]):void 0};var EJM=/^\s*[-]{4,}$/,SJM=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,m1_=(e,t)=>{let r=e.match(SJM);if(r){let i,n,a,o,c;if(r[1]){a=r[1];let u=a.lastIndexOf(".");if(a[u-1]==="."&&u--,u>0){i=a.slice(0,u),n=a.slice(u+1);let f=i.indexOf(".Module");f>0&&(a=a.slice(f+1),i=i.slice(0,f))}o=void 0}n&&(o=i,c=n),n==="<anonymous>"&&(c=void 0,a=void 0),a===void 0&&(c=c||T4,a=o?`${o}.${c}`:c);let d=r[2]?.startsWith("file://")?r[2].slice(7):r[2],s=r[5]==="native";return d?.match(/\/[A-Z]:/)&&(d=d.slice(1)),!d&&r[5]&&!s&&(d=r[5]),{filename:d?decodeURI(d):void 0,module:void 0,function:a,lineno:A1_(r[3]),colno:A1_(r[4]),in_app:MJM(d||"",s),platform:t}}if(e.match(EJM))return{filename:e,platform:t}};function MJM(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 A1_(e){return parseInt(e||"",10)||void 0}var P1_=/\(error: (.*)\)/,j1_=50;function w1_(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,j1_).map(r=>({...r,filename:r.filename||DJM(t).filename,function:r.function||T4}))}function DJM(e){return e[e.length-1]||{}}function BJM(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
1149
- `);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=P1_.test(c)?c.replace(P1_,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=j1_)break}}return w1_(n)}}var _wc=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=qWa(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?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 v_n(t,"DOMException")}isDOMError(t){return v_n(t,"DOMError")}};var hwc=class{match(t){return nwc(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var ywc=class{constructor(){}match(t){return Yq_(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var IJM=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,bwc=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(IJM);return n&&(r=n[1],i=n[2]),[r,i]}};var E1_=["fatal","error","warning","log","info","debug"];function M7o(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var vwc=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return y7o(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=M7o(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return qWa(t)&&!Jq_(t)&&E1_.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(l1_(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var gwc=class{match(t){return y7o(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${M7o(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Owc=class{match(t){return TWa(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Awc=class{match(t){return v_n(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return TWa(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(TWa(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var mwc=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 D1_=require("fs"),B1_=require("readline"),D7o=new c$.ReduceableCache(25),I1_=new c$.ReduceableCache(20),Pwc=7,CJM=1e3,qJM=1e4;async function C1_(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||NJM(o)||FJM(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(I1_.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=UJM(a);if(o.every(d=>QJM(n,d)))continue;let c=LJM(D7o,n,{});i.push(TJM(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&RJM(e,D7o),D7o.reduce(),e}function TJM(e,t,r){return new Promise(i=>{let n=(0,D1_.createReadStream)(e),a=(0,B1_.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],f=s[1];function p(){I1_.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=VJM(_,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],f=h[1]}})})}function RJM(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;zJM(r.lineno,r,i)}}function zJM(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=q1_(e);n<e;n++){let a=r[n];if(a===void 0)return void S1_(t);t.pre_context.push(a)}if(r[e]===void 0)return void S1_(t);t.context_line=r[e];let i=T1_(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function S1_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function NJM(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function FJM(e){return e.lineno!==void 0&&e.lineno>qJM||e.colno!==void 0&&e.colno>CJM}function QJM(e,t){let r=D7o.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function UJM(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=M1_(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+Pwc:(n.push(i),i=M1_(a)),t++}return n}function M1_(e){return[q1_(e),T1_(e)]}function q1_(e){return Math.max(1,e-Pwc)}function T1_(e){return e+Pwc}function LJM(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function VJM(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}function WJM(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t(i))},{_posthogErrorHandler:!0})}function R1_(e,t){globalThis.process?.on("uncaughtException",WJM(e,t))}function z1_(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var GJM=2e3,OFi=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new b7o({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||zJt(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(R1_(this.onException.bind(this),this.onFatalError.bind(this)),z1_(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)})())}async onFatalError(t){console.error(t),await this.client.shutdown(GJM),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var N1_="5.17.4";async function F1_(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("")}var HJM=6e4,xJM=1152921504606847e3,KJM=["is_not"],skn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},f0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},FJt=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},B7o=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof FJt||d instanceof f0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,_&&(c[f.key]=_)}catch(p){p instanceof FJt||p instanceof f0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new f0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new f0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new f0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new f0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new f0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new f0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new f0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new f0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new f0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}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,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof FJt)throw u;if(u instanceof f0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new f0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?W1_(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):V1_(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await Q1_(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await Q1_(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}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),!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 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}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(HJM,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}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.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new skn(`Your project key or personal API 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.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new skn(`Your personal API 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 personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new skn(`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 i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof skn&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=g_n(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function Q1_(e,t,r=""){let i=await F1_(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/xJM}function V1_(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new f0("Operator is_not_set is not supported")}else throw new f0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!KJM.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return U1_(String(n))&&String(o).match(String(n))!==null;case"not_regex":return U1_(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s==null||o==null?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new f0("Date operations cannot be performed on boolean values");let s=$JM(String(n));if(s==null&&(s=L1_(n)),s==null)throw new f0(`Invalid date: ${n}`);let u=L1_(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new f0(`Unknown operator: ${a}`)}}function JJM(e,t){if(!(e in t))throw new FJt(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function W1_(e,t,r,i=!1){let n=String(e.value);JJM(n,r);let a=r[n];return G1_(a,t,r,i)}function G1_(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let d=G1_(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof FJt)throw d;if(d instanceof f0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new f0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=W1_(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=V1_(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof FJt)throw d;if(d instanceof f0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new f0("can't match cohort without a given cohort property value");return n==="AND"}function U1_(e){try{return new RegExp(e),!0}catch{return!1}}function L1_(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 f0(`${e} is in an invalid date format`)}throw new f0(`The date provided ${e} must be a string, number, or date object`)}function $JM(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var I7o=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var YJM=100,H1_=3e4,XJM=5e4,C7o=class extends FWa{constructor(t,r={}){if(super(t,r),this._memoryStorage=new I7o,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,YJM):H1_,r.personalApiKey){if(r.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.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new B7o({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider}))}this.errorTracking=new OFi(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||XJM}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)}getLibraryVersion(){return N1_}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=H1_){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let f=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=f!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,f=b_n(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${f}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:f,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:f,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),f}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let f;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,f=y.payload)}catch(y){if(y instanceof FJt||y instanceof f0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(f!==void 0)&&!c&&(f=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),f}async getRemoteConfigPayload(t){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 i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},_=!0;if(u&&(f=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:f,featureFlagPayloads:p}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=g_n(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(Xq_(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(OFi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(OFi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=zJt(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[O,A]of Object.entries(y))b[`$feature/${O}`]=A;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&Hq_(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var x1_=require("async_hooks"),q7o=class{constructor(){this.storage=new x1_.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var K1_="posthog-node";function ZJM(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[jwc.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],p=f.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var jwc=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=K1_,this.name=K1_,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(ZJM(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};OFi.errorPropertiesBuilder=new c$.ErrorPropertiesBuilder([new c$.EventCoercer,new c$.ErrorCoercer,new c$.ObjectCoercer,new c$.StringCoercer,new c$.PrimitiveCoercer],c$.createStackParser("node:javascript",c$.nodeStackLineParser),[Uq_(),C1_]);var ckn=class extends C7o{getLibraryId(){return"posthog-node"}initializeContext(){return new q7o}};var T7o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new ckn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.42.4",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var QWa=class{async sendEvent(){}async identify(){}async flush(){}};var lkn=require("fs/promises"),X1_=require("os"),Z1_=require("path");var J1_=ce(require("crypto")),z7o=new Uint8Array(256),R7o=z7o.length;function wwc(){return R7o>z7o.length-16&&(J1_.default.randomFillSync(z7o),R7o=0),z7o.slice(R7o,R7o+=16)}var R4=[];for(let e=0;e<256;++e)R4.push((e+256).toString(16).slice(1));function $1_(e,t=0){return R4[e[t+0]]+R4[e[t+1]]+R4[e[t+2]]+R4[e[t+3]]+"-"+R4[e[t+4]]+R4[e[t+5]]+"-"+R4[e[t+6]]+R4[e[t+7]]+"-"+R4[e[t+8]]+R4[e[t+9]]+"-"+R4[e[t+10]]+R4[e[t+11]]+R4[e[t+12]]+R4[e[t+13]]+R4[e[t+14]]+R4[e[t+15]]}var Y1_=ce(require("crypto")),Ewc={randomUUID:Y1_.default.randomUUID};function kJM(e,t,r){if(Ewc.randomUUID&&!t&&!e)return Ewc.randomUUID();e=e||{};let i=e.random||(e.rng||wwc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return $1_(i)}var Xbe=kJM;var e$M="id",t$M=".fern",UWa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new ckn(r),this.userId=t==null?void 0:vgc(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:"3.42.4",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}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 w4({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=Ct(Sr.of((0,X1_.homedir)()),He.of(t$M),He.of(e$M));await mi(t)||(await(0,lkn.mkdir)((0,Z1_.dirname)(t),{recursive:!0}),await(0,lkn.writeFile)(t,Xbe())),this.persistedDistinctId=(await(0,lkn.readFile)(t)).toString()}return this.persistedDistinctId}};var Swc;async function fkn(){return Swc==null&&(Swc=await r$M()),Swc}async function r$M(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new QWa;let r=await iWo();return r!=null?new UWa({token:r,posthogApiKey:e}):await OZn()!=null?new T7o({posthogApiKey:e}):new UWa({token:void 0,posthogApiKey:e})}catch{return new QWa}}function LWa(e,t){return function(){return e.apply(t,arguments)}}var{toString:i$M}=Object.prototype,{getPrototypeOf:Dwc}=Object,{iterator:F7o,toStringTag:eT_}=Symbol,Q7o=(e=>t=>{let r=i$M.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),t3t=e=>(e=e.toLowerCase(),t=>Q7o(t)===e),U7o=e=>t=>typeof t===e,{isArray:pkn}=Array,dkn=U7o("undefined");function VWa(e){return e!==null&&!dkn(e)&&e.constructor!==null&&!dkn(e.constructor)&&l$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var tT_=t3t("ArrayBuffer");function n$M(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&tT_(e.buffer),t}var a$M=U7o("string"),l$=U7o("function"),rT_=U7o("number"),WWa=e=>e!==null&&typeof e=="object",o$M=e=>e===!0||e===!1,N7o=e=>{if(Q7o(e)!=="object")return!1;let t=Dwc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(eT_ in e)&&!(F7o in e)},u$M=e=>{if(!WWa(e)||VWa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},s$M=t3t("Date"),c$M=t3t("File"),l$M=t3t("Blob"),f$M=t3t("FileList"),d$M=e=>WWa(e)&&l$(e.pipe),p$M=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||l$(e.append)&&((t=Q7o(e))==="formdata"||t==="object"&&l$(e.toString)&&e.toString()==="[object FormData]"))},_$M=t3t("URLSearchParams"),[h$M,y$M,b$M,v$M]=["ReadableStream","Request","Response","Headers"].map(t3t),g$M=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function GWa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),pkn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(VWa(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function iT_(e,t){if(VWa(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var O_n=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,nT_=e=>!dkn(e)&&e!==O_n;function Mwc(){let{caseless:e,skipUndefined:t}=nT_(this)&&this||{},r={},i=(n,a)=>{let o=e&&iT_(r,a)||a;N7o(r[o])&&N7o(n)?r[o]=Mwc(r[o],n):N7o(n)?r[o]=Mwc({},n):pkn(n)?r[o]=n.slice():(!t||!dkn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&GWa(arguments[n],i);return r}var O$M=(e,t,r,{allOwnKeys:i}={})=>(GWa(t,(n,a)=>{r&&l$(n)?e[a]=LWa(n,r):e[a]=n},{allOwnKeys:i}),e),A$M=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),m$M=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},P$M=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&Dwc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},j$M=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},w$M=e=>{if(!e)return null;if(pkn(e))return e;let t=e.length;if(!rT_(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},E$M=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Dwc(Uint8Array)),S$M=(e,t)=>{let i=(e&&e[F7o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},M$M=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},D$M=t3t("HTMLFormElement"),B$M=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),k1_=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),I$M=t3t("RegExp"),aT_=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};GWa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},C$M=e=>{aT_(e,(t,r)=>{if(l$(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(l$(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},q$M=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return pkn(e)?i(e):i(String(e).split(t)),r},T$M=()=>{},R$M=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function z$M(e){return!!(e&&l$(e.append)&&e[eT_]==="FormData"&&e[F7o])}var N$M=e=>{let t=new Array(10),r=(i,n)=>{if(WWa(i)){if(t.indexOf(i)>=0)return;if(VWa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=pkn(i)?[]:{};return GWa(i,(o,c)=>{let d=r(o,n+1);!dkn(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},F$M=t3t("AsyncFunction"),Q$M=e=>e&&(WWa(e)||l$(e))&&l$(e.then)&&l$(e.catch),oT_=((e,t)=>e?setImmediate:t?((r,i)=>(O_n.addEventListener("message",({source:n,data:a})=>{n===O_n&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),O_n.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",l$(O_n.postMessage)),U$M=typeof queueMicrotask<"u"?queueMicrotask.bind(O_n):typeof process<"u"&&process.nextTick||oT_,L$M=e=>e!=null&&l$(e[F7o]),rr={isArray:pkn,isArrayBuffer:tT_,isBuffer:VWa,isFormData:p$M,isArrayBufferView:n$M,isString:a$M,isNumber:rT_,isBoolean:o$M,isObject:WWa,isPlainObject:N7o,isEmptyObject:u$M,isReadableStream:h$M,isRequest:y$M,isResponse:b$M,isHeaders:v$M,isUndefined:dkn,isDate:s$M,isFile:c$M,isBlob:l$M,isRegExp:I$M,isFunction:l$,isStream:d$M,isURLSearchParams:_$M,isTypedArray:E$M,isFileList:f$M,forEach:GWa,merge:Mwc,extend:O$M,trim:g$M,stripBOM:A$M,inherits:m$M,toFlatObject:P$M,kindOf:Q7o,kindOfTest:t3t,endsWith:j$M,toArray:w$M,forEachEntry:S$M,matchAll:M$M,isHTMLForm:D$M,hasOwnProperty:k1_,hasOwnProp:k1_,reduceDescriptors:aT_,freezeMethods:C$M,toObjectSet:q$M,toCamelCase:B$M,noop:T$M,toFiniteNumber:R$M,findKey:iT_,global:O_n,isContextDefined:nT_,isSpecCompliantForm:z$M,toJSONObject:N$M,isAsyncFn:F$M,isThenable:Q$M,setImmediate:oT_,asap:U$M,isIterable:L$M};function _kn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}rr.inherits(_kn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:rr.toJSONObject(this.config),code:this.code,status:this.status}}});var uT_=_kn.prototype,sT_={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{sT_[e]={value:e}});Object.defineProperties(_kn,sT_);Object.defineProperty(uT_,"isAxiosError",{value:!0});_kn.from=(e,t,r,i,n,a)=>{let o=Object.create(uT_);rr.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return _kn.call(o,c,d,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var Da=_kn;var cT_=ce(RXn(),1),L7o=cT_.default;function Bwc(e){return rr.isPlainObject(e)||rr.isArray(e)}function fT_(e){return rr.endsWith(e,"[]")?e.slice(0,-2):e}function lT_(e,t,r){return e?e.concat(t).map(function(n,a){return n=fT_(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function V$M(e){return rr.isArray(e)&&!e.some(Bwc)}var W$M=rr.toFlatObject(rr,{},null,function(t){return/^is[A-Z]/.test(t)});function G$M(e,t,r){if(!rr.isObject(e))throw new TypeError("target must be an object");t=t||new(L7o||FormData),r=rr.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!rr.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&rr.isSpecCompliantForm(t);if(!rr.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(rr.isDate(h))return h.toISOString();if(rr.isBoolean(h))return h.toString();if(!d&&rr.isBlob(h))throw new Da("Blob is not supported. Use a Buffer instead.");return rr.isArrayBuffer(h)||rr.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(rr.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(rr.isArray(h)&&V$M(h)||(rr.isFileList(h)||rr.endsWith(y,"[]"))&&(v=rr.toArray(h)))return y=fT_(y),v.forEach(function(A,g){!(rr.isUndefined(A)||A===null)&&t.append(o===!0?lT_([y],g,a):o===null?y:y+"[]",s(A))}),!1}return Bwc(h)?!0:(t.append(lT_(b,y,a),s(h)),!1)}let f=[],p=Object.assign(W$M,{defaultVisitor:u,convertValue:s,isVisitable:Bwc});function _(h,y){if(!rr.isUndefined(h)){if(f.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));f.push(h),rr.forEach(h,function(v,O){(!(rr.isUndefined(v)||v===null)&&n.call(t,v,rr.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),f.pop()}}if(!rr.isObject(e))throw new TypeError("data must be an object");return _(e),t}var N7i=G$M;function dT_(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function pT_(e,t){this._pairs=[],e&&N7i(e,this,t)}var _T_=pT_.prototype;_T_.append=function(t,r){this._pairs.push([t,r])};_T_.toString=function(t){let r=t?function(i){return t.call(this,i,dT_)}:dT_;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var hT_=pT_;function H$M(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function A_n(e,t,r){if(!t)return e;let i=r&&r.encode||H$M;rr.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=rr.isURLSearchParams(t)?t.toString():new hT_(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Iwc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){rr.forEach(this.handlers,function(i){i!==null&&t(i)})}},Cwc=Iwc;var hkn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var gT_=ce(require("crypto"),1);var yT_=ce(require("url"),1),bT_=yT_.default.URLSearchParams;var qwc="abcdefghijklmnopqrstuvwxyz",vT_="0123456789",OT_={DIGIT:vT_,ALPHA:qwc,ALPHA_DIGIT:qwc+qwc.toUpperCase()+vT_},x$M=(e=16,t=OT_.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);gT_.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},AT_={isNode:!0,classes:{URLSearchParams:bT_,FormData:L7o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:OT_,generateString:x$M,protocols:["http","https","file","data"]};var zwc={};Zt(zwc,{hasBrowserEnv:()=>Rwc,hasStandardBrowserEnv:()=>K$M,hasStandardBrowserWebWorkerEnv:()=>J$M,navigator:()=>Twc,origin:()=>$$M});var Rwc=typeof window<"u"&&typeof document<"u",Twc=typeof navigator=="object"&&navigator||void 0,K$M=Rwc&&(!Twc||["ReactNative","NativeScript","NS"].indexOf(Twc.product)<0),J$M=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",$$M=Rwc&&window.location.href||"http://localhost";var ZA={...zwc,...AT_};function Nwc(e,t){return N7i(e,new ZA.classes.URLSearchParams,{visitor:function(r,i,n,a){return ZA.isNode&&rr.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function Y$M(e){return rr.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function X$M(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function Z$M(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),d=a>=r.length;return o=!o&&rr.isArray(n)?n.length:o,d?(rr.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!rr.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&rr.isArray(n[o])&&(n[o]=X$M(n[o])),!c)}if(rr.isFormData(e)&&rr.isFunction(e.entries)){let r={};return rr.forEachEntry(e,(i,n)=>{t(Y$M(i),n,r,0)}),r}return null}var V7o=Z$M;function k$M(e,t,r){if(rr.isString(e))try{return(t||JSON.parse)(e),rr.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var Fwc={transitional:hkn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=rr.isObject(t);if(a&&rr.isHTMLForm(t)&&(t=new FormData(t)),rr.isFormData(t))return n?JSON.stringify(V7o(t)):t;if(rr.isArrayBuffer(t)||rr.isBuffer(t)||rr.isStream(t)||rr.isFile(t)||rr.isBlob(t)||rr.isReadableStream(t))return t;if(rr.isArrayBufferView(t))return t.buffer;if(rr.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return Nwc(t,this.formSerializer).toString();if((c=rr.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return N7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),k$M(t)):t}],transformResponse:[function(t){let r=this.transitional||Fwc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(rr.isResponse(t)||rr.isReadableStream(t))return t;if(t&&rr.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?Da.from(c,Da.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ZA.classes.FormData,Blob:ZA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};rr.forEach(["delete","get","head","post","put","patch"],e=>{Fwc.headers[e]={}});var ykn=Fwc;var eYM=rr.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mT_=e=>{let t={},r,i,n;return e&&e.split(`
1149
+ `);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=P1_.test(c)?c.replace(P1_,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=j1_)break}}return w1_(n)}}var _wc=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=qWa(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?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 v_n(t,"DOMException")}isDOMError(t){return v_n(t,"DOMError")}};var hwc=class{match(t){return nwc(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var ywc=class{constructor(){}match(t){return Yq_(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var IJM=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,bwc=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(IJM);return n&&(r=n[1],i=n[2]),[r,i]}};var E1_=["fatal","error","warning","log","info","debug"];function M7o(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var vwc=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return y7o(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=M7o(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return qWa(t)&&!Jq_(t)&&E1_.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(l1_(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var gwc=class{match(t){return y7o(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${M7o(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Owc=class{match(t){return TWa(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Awc=class{match(t){return v_n(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return TWa(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(TWa(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var mwc=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 D1_=require("fs"),B1_=require("readline"),D7o=new c$.ReduceableCache(25),I1_=new c$.ReduceableCache(20),Pwc=7,CJM=1e3,qJM=1e4;async function C1_(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||NJM(o)||FJM(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(I1_.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=UJM(a);if(o.every(d=>QJM(n,d)))continue;let c=LJM(D7o,n,{});i.push(TJM(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&RJM(e,D7o),D7o.reduce(),e}function TJM(e,t,r){return new Promise(i=>{let n=(0,D1_.createReadStream)(e),a=(0,B1_.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],f=s[1];function p(){I1_.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=VJM(_,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],f=h[1]}})})}function RJM(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;zJM(r.lineno,r,i)}}function zJM(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=q1_(e);n<e;n++){let a=r[n];if(a===void 0)return void S1_(t);t.pre_context.push(a)}if(r[e]===void 0)return void S1_(t);t.context_line=r[e];let i=T1_(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function S1_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function NJM(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function FJM(e){return e.lineno!==void 0&&e.lineno>qJM||e.colno!==void 0&&e.colno>CJM}function QJM(e,t){let r=D7o.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function UJM(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=M1_(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+Pwc:(n.push(i),i=M1_(a)),t++}return n}function M1_(e){return[q1_(e),T1_(e)]}function q1_(e){return Math.max(1,e-Pwc)}function T1_(e){return e+Pwc}function LJM(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function VJM(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}function WJM(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t(i))},{_posthogErrorHandler:!0})}function R1_(e,t){globalThis.process?.on("uncaughtException",WJM(e,t))}function z1_(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var GJM=2e3,OFi=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new b7o({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||zJt(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(R1_(this.onException.bind(this),this.onFatalError.bind(this)),z1_(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)})())}async onFatalError(t){console.error(t),await this.client.shutdown(GJM),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var N1_="5.17.4";async function F1_(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("")}var HJM=6e4,xJM=1152921504606847e3,KJM=["is_not"],skn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},f0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},FJt=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},B7o=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof FJt||d instanceof f0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,_&&(c[f.key]=_)}catch(p){p instanceof FJt||p instanceof f0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new f0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new f0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new f0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new f0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new f0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new f0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new f0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new f0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new f0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}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,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof FJt)throw u;if(u instanceof f0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new f0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?W1_(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):V1_(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await Q1_(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await Q1_(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}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),!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 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}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(HJM,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}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.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new skn(`Your project key or personal API 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.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new skn(`Your personal API 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 personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new skn(`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 i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof skn&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=g_n(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function Q1_(e,t,r=""){let i=await F1_(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/xJM}function V1_(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new f0("Operator is_not_set is not supported")}else throw new f0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!KJM.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return U1_(String(n))&&String(o).match(String(n))!==null;case"not_regex":return U1_(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s==null||o==null?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new f0("Date operations cannot be performed on boolean values");let s=$JM(String(n));if(s==null&&(s=L1_(n)),s==null)throw new f0(`Invalid date: ${n}`);let u=L1_(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new f0(`Unknown operator: ${a}`)}}function JJM(e,t){if(!(e in t))throw new FJt(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function W1_(e,t,r,i=!1){let n=String(e.value);JJM(n,r);let a=r[n];return G1_(a,t,r,i)}function G1_(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let d=G1_(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof FJt)throw d;if(d instanceof f0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new f0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=W1_(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=V1_(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof FJt)throw d;if(d instanceof f0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new f0("can't match cohort without a given cohort property value");return n==="AND"}function U1_(e){try{return new RegExp(e),!0}catch{return!1}}function L1_(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 f0(`${e} is in an invalid date format`)}throw new f0(`The date provided ${e} must be a string, number, or date object`)}function $JM(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var I7o=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var YJM=100,H1_=3e4,XJM=5e4,C7o=class extends FWa{constructor(t,r={}){if(super(t,r),this._memoryStorage=new I7o,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,YJM):H1_,r.personalApiKey){if(r.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.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new B7o({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider}))}this.errorTracking=new OFi(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||XJM}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)}getLibraryVersion(){return N1_}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=H1_){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let f=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=f!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,f=b_n(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${f}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:f,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:f,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),f}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let f;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,f=y.payload)}catch(y){if(y instanceof FJt||y instanceof f0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(f!==void 0)&&!c&&(f=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),f}async getRemoteConfigPayload(t){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 i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},_=!0;if(u&&(f=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:f,featureFlagPayloads:p}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=g_n(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(Xq_(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(OFi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(OFi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=zJt(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[O,A]of Object.entries(y))b[`$feature/${O}`]=A;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&Hq_(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var x1_=require("async_hooks"),q7o=class{constructor(){this.storage=new x1_.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var K1_="posthog-node";function ZJM(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[jwc.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],p=f.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var jwc=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=K1_,this.name=K1_,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(ZJM(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};OFi.errorPropertiesBuilder=new c$.ErrorPropertiesBuilder([new c$.EventCoercer,new c$.ErrorCoercer,new c$.ObjectCoercer,new c$.StringCoercer,new c$.PrimitiveCoercer],c$.createStackParser("node:javascript",c$.nodeStackLineParser),[Uq_(),C1_]);var ckn=class extends C7o{getLibraryId(){return"posthog-node"}initializeContext(){return new q7o}};var T7o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new ckn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.43.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var QWa=class{async sendEvent(){}async identify(){}async flush(){}};var lkn=require("fs/promises"),X1_=require("os"),Z1_=require("path");var J1_=ce(require("crypto")),z7o=new Uint8Array(256),R7o=z7o.length;function wwc(){return R7o>z7o.length-16&&(J1_.default.randomFillSync(z7o),R7o=0),z7o.slice(R7o,R7o+=16)}var R4=[];for(let e=0;e<256;++e)R4.push((e+256).toString(16).slice(1));function $1_(e,t=0){return R4[e[t+0]]+R4[e[t+1]]+R4[e[t+2]]+R4[e[t+3]]+"-"+R4[e[t+4]]+R4[e[t+5]]+"-"+R4[e[t+6]]+R4[e[t+7]]+"-"+R4[e[t+8]]+R4[e[t+9]]+"-"+R4[e[t+10]]+R4[e[t+11]]+R4[e[t+12]]+R4[e[t+13]]+R4[e[t+14]]+R4[e[t+15]]}var Y1_=ce(require("crypto")),Ewc={randomUUID:Y1_.default.randomUUID};function kJM(e,t,r){if(Ewc.randomUUID&&!t&&!e)return Ewc.randomUUID();e=e||{};let i=e.random||(e.rng||wwc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return $1_(i)}var Xbe=kJM;var e$M="id",t$M=".fern",UWa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new ckn(r),this.userId=t==null?void 0:vgc(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:"3.43.0",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}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 w4({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=Ct(Sr.of((0,X1_.homedir)()),He.of(t$M),He.of(e$M));await mi(t)||(await(0,lkn.mkdir)((0,Z1_.dirname)(t),{recursive:!0}),await(0,lkn.writeFile)(t,Xbe())),this.persistedDistinctId=(await(0,lkn.readFile)(t)).toString()}return this.persistedDistinctId}};var Swc;async function fkn(){return Swc==null&&(Swc=await r$M()),Swc}async function r$M(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new QWa;let r=await iWo();return r!=null?new UWa({token:r,posthogApiKey:e}):await OZn()!=null?new T7o({posthogApiKey:e}):new UWa({token:void 0,posthogApiKey:e})}catch{return new QWa}}function LWa(e,t){return function(){return e.apply(t,arguments)}}var{toString:i$M}=Object.prototype,{getPrototypeOf:Dwc}=Object,{iterator:F7o,toStringTag:eT_}=Symbol,Q7o=(e=>t=>{let r=i$M.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),t3t=e=>(e=e.toLowerCase(),t=>Q7o(t)===e),U7o=e=>t=>typeof t===e,{isArray:pkn}=Array,dkn=U7o("undefined");function VWa(e){return e!==null&&!dkn(e)&&e.constructor!==null&&!dkn(e.constructor)&&l$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var tT_=t3t("ArrayBuffer");function n$M(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&tT_(e.buffer),t}var a$M=U7o("string"),l$=U7o("function"),rT_=U7o("number"),WWa=e=>e!==null&&typeof e=="object",o$M=e=>e===!0||e===!1,N7o=e=>{if(Q7o(e)!=="object")return!1;let t=Dwc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(eT_ in e)&&!(F7o in e)},u$M=e=>{if(!WWa(e)||VWa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},s$M=t3t("Date"),c$M=t3t("File"),l$M=t3t("Blob"),f$M=t3t("FileList"),d$M=e=>WWa(e)&&l$(e.pipe),p$M=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||l$(e.append)&&((t=Q7o(e))==="formdata"||t==="object"&&l$(e.toString)&&e.toString()==="[object FormData]"))},_$M=t3t("URLSearchParams"),[h$M,y$M,b$M,v$M]=["ReadableStream","Request","Response","Headers"].map(t3t),g$M=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function GWa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),pkn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(VWa(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function iT_(e,t){if(VWa(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var O_n=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,nT_=e=>!dkn(e)&&e!==O_n;function Mwc(){let{caseless:e,skipUndefined:t}=nT_(this)&&this||{},r={},i=(n,a)=>{let o=e&&iT_(r,a)||a;N7o(r[o])&&N7o(n)?r[o]=Mwc(r[o],n):N7o(n)?r[o]=Mwc({},n):pkn(n)?r[o]=n.slice():(!t||!dkn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&GWa(arguments[n],i);return r}var O$M=(e,t,r,{allOwnKeys:i}={})=>(GWa(t,(n,a)=>{r&&l$(n)?e[a]=LWa(n,r):e[a]=n},{allOwnKeys:i}),e),A$M=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),m$M=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},P$M=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&Dwc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},j$M=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},w$M=e=>{if(!e)return null;if(pkn(e))return e;let t=e.length;if(!rT_(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},E$M=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Dwc(Uint8Array)),S$M=(e,t)=>{let i=(e&&e[F7o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},M$M=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},D$M=t3t("HTMLFormElement"),B$M=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),k1_=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),I$M=t3t("RegExp"),aT_=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};GWa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},C$M=e=>{aT_(e,(t,r)=>{if(l$(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(l$(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},q$M=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return pkn(e)?i(e):i(String(e).split(t)),r},T$M=()=>{},R$M=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function z$M(e){return!!(e&&l$(e.append)&&e[eT_]==="FormData"&&e[F7o])}var N$M=e=>{let t=new Array(10),r=(i,n)=>{if(WWa(i)){if(t.indexOf(i)>=0)return;if(VWa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=pkn(i)?[]:{};return GWa(i,(o,c)=>{let d=r(o,n+1);!dkn(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},F$M=t3t("AsyncFunction"),Q$M=e=>e&&(WWa(e)||l$(e))&&l$(e.then)&&l$(e.catch),oT_=((e,t)=>e?setImmediate:t?((r,i)=>(O_n.addEventListener("message",({source:n,data:a})=>{n===O_n&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),O_n.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",l$(O_n.postMessage)),U$M=typeof queueMicrotask<"u"?queueMicrotask.bind(O_n):typeof process<"u"&&process.nextTick||oT_,L$M=e=>e!=null&&l$(e[F7o]),rr={isArray:pkn,isArrayBuffer:tT_,isBuffer:VWa,isFormData:p$M,isArrayBufferView:n$M,isString:a$M,isNumber:rT_,isBoolean:o$M,isObject:WWa,isPlainObject:N7o,isEmptyObject:u$M,isReadableStream:h$M,isRequest:y$M,isResponse:b$M,isHeaders:v$M,isUndefined:dkn,isDate:s$M,isFile:c$M,isBlob:l$M,isRegExp:I$M,isFunction:l$,isStream:d$M,isURLSearchParams:_$M,isTypedArray:E$M,isFileList:f$M,forEach:GWa,merge:Mwc,extend:O$M,trim:g$M,stripBOM:A$M,inherits:m$M,toFlatObject:P$M,kindOf:Q7o,kindOfTest:t3t,endsWith:j$M,toArray:w$M,forEachEntry:S$M,matchAll:M$M,isHTMLForm:D$M,hasOwnProperty:k1_,hasOwnProp:k1_,reduceDescriptors:aT_,freezeMethods:C$M,toObjectSet:q$M,toCamelCase:B$M,noop:T$M,toFiniteNumber:R$M,findKey:iT_,global:O_n,isContextDefined:nT_,isSpecCompliantForm:z$M,toJSONObject:N$M,isAsyncFn:F$M,isThenable:Q$M,setImmediate:oT_,asap:U$M,isIterable:L$M};function _kn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}rr.inherits(_kn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:rr.toJSONObject(this.config),code:this.code,status:this.status}}});var uT_=_kn.prototype,sT_={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{sT_[e]={value:e}});Object.defineProperties(_kn,sT_);Object.defineProperty(uT_,"isAxiosError",{value:!0});_kn.from=(e,t,r,i,n,a)=>{let o=Object.create(uT_);rr.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return _kn.call(o,c,d,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var Da=_kn;var cT_=ce(RXn(),1),L7o=cT_.default;function Bwc(e){return rr.isPlainObject(e)||rr.isArray(e)}function fT_(e){return rr.endsWith(e,"[]")?e.slice(0,-2):e}function lT_(e,t,r){return e?e.concat(t).map(function(n,a){return n=fT_(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function V$M(e){return rr.isArray(e)&&!e.some(Bwc)}var W$M=rr.toFlatObject(rr,{},null,function(t){return/^is[A-Z]/.test(t)});function G$M(e,t,r){if(!rr.isObject(e))throw new TypeError("target must be an object");t=t||new(L7o||FormData),r=rr.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!rr.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&rr.isSpecCompliantForm(t);if(!rr.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(rr.isDate(h))return h.toISOString();if(rr.isBoolean(h))return h.toString();if(!d&&rr.isBlob(h))throw new Da("Blob is not supported. Use a Buffer instead.");return rr.isArrayBuffer(h)||rr.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(rr.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(rr.isArray(h)&&V$M(h)||(rr.isFileList(h)||rr.endsWith(y,"[]"))&&(v=rr.toArray(h)))return y=fT_(y),v.forEach(function(A,g){!(rr.isUndefined(A)||A===null)&&t.append(o===!0?lT_([y],g,a):o===null?y:y+"[]",s(A))}),!1}return Bwc(h)?!0:(t.append(lT_(b,y,a),s(h)),!1)}let f=[],p=Object.assign(W$M,{defaultVisitor:u,convertValue:s,isVisitable:Bwc});function _(h,y){if(!rr.isUndefined(h)){if(f.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));f.push(h),rr.forEach(h,function(v,O){(!(rr.isUndefined(v)||v===null)&&n.call(t,v,rr.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),f.pop()}}if(!rr.isObject(e))throw new TypeError("data must be an object");return _(e),t}var N7i=G$M;function dT_(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function pT_(e,t){this._pairs=[],e&&N7i(e,this,t)}var _T_=pT_.prototype;_T_.append=function(t,r){this._pairs.push([t,r])};_T_.toString=function(t){let r=t?function(i){return t.call(this,i,dT_)}:dT_;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var hT_=pT_;function H$M(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function A_n(e,t,r){if(!t)return e;let i=r&&r.encode||H$M;rr.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=rr.isURLSearchParams(t)?t.toString():new hT_(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Iwc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){rr.forEach(this.handlers,function(i){i!==null&&t(i)})}},Cwc=Iwc;var hkn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var gT_=ce(require("crypto"),1);var yT_=ce(require("url"),1),bT_=yT_.default.URLSearchParams;var qwc="abcdefghijklmnopqrstuvwxyz",vT_="0123456789",OT_={DIGIT:vT_,ALPHA:qwc,ALPHA_DIGIT:qwc+qwc.toUpperCase()+vT_},x$M=(e=16,t=OT_.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);gT_.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},AT_={isNode:!0,classes:{URLSearchParams:bT_,FormData:L7o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:OT_,generateString:x$M,protocols:["http","https","file","data"]};var zwc={};Zt(zwc,{hasBrowserEnv:()=>Rwc,hasStandardBrowserEnv:()=>K$M,hasStandardBrowserWebWorkerEnv:()=>J$M,navigator:()=>Twc,origin:()=>$$M});var Rwc=typeof window<"u"&&typeof document<"u",Twc=typeof navigator=="object"&&navigator||void 0,K$M=Rwc&&(!Twc||["ReactNative","NativeScript","NS"].indexOf(Twc.product)<0),J$M=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",$$M=Rwc&&window.location.href||"http://localhost";var ZA={...zwc,...AT_};function Nwc(e,t){return N7i(e,new ZA.classes.URLSearchParams,{visitor:function(r,i,n,a){return ZA.isNode&&rr.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function Y$M(e){return rr.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function X$M(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function Z$M(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),d=a>=r.length;return o=!o&&rr.isArray(n)?n.length:o,d?(rr.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!rr.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&rr.isArray(n[o])&&(n[o]=X$M(n[o])),!c)}if(rr.isFormData(e)&&rr.isFunction(e.entries)){let r={};return rr.forEachEntry(e,(i,n)=>{t(Y$M(i),n,r,0)}),r}return null}var V7o=Z$M;function k$M(e,t,r){if(rr.isString(e))try{return(t||JSON.parse)(e),rr.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var Fwc={transitional:hkn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=rr.isObject(t);if(a&&rr.isHTMLForm(t)&&(t=new FormData(t)),rr.isFormData(t))return n?JSON.stringify(V7o(t)):t;if(rr.isArrayBuffer(t)||rr.isBuffer(t)||rr.isStream(t)||rr.isFile(t)||rr.isBlob(t)||rr.isReadableStream(t))return t;if(rr.isArrayBufferView(t))return t.buffer;if(rr.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return Nwc(t,this.formSerializer).toString();if((c=rr.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return N7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),k$M(t)):t}],transformResponse:[function(t){let r=this.transitional||Fwc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(rr.isResponse(t)||rr.isReadableStream(t))return t;if(t&&rr.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?Da.from(c,Da.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ZA.classes.FormData,Blob:ZA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};rr.forEach(["delete","get","head","post","put","patch"],e=>{Fwc.headers[e]={}});var ykn=Fwc;var eYM=rr.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mT_=e=>{let t={},r,i,n;return e&&e.split(`
1150
1150
  `).forEach(function(o){n=o.indexOf(":"),r=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim(),!(!r||t[r]&&eYM[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var PT_=Symbol("internals");function HWa(e){return e&&String(e).trim().toLowerCase()}function W7o(e){return e===!1||e==null?e:rr.isArray(e)?e.map(W7o):String(e)}function tYM(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}var rYM=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Qwc(e,t,r,i,n){if(rr.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!rr.isString(t)){if(rr.isString(i))return t.indexOf(i)!==-1;if(rr.isRegExp(i))return i.test(t)}}function iYM(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function nYM(e,t){let r=rr.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,o){return this[i].call(this,t,n,a,o)},configurable:!0})})}var bkn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,d,s){let u=HWa(d);if(!u)throw new Error("header name must be a non-empty string");let f=rr.findKey(n,u);(!f||n[f]===void 0||s===!0||s===void 0&&n[f]!==!1)&&(n[f||d]=W7o(c))}let o=(c,d)=>rr.forEach(c,(s,u)=>a(s,u,d));if(rr.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(rr.isString(t)&&(t=t.trim())&&!rYM(t))o(mT_(t),r);else if(rr.isObject(t)&&rr.isIterable(t)){let c={},d,s;for(let u of t){if(!rr.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(d=c[s])?rr.isArray(d)?[...d,u[1]]:[d,u[1]]:u[1]}o(c,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=HWa(t),t){let i=rr.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return tYM(n);if(rr.isFunction(r))return r.call(this,n,i);if(rr.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=HWa(t),t){let i=rr.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||Qwc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(o){if(o=HWa(o),o){let c=rr.findKey(i,o);c&&(!r||Qwc(i,i[c],c,r))&&(delete i[c],n=!0)}}return rr.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||Qwc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return rr.forEach(this,(n,a)=>{let o=rr.findKey(i,a);if(o){r[o]=W7o(n),delete r[a];return}let c=t?iYM(a):String(a).trim();c!==a&&delete r[a],r[c]=W7o(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return rr.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&rr.isArray(i)?i.join(", "):i)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
1151
1151
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let i=new this(t);return r.forEach(n=>i.set(n)),i}static accessor(t){let i=(this[PT_]=this[PT_]={accessors:{}}).accessors,n=this.prototype;function a(o){let c=HWa(o);i[c]||(nYM(n,o),i[c]=!0)}return rr.isArray(t)?t.forEach(a):a(t),this}};bkn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);rr.reduceDescriptors(bkn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});rr.freezeMethods(bkn);var XM=bkn;function xWa(e,t){let r=this||ykn,i=t||r,n=XM.from(i.headers),a=i.data;return rr.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function KWa(e){return!!(e&&e.__CANCEL__)}function jT_(e,t,r){Da.call(this,e??"canceled",Da.ERR_CANCELED,t,r),this.name="CanceledError"}rr.inherits(jT_,Da,{__CANCEL__:!0});var Zbe=jT_;function QJt(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Da("Request failed with status code "+r.status,[Da.ERR_BAD_REQUEST,Da.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function Uwc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Lwc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function m_n(e,t,r){let i=!Uwc(t);return e&&(i||r==!1)?Lwc(e,t):t}var JT_=ce(Vwc(),1),$T_=ce(require("http"),1),YT_=ce(require("https"),1),XT_=ce(require("util"),1),ZT_=ce(CT_(),1),mFi=ce(require("zlib"),1);var w_n="1.12.2";function ZWa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var AYM=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function tEc(e,t,r){let i=r&&r.Blob||ZA.classes.Blob,n=ZWa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=AYM.exec(e);if(!a)throw new Da("Invalid URL",Da.ERR_INVALID_URL);let o=a[1],c=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),c?"base64":"utf8");if(t){if(!i)throw new Da("Blob is not supported",Da.ERR_NOT_SUPPORT);return new i([s],{type:o})}return s}throw new Da("Unsupported protocol "+n,Da.ERR_NOT_SUPPORT)}var S_n=ce(require("stream"),1);var qT_=ce(require("stream"),1);var rEc=Symbol("internals"),iEc=class extends qT_.default.Transform{constructor(t){t=rr.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!rr.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[rEc]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[rEc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[rEc],a=n.maxRate,o=this.readableHighWaterMark,c=n.timeWindow,d=1e3/c,s=a/d,u=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,f=(_,h)=>{let y=Buffer.byteLength(_);n.bytesSeen+=y,n.bytes+=y,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(_)?process.nextTick(h):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(h)}},p=(_,h)=>{let y=Buffer.byteLength(_),b=null,v=o,O,A=0;if(a){let g=Date.now();(!n.ts||(A=g-n.ts)>=c)&&(n.ts=g,O=s-n.bytes,n.bytes=O<0?-O:0,A=0),O=s-n.bytes}if(a){if(O<=0)return setTimeout(()=>{h(null,_)},c-A);O<v&&(v=O)}v&&y>v&&y-v>u&&(b=_.subarray(v),_=_.subarray(0,v)),f(_,b?()=>{process.nextTick(h,null,b)}:h)};p(t,function _(h,y){if(h)return i(h);y?p(y,_):i(null)})}},nEc=iEc;var kT_=require("events");var RT_=ce(require("util"),1),zT_=require("stream");var{asyncIterator:TT_}=Symbol,mYM=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[TT_]?yield*e[TT_]():yield e},G7o=mYM;var PYM=ZA.ALPHABET.ALPHA_DIGIT+"-_",kWa=typeof TextEncoder=="function"?new TextEncoder:new RT_.default.TextEncoder,E_n=`\r
1152
1152
  `,jYM=kWa.encode(E_n),wYM=2,aEc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=rr.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${E_n}`;n?r=kWa.encode(String(r).replace(/\r?\n|\r\n?/g,E_n)):a+=`Content-Type: ${r.type||"application/octet-stream"}${E_n}`,this.headers=kWa.encode(a+E_n),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+wYM,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;rr.isTypedArray(t)?yield t:yield*G7o(t),yield jYM}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},EYM=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+ZA.generateString(n,PYM)}=r||{};if(!rr.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let o=kWa.encode("--"+a+E_n),c=kWa.encode("--"+a+"--"+E_n),d=c.byteLength,s=Array.from(e.entries()).map(([f,p])=>{let _=new aEc(f,p);return d+=_.size,_});d+=o.byteLength*s.length,d=rr.toFiniteNumber(d);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(u["Content-Length"]=d),t&&t(u),zT_.Readable.from((async function*(){for(let f of s)yield o,yield*f.encode();yield c})())},NT_=EYM;var FT_=ce(require("stream"),1),oEc=class extends FT_.default.Transform{__transform(t,r,i){this.push(t),i()}_transform(t,r,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let n=Buffer.alloc(2);n[0]=120,n[1]=156,this.push(n,r)}this.__transform(t,r,i)}},QT_=oEc;var SYM=(e,t)=>rr.isAsyncFn(e)?function(...r){let i=r.pop();e.apply(this,r).then(n=>{try{t?i(null,...t(n)):i(null,n)}catch(a){i(a)}},i)}:e,UT_=SYM;function MYM(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,o;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),u=i[a];o||(o=s),r[n]=d,i[n]=s;let f=a,p=0;for(;f!==n;)p+=r[f++],f=f%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-o<t)return;let _=u&&s-u;return _?Math.round(p*1e3/_):void 0}}var LT_=MYM;function DYM(e,t){let r=0,i=1e3/t,n,a,o=(s,u=Date.now())=>{r=u,n=null,a&&(clearTimeout(a),a=null),e(...s)};return[(...s)=>{let u=Date.now(),f=u-r;f>=i?o(s,u):(n=s,a||(a=setTimeout(()=>{a=null,o(n)},i-f)))},()=>n&&o(n)]}var VT_=DYM;var AFi=(e,t,r=3)=>{let i=0,n=LT_(50,250);return VT_(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,d=o-i,s=n(d),u=o<=c;i=o;let f={loaded:o,total:c,progress:c?o/c:void 0,bytes:d,rate:s||void 0,estimated:s&&c&&u?(c-o)/s:void 0,event:a,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(f)},r)},gkn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},Okn=e=>(...t)=>rr.asap(()=>e(...t));function uEc(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;let t=e.indexOf(",");if(t<0)return 0;let r=e.slice(5,t),i=e.slice(t+1);if(/;base64/i.test(r)){let a=i.length,o=i.length;for(let p=0;p<o;p++)if(i.charCodeAt(p)===37&&p+2<o){let _=i.charCodeAt(p+1),h=i.charCodeAt(p+2);(_>=48&&_<=57||_>=65&&_<=70||_>=97&&_<=102)&&(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102)&&(a-=2,p+=2)}let c=0,d=o-1,s=p=>p>=2&&i.charCodeAt(p-2)===37&&i.charCodeAt(p-1)===51&&(i.charCodeAt(p)===68||i.charCodeAt(p)===100);d>=0&&(i.charCodeAt(d)===61?(c++,d--):s(d)&&(c++,d-=3)),c===1&&d>=0&&(i.charCodeAt(d)===61||s(d))&&c++;let f=Math.floor(a/4)*3-(c||0);return f>0?f:0}return Buffer.byteLength(i,"utf8")}var WT_={flush:mFi.default.constants.Z_SYNC_FLUSH,finishFlush:mFi.default.constants.Z_SYNC_FLUSH},BYM={flush:mFi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:mFi.default.constants.BROTLI_OPERATION_FLUSH},GT_=rr.isFunction(mFi.default.createBrotliDecompress),{http:IYM,https:CYM}=ZT_.default,qYM=/https:?/,HT_=ZA.protocols.map(e=>e+":"),xT_=(e,[t,r])=>(e.on("end",r).on("error",r),t);function TYM(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function eR_(e,t,r){let i=t;if(!i&&i!==!1){let n=JT_.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){eR_(a,t,a.href)}}var RYM=typeof process<"u"&&rr.kindOf(process)==="process",zYM=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},o=d=>{a(d),t(d)},c=d=>{a(d,!0),r(d)};e(o,c,d=>i=d).catch(c)}),NYM=({address:e,family:t})=>{if(!rr.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},KT_=(e,t)=>NYM(rr.isObject(e)?e:{address:e,family:t}),tR_=RYM&&function(t){return zYM(async function(i,n,a){let{data:o,lookup:c,family:d}=t,{responseType:s,responseEncoding:u}=t,f=t.method.toUpperCase(),p,_=!1,h;if(c){let ee=UT_(c,ve=>rr.isArray(ve)?ve:[ve]);c=(ve,be,H)=>{ee(ve,be,(G,Ee,se)=>{if(G)return H(G);let Ae=rr.isArray(Ee)?Ee.map(Fe=>KT_(Fe)):[KT_(Ee,se)];be.all?H(G,Ae):H(G,Ae[0].address,Ae[0].family)})}}let y=new kT_.EventEmitter,b=()=>{t.cancelToken&&t.cancelToken.unsubscribe(v),t.signal&&t.signal.removeEventListener("abort",v),y.removeAllListeners()};a((ee,ve)=>{p=!0,ve&&(_=!0,b())});function v(ee){y.emit("abort",!ee||ee.type?new Zbe(null,t,h):ee)}y.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(v),t.signal&&(t.signal.aborted?v():t.signal.addEventListener("abort",v)));let O=m_n(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(O,ZA.hasBrowserEnv?ZA.origin:void 0),g=A.protocol||HT_[0];if(g==="data:"){if(t.maxContentLength>-1){let ve=String(t.url||O||"");if(uEc(ve)>t.maxContentLength)return n(new Da("maxContentLength size of "+t.maxContentLength+" exceeded",Da.ERR_BAD_RESPONSE,t))}let ee;if(f!=="GET")return QJt(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{ee=tEc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(ve){throw Da.from(ve,Da.ERR_BAD_REQUEST,t)}return s==="text"?(ee=ee.toString(u),(!u||u==="utf8")&&(ee=rr.stripBOM(ee))):s==="stream"&&(ee=S_n.default.Readable.from(ee)),QJt(i,n,{data:ee,status:200,statusText:"OK",headers:new XM,config:t})}if(HT_.indexOf(g)===-1)return n(new Da("Unsupported protocol "+g,Da.ERR_BAD_REQUEST,t));let m=XM.from(t.headers).normalize();m.set("User-Agent","axios/"+w_n,!1);let{onUploadProgress:j,onDownloadProgress:M}=t,w=t.maxRate,D,B;if(rr.isSpecCompliantForm(o)){let ee=m.getContentType(/boundary=([-_\w\d]{10,70})/i);o=NT_(o,ve=>{m.set(ve)},{tag:`axios-${w_n}-boundary`,boundary:ee&&ee[1]||void 0})}else if(rr.isFormData(o)&&rr.isFunction(o.getHeaders)){if(m.set(o.getHeaders()),!m.hasContentLength())try{let ee=await XT_.default.promisify(o.getLength).call(o);Number.isFinite(ee)&&ee>=0&&m.setContentLength(ee)}catch{}}else if(rr.isBlob(o)||rr.isFile(o))o.size&&m.setContentType(o.type||"application/octet-stream"),m.setContentLength(o.size||0),o=S_n.default.Readable.from(G7o(o));else if(o&&!rr.isStream(o)){if(!Buffer.isBuffer(o))if(rr.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(rr.isString(o))o=Buffer.from(o,"utf-8");else return n(new Da("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Da.ERR_BAD_REQUEST,t));if(m.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return n(new Da("Request body larger than maxBodyLength limit",Da.ERR_BAD_REQUEST,t))}let z=rr.toFiniteNumber(m.getContentLength());rr.isArray(w)?(D=w[0],B=w[1]):D=B=w,o&&(j||D)&&(rr.isStream(o)||(o=S_n.default.Readable.from(o,{objectMode:!1})),o=S_n.default.pipeline([o,new nEc({maxRate:rr.toFiniteNumber(D)})],rr.noop),j&&o.on("progress",xT_(o,gkn(z,AFi(Okn(j),!1,3)))));let F;if(t.auth){let ee=t.auth.username||"",ve=t.auth.password||"";F=ee+":"+ve}if(!F&&A.username){let ee=A.username,ve=A.password;F=ee+":"+ve}F&&m.delete("authorization");let q;try{q=A_n(A.pathname+A.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(ee){let ve=new Error(ee.message);return ve.config=t,ve.url=t.url,ve.exists=!0,n(ve)}m.set("Accept-Encoding","gzip, compress, deflate"+(GT_?", br":""),!1);let N={path:q,method:f,headers:m.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:F,protocol:g,family:d,beforeRedirect:TYM,beforeRedirects:{}};!rr.isUndefined(c)&&(N.lookup=c),t.socketPath?N.socketPath=t.socketPath:(N.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,N.port=A.port,eR_(N,t.proxy,g+"//"+A.hostname+(A.port?":"+A.port:"")+N.path));let Q,x=qYM.test(N.protocol);if(N.agent=x?t.httpsAgent:t.httpAgent,t.transport?Q=t.transport:t.maxRedirects===0?Q=x?YT_.default:$T_.default:(t.maxRedirects&&(N.maxRedirects=t.maxRedirects),t.beforeRedirect&&(N.beforeRedirects.config=t.beforeRedirect),Q=x?CYM:IYM),t.maxBodyLength>-1?N.maxBodyLength=t.maxBodyLength:N.maxBodyLength=1/0,t.insecureHTTPParser&&(N.insecureHTTPParser=t.insecureHTTPParser),h=Q.request(N,function(ve){if(h.destroyed)return;let be=[ve],H=+ve.headers["content-length"];if(M||B){let Fe=new nEc({maxRate:rr.toFiniteNumber(B)});M&&Fe.on("progress",xT_(Fe,gkn(H,AFi(Okn(M),!0,3)))),be.push(Fe)}let G=ve,Ee=ve.req||h;if(t.decompress!==!1&&ve.headers["content-encoding"])switch((f==="HEAD"||ve.statusCode===204)&&delete ve.headers["content-encoding"],(ve.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":be.push(mFi.default.createUnzip(WT_)),delete ve.headers["content-encoding"];break;case"deflate":be.push(new QT_),be.push(mFi.default.createUnzip(WT_)),delete ve.headers["content-encoding"];break;case"br":GT_&&(be.push(mFi.default.createBrotliDecompress(BYM)),delete ve.headers["content-encoding"])}G=be.length>1?S_n.default.pipeline(be,rr.noop):be[0];let se=S_n.default.finished(G,()=>{se(),b()}),Ae={status:ve.statusCode,statusText:ve.statusMessage,headers:new XM(ve.headers),config:t,request:Ee};if(s==="stream")Ae.data=G,QJt(i,n,Ae);else{let Fe=[],oe=0;G.on("data",function(Ye){Fe.push(Ye),oe+=Ye.length,t.maxContentLength>-1&&oe>t.maxContentLength&&(_=!0,G.destroy(),n(new Da("maxContentLength size of "+t.maxContentLength+" exceeded",Da.ERR_BAD_RESPONSE,t,Ee)))}),G.on("aborted",function(){if(_)return;let Ye=new Da("stream has been aborted",Da.ERR_BAD_RESPONSE,t,Ee);G.destroy(Ye),n(Ye)}),G.on("error",function(Ye){h.destroyed||n(Da.from(Ye,null,t,Ee))}),G.on("end",function(){try{let Ye=Fe.length===1?Fe[0]:Buffer.concat(Fe);s!=="arraybuffer"&&(Ye=Ye.toString(u),(!u||u==="utf8")&&(Ye=rr.stripBOM(Ye))),Ae.data=Ye}catch(Ye){return n(Da.from(Ye,null,t,Ae.request,Ae))}QJt(i,n,Ae)})}y.once("abort",Fe=>{G.destroyed||(G.emit("error",Fe),G.destroy())})}),y.once("abort",ee=>{n(ee),h.destroy(ee)}),h.on("error",function(ve){n(Da.from(ve,null,t,h))}),h.on("socket",function(ve){ve.setKeepAlive(!0,1e3*60)}),t.timeout){let ee=parseInt(t.timeout,10);if(Number.isNaN(ee)){n(new Da("error trying to parse `config.timeout` to int",Da.ERR_BAD_OPTION_VALUE,t,h));return}h.setTimeout(ee,function(){if(p)return;let be=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",H=t.transitional||hkn;t.timeoutErrorMessage&&(be=t.timeoutErrorMessage),n(new Da(be,H.clarifyTimeoutError?Da.ETIMEDOUT:Da.ECONNABORTED,t,h)),v()})}if(rr.isStream(o)){let ee=!1,ve=!1;o.on("end",()=>{ee=!0}),o.once("error",be=>{ve=!0,h.destroy(be)}),o.on("close",()=>{!ee&&!ve&&v(new Zbe("Request stream has been aborted",t,h))}),o.pipe(h)}else h.end(o)})};var rR_=ZA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,ZA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(ZA.origin),ZA.navigator&&/(msie|trident)/i.test(ZA.navigator.userAgent)):()=>!0;var iR_=ZA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let o=[e+"="+encodeURIComponent(t)];rr.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),rr.isString(i)&&o.push("path="+i),rr.isString(n)&&o.push("domain="+n),a===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var nR_=e=>e instanceof XM?{...e}:e;function r3t(e,t){t=t||{};let r={};function i(s,u,f,p){return rr.isPlainObject(s)&&rr.isPlainObject(u)?rr.merge.call({caseless:p},s,u):rr.isPlainObject(u)?rr.merge({},u):rr.isArray(u)?u.slice():u}function n(s,u,f,p){if(rr.isUndefined(u)){if(!rr.isUndefined(s))return i(void 0,s,f,p)}else return i(s,u,f,p)}function a(s,u){if(!rr.isUndefined(u))return i(void 0,u)}function o(s,u){if(rr.isUndefined(u)){if(!rr.isUndefined(s))return i(void 0,s)}else return i(void 0,u)}function c(s,u,f){if(f in t)return i(s,u);if(f in e)return i(void 0,s)}let d={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(s,u,f)=>n(nR_(s),nR_(u),f,!0)};return rr.forEach(Object.keys({...e,...t}),function(u){let f=d[u]||n,p=f(e[u],t[u],u);rr.isUndefined(p)&&f!==c||(r[u]=p)}),r}var H7o=e=>{let t=r3t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=XM.from(o),t.url=A_n(m_n(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),rr.isFormData(r)){if(ZA.hasStandardBrowserEnv||ZA.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(rr.isFunction(r.getHeaders)){let d=r.getHeaders(),s=["content-type","content-length"];Object.entries(d).forEach(([u,f])=>{s.includes(u.toLowerCase())&&o.set(u,f)})}}if(ZA.hasStandardBrowserEnv&&(i&&rr.isFunction(i)&&(i=i(t)),i||i!==!1&&rR_(t.url))){let d=n&&a&&iR_.read(a);d&&o.set(n,d)}return t};var FYM=typeof XMLHttpRequest<"u",aR_=FYM&&function(e){return new Promise(function(r,i){let n=H7o(e),a=n.data,o=XM.from(n.headers).normalize(),{responseType:c,onUploadProgress:d,onDownloadProgress:s}=n,u,f,p,_,h;function y(){_&&_(),h&&h(),n.cancelToken&&n.cancelToken.unsubscribe(u),n.signal&&n.signal.removeEventListener("abort",u)}let b=new XMLHttpRequest;b.open(n.method.toUpperCase(),n.url,!0),b.timeout=n.timeout;function v(){if(!b)return;let A=XM.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),m={data:!c||c==="text"||c==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:A,config:e,request:b};QJt(function(M){r(M),y()},function(M){i(M),y()},m),b=null}"onloadend"in b?b.onloadend=v:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(v)},b.onabort=function(){b&&(i(new Da("Request aborted",Da.ECONNABORTED,e,b)),b=null)},b.onerror=function(g){let m=g&&g.message?g.message:"Network Error",j=new Da(m,Da.ERR_NETWORK,e,b);j.event=g||null,i(j),b=null},b.ontimeout=function(){let g=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",m=n.transitional||hkn;n.timeoutErrorMessage&&(g=n.timeoutErrorMessage),i(new Da(g,m.clarifyTimeoutError?Da.ETIMEDOUT:Da.ECONNABORTED,e,b)),b=null},a===void 0&&o.setContentType(null),"setRequestHeader"in b&&rr.forEach(o.toJSON(),function(g,m){b.setRequestHeader(m,g)}),rr.isUndefined(n.withCredentials)||(b.withCredentials=!!n.withCredentials),c&&c!=="json"&&(b.responseType=n.responseType),s&&([p,h]=AFi(s,!0),b.addEventListener("progress",p)),d&&b.upload&&([f,_]=AFi(d),b.upload.addEventListener("progress",f),b.upload.addEventListener("loadend",_)),(n.cancelToken||n.signal)&&(u=A=>{b&&(i(!A||A.type?new Zbe(null,e,b):A),b.abort(),b=null)},n.cancelToken&&n.cancelToken.subscribe(u),n.signal&&(n.signal.aborted?u():n.signal.addEventListener("abort",u)));let O=ZWa(n.url);if(O&&ZA.protocols.indexOf(O)===-1){i(new Da("Unsupported protocol "+O+":",Da.ERR_BAD_REQUEST,e));return}b.send(a||null)})};var QYM=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,c();let u=s instanceof Error?s:this.reason;i.abort(u instanceof Da?u:new Zbe(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new Da(`timeout ${t} of ms exceeded`,Da.ETIMEDOUT))},t),c=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>rr.asap(c),d}},oR_=QYM;var UYM=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let i=0,n;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},LYM=async function*(e,t){for await(let r of VYM(e))yield*UYM(r,t)},VYM=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)break;yield i}}finally{await t.cancel()}},sEc=(e,t,r,i)=>{let n=LYM(e,t),a=0,o,c=d=>{o||(o=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:u}=await n.next();if(s){c(),d.close();return}let f=u.byteLength;if(r){let p=a+=f;r(p)}d.enqueue(new Uint8Array(u))}catch(s){throw c(s),s}},cancel(d){return c(d),n.return()}},{highWaterMark:2})};var uR_=64*1024,{isFunction:x7o}=rr,WYM=(({Request:e,Response:t})=>({Request:e,Response:t}))(rr.global),{ReadableStream:sR_,TextEncoder:cR_}=rr.global,lR_=(e,...t)=>{try{return!!e(...t)}catch{return!1}},GYM=e=>{e=rr.merge.call({skipUndefined:!0},WYM,e);let{fetch:t,Request:r,Response:i}=e,n=t?x7o(t):typeof fetch=="function",a=x7o(r),o=x7o(i);if(!n)return!1;let c=n&&x7o(sR_),d=n&&(typeof cR_=="function"?(h=>y=>h.encode(y))(new cR_):async h=>new Uint8Array(await new r(h).arrayBuffer())),s=a&&c&&lR_(()=>{let h=!1,y=new r(ZA.origin,{body:new sR_,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!y}),u=o&&c&&lR_(()=>rr.isReadableStream(new i("").body)),f={stream:u&&(h=>h.body)};n&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!f[h]&&(f[h]=(y,b)=>{let v=y&&y[h];if(v)return v.call(y);throw new Da(`Response type '${h}' is not supported`,Da.ERR_NOT_SUPPORT,b)})});let p=async h=>{if(h==null)return 0;if(rr.isBlob(h))return h.size;if(rr.isSpecCompliantForm(h))return(await new r(ZA.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(rr.isArrayBufferView(h)||rr.isArrayBuffer(h))return h.byteLength;if(rr.isURLSearchParams(h)&&(h=h+""),rr.isString(h))return(await d(h)).byteLength},_=async(h,y)=>{let b=rr.toFiniteNumber(h.getContentLength());return b??p(y)};return async h=>{let{url:y,method:b,data:v,signal:O,cancelToken:A,timeout:g,onDownloadProgress:m,onUploadProgress:j,responseType:M,headers:w,withCredentials:D="same-origin",fetchOptions:B}=H7o(h),z=t||fetch;M=M?(M+"").toLowerCase():"text";let F=oR_([O,A&&A.toAbortSignal()],g),q=null,N=F&&F.unsubscribe&&(()=>{F.unsubscribe()}),Q;try{if(j&&s&&b!=="get"&&b!=="head"&&(Q=await _(w,v))!==0){let G=new r(y,{method:"POST",body:v,duplex:"half"}),Ee;if(rr.isFormData(v)&&(Ee=G.headers.get("content-type"))&&w.setContentType(Ee),G.body){let[se,Ae]=gkn(Q,AFi(Okn(j)));v=sEc(G.body,uR_,se,Ae)}}rr.isString(D)||(D=D?"include":"omit");let x=a&&"credentials"in r.prototype,ee={...B,signal:F,method:b.toUpperCase(),headers:w.normalize().toJSON(),body:v,duplex:"half",credentials:x?D:void 0};q=a&&new r(y,ee);let ve=await(a?z(q,B):z(y,ee)),be=u&&(M==="stream"||M==="response");if(u&&(m||be&&N)){let G={};["status","statusText","headers"].forEach(Fe=>{G[Fe]=ve[Fe]});let Ee=rr.toFiniteNumber(ve.headers.get("content-length")),[se,Ae]=m&&gkn(Ee,AFi(Okn(m),!0))||[];ve=new i(sEc(ve.body,uR_,se,()=>{Ae&&Ae(),N&&N()}),G)}M=M||"text";let H=await f[rr.findKey(f,M)||"text"](ve,h);return!be&&N&&N(),await new Promise((G,Ee)=>{QJt(G,Ee,{data:H,headers:XM.from(ve.headers),status:ve.status,statusText:ve.statusText,config:h,request:q})})}catch(x){throw N&&N(),x&&x.name==="TypeError"&&/Load failed|fetch/i.test(x.message)?Object.assign(new Da("Network Error",Da.ERR_NETWORK,h,q),{cause:x.cause||x}):Da.from(x,x&&x.code,h,q)}}},HYM=new Map,cEc=e=>{let t=e?e.env:{},{fetch:r,Request:i,Response:n}=t,a=[i,n,r],o=a.length,c=o,d,s,u=HYM;for(;c--;)d=a[c],s=u.get(d),s===void 0&&u.set(d,s=c?new Map:GYM(t)),u=s;return s},lS9=cEc();var lEc={http:tR_,xhr:aR_,fetch:{get:cEc}};rr.forEach(lEc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var fR_=e=>`- ${e}`,KYM=e=>rr.isFunction(e)||e===null||e===!1,K7o={getAdapter:(e,t)=>{e=rr.isArray(e)?e:[e];let{length:r}=e,i,n,a={};for(let o=0;o<r;o++){i=e[o];let c;if(n=i,!KYM(i)&&(n=lEc[(c=String(i)).toLowerCase()],n===void 0))throw new Da(`Unknown adapter '${c}'`);if(n&&(rr.isFunction(n)||(n=n.get(t))))break;a[c||"#"+o]=n}if(!n){let o=Object.entries(a).map(([d,s])=>`adapter ${d} `+(s===!1?"is not supported by the environment":"is not available in the build")),c=r?o.length>1?`since :
@@ -1392,7 +1392,7 @@ ${g}${O}${m}${dna}`});function Lsu({message:e,error:t,logger:r,logLevel:i=oc.Err
1392
1392
  Run ${qt.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1393
1393
  Run ${qt.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),mkn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function H4c({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!irh(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,d)=>c.generatorName.localeCompare(d.generatorName)||c.currentVersion.localeCompare(d.currentVersion));for(let c of o)n+=`
1394
1394
  ${await zID(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+qt.dim(c.currentVersion)+qt.reset(" \u2192 ")+qt.green(c.latestVersion);return n+=`
1395
- `,i?mkn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function zID(e){let r=await new rrh.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function NID({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await arh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=LGi(u.name,f),_=await BVt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await arh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let f=LGi(s.name,u),p=await BVt({generatorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function arh({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await xbe({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?sN(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function orh(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let d=T$(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Hsu({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await NID({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...orh(s,d,t.logger));else o.push(...orh(c.versions,void 0,t.logger))}return o}var pHa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var yna=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var x4c=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),urh=typeof globalThis.AbortController=="function",srh=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",crh=typeof globalThis.ReadableStream=="function",lrh=typeof globalThis.FormData=="function",xsu=["get","post","put","patch","head","delete"],FID=()=>{};FID();var frh={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Ksu=2147483647,drh=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,Jsu=Symbol("stop"),prh={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},_rh={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var QID=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=drh,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},hrh=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},yrh=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(hrh(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},brh=(e,t,r)=>{if(!e.body)return e;let i=QID(r??e.body);return new Request(e,{duplex:"half",body:hrh(e.body,i,t)})};var bna=e=>e!==null&&typeof e=="object";var _Ha=(...e)=>{for(let t of e)if((!bna(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return $4c({},...e)},K4c=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function $su(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:$4c(e[r]??[],t[r]??[])}var J4c=(e={},t={})=>({beforeRequest:$su(e,t,"beforeRequest"),beforeRetry:$su(e,t,"beforeRetry"),afterResponse:$su(e,t,"afterResponse"),beforeError:$su(e,t,"beforeError")}),$4c=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(bna(n)){for(let[a,o]of Object.entries(n))bna(o)&&a in t&&(o=$4c(t[a],o)),t={...t,[a]:o};bna(n.hooks)&&(i=J4c(i,n.hooks),t.hooks=i),bna(n.headers)&&(r=K4c(r,n.headers),t.headers=r)}return t};var grh=e=>xsu.includes(e)?e.toUpperCase():e,UID=["get","put","head","delete","options","trace"],LID=[408,413,429,500,502,503,504],VID=[413,429,503],vrh={limit:2,methods:UID,statusCodes:LID,afterStatusCodes:VID,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Orh=(e={})=>{if(typeof e=="number")return{...vrh,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...vrh,...e}};async function Y4c(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new yna(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function X4c(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Arh=(e,t)=>{let r={};for(let i in t)!(i in _rh)&&!(i in prh)&&!(i in e)&&(r[i]=t[i]);return r},mrh=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var hHa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Ksu)throw new RangeError(`The \`timeout\` option cannot be greater than ${Ksu}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new pHa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!crh)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return yrh(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,d=[];c&&!c.bodyUsed&&d.push(c.body?.cancel()),i.request.bodyUsed||d.push(i.request.body?.cancel()),await Promise.all(d)});for(let[c,d]of Object.entries(frh))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:K4c(this._input.headers,r.headers),hooks:J4c({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:grh(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:Orh(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(urh&&srh){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(x4c&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),mrh(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(lrh&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!x4c)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=brh(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof yna)throw t;if(t instanceof pHa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),Ksu);if(this._retryCount<1)throw r;await X4c(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===Jsu)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=Arh(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):Y4c(this._originalRequest,t,this.abortController,this._options)}};var Z4c=e=>{let t=(r,i)=>hHa.create(r,_Ha(e,i));for(let r of xsu)t[r]=(i,n)=>hHa.create(i,_Ha(e,n,{method:r}));return t.create=r=>Z4c(_Ha(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Z4c(_Ha(e,r))),t.stop=Jsu,t},WID=Z4c(),Prh=WID;var xrh=ce(Hrh(),1);function iLc(e){let t=(0,xrh.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Uih=ce(Qih(),1),Lih=ce(XK(),1),yLc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},bLc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function vLc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??iLc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,Uih.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await Prh(o,{headers:d,keepalive:!0}).json()}catch(f){throw f?.response?.status===404?new yLc(e):f}if(t.allVersions)return s;let u=new bLc(e,r);if(s["dist-tags"][r]){let{time:f}=s;s=s.versions[s["dist-tags"][r]],s.time=f}else if(r){let f=!!s.versions[r];if(i&&!f)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!f){let _=Object.keys(s.versions);if(r=Lih.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function AHa(e,t){let{version:r}=await vLc(e.toLowerCase(),t);return r}async function CKi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:AHa(e.packageName,{version:t?"prerelease":"latest"})}var Vih=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],ucu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=oc.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Gsu(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.42.4"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${qt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new WS}failWithoutThrowing(t,r){this.didSucceed=!1,Lsu({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await fkn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await nrh({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1395
+ `,i?mkn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function zID(e){let r=await new rrh.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function NID({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await arh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=LGi(u.name,f),_=await BVt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await arh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let f=LGi(s.name,u),p=await BVt({generatorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function arh({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await xbe({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?sN(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function orh(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let d=T$(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Hsu({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await NID({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...orh(s,d,t.logger));else o.push(...orh(c.versions,void 0,t.logger))}return o}var pHa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var yna=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var x4c=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),urh=typeof globalThis.AbortController=="function",srh=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",crh=typeof globalThis.ReadableStream=="function",lrh=typeof globalThis.FormData=="function",xsu=["get","post","put","patch","head","delete"],FID=()=>{};FID();var frh={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Ksu=2147483647,drh=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,Jsu=Symbol("stop"),prh={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},_rh={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var QID=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=drh,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},hrh=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},yrh=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(hrh(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},brh=(e,t,r)=>{if(!e.body)return e;let i=QID(r??e.body);return new Request(e,{duplex:"half",body:hrh(e.body,i,t)})};var bna=e=>e!==null&&typeof e=="object";var _Ha=(...e)=>{for(let t of e)if((!bna(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return $4c({},...e)},K4c=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function $su(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:$4c(e[r]??[],t[r]??[])}var J4c=(e={},t={})=>({beforeRequest:$su(e,t,"beforeRequest"),beforeRetry:$su(e,t,"beforeRetry"),afterResponse:$su(e,t,"afterResponse"),beforeError:$su(e,t,"beforeError")}),$4c=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(bna(n)){for(let[a,o]of Object.entries(n))bna(o)&&a in t&&(o=$4c(t[a],o)),t={...t,[a]:o};bna(n.hooks)&&(i=J4c(i,n.hooks),t.hooks=i),bna(n.headers)&&(r=K4c(r,n.headers),t.headers=r)}return t};var grh=e=>xsu.includes(e)?e.toUpperCase():e,UID=["get","put","head","delete","options","trace"],LID=[408,413,429,500,502,503,504],VID=[413,429,503],vrh={limit:2,methods:UID,statusCodes:LID,afterStatusCodes:VID,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Orh=(e={})=>{if(typeof e=="number")return{...vrh,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...vrh,...e}};async function Y4c(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new yna(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function X4c(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Arh=(e,t)=>{let r={};for(let i in t)!(i in _rh)&&!(i in prh)&&!(i in e)&&(r[i]=t[i]);return r},mrh=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var hHa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Ksu)throw new RangeError(`The \`timeout\` option cannot be greater than ${Ksu}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new pHa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!crh)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return yrh(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,d=[];c&&!c.bodyUsed&&d.push(c.body?.cancel()),i.request.bodyUsed||d.push(i.request.body?.cancel()),await Promise.all(d)});for(let[c,d]of Object.entries(frh))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:K4c(this._input.headers,r.headers),hooks:J4c({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:grh(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:Orh(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(urh&&srh){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(x4c&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),mrh(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(lrh&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!x4c)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=brh(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof yna)throw t;if(t instanceof pHa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),Ksu);if(this._retryCount<1)throw r;await X4c(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===Jsu)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=Arh(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):Y4c(this._originalRequest,t,this.abortController,this._options)}};var Z4c=e=>{let t=(r,i)=>hHa.create(r,_Ha(e,i));for(let r of xsu)t[r]=(i,n)=>hHa.create(i,_Ha(e,n,{method:r}));return t.create=r=>Z4c(_Ha(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Z4c(_Ha(e,r))),t.stop=Jsu,t},WID=Z4c(),Prh=WID;var xrh=ce(Hrh(),1);function iLc(e){let t=(0,xrh.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Uih=ce(Qih(),1),Lih=ce(XK(),1),yLc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},bLc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function vLc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??iLc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,Uih.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await Prh(o,{headers:d,keepalive:!0}).json()}catch(f){throw f?.response?.status===404?new yLc(e):f}if(t.allVersions)return s;let u=new bLc(e,r);if(s["dist-tags"][r]){let{time:f}=s;s=s.versions[s["dist-tags"][r]],s.time=f}else if(r){let f=!!s.versions[r];if(i&&!f)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!f){let _=Object.keys(s.versions);if(r=Lih.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function AHa(e,t){let{version:r}=await vLc(e.toLowerCase(),t);return r}async function CKi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:AHa(e.packageName,{version:t?"prerelease":"latest"})}var Vih=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],ucu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=oc.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Gsu(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.43.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${qt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new WS}failWithoutThrowing(t,r){this.didSucceed=!1,Lsu({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await fkn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await nrh({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1396
1396
  `)||(r+=`
1397
1397
  `),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=O2s(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new uHa(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new WS}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await fkn()).sendEvent(t)}logger=SHt((t,...r)=>this.log(t,...r));stderr=SHt((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=Wih(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Wih(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=Vih[this.numTasks++%Vih.length],o=qt.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===bw.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let i=t.filter(n=>cGi.indexOf(n.level)>=cGi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===oc.Debug,stderr:r})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await CKi({cliEnvironment:this.environment,includePreReleases:t}),i=T$(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await Hsu({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await q4c({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:qt.yellow("?"),style:{answer:n=>qt.cyan(n),message:n=>qt.bold(n),highlight:n=>qt.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
1398
1398
  Cancelled by user.`),new WS):i}}async getInput(t){return await D4c({message:t.message,default:t.default})}};function Wih(e){return`[${e}]:`}var q3t=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};function scu(e,t,r,i){if(typeof r!="function")throw new Error("method for before hook must be a function");return i||(i={}),Array.isArray(t)?t.reverse().reduce((n,a)=>scu.bind(null,e,a,n,i),r)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((n,a)=>a.hook.bind(null,n,i),r)():r(i))}function Gih(e,t,r,i){let n=i;e.registry[r]||(e.registry[r]=[]),t==="before"&&(i=(a,o)=>Promise.resolve().then(n.bind(null,o)).then(a.bind(null,o))),t==="after"&&(i=(a,o)=>{let c;return Promise.resolve().then(a.bind(null,o)).then(d=>(c=d,n(c,o))).then(()=>c)}),t==="error"&&(i=(a,o)=>Promise.resolve().then(a.bind(null,o)).catch(c=>n(c,o))),e.registry[r].push({hook:i,orig:n})}function Hih(e,t,r){if(!e.registry[t])return;let i=e.registry[t].map(n=>n.orig).indexOf(r);i!==-1&&e.registry[t].splice(i,1)}var xih=Function.bind,Kih=xih.bind(xih);function Jih(e,t,r){let i=Kih(Hih,null).apply(null,r?[t,r]:[t]);e.api={remove:i},e.remove=i,["before","error","after","wrap"].forEach(n=>{let a=r?[t,n,r]:[t,n];e[n]=e.api[n]=Kih(Gih,null).apply(null,a)})}function $CD(){let e=Symbol("Singular"),t={registry:{}},r=scu.bind(null,t,e);return Jih(r,t,e),r}function YCD(){let e={registry:{}},t=scu.bind(null,e);return Jih(t,e),t}var $ih={Singular:$CD,Collection:YCD};var XCD="0.0.0-development",ZCD=`octokit-endpoint.js/${XCD} ${pN()}`,kCD={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":ZCD},mediaType:{format:""}};function eqD(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function tqD(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}function Zih(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(i=>{tqD(t[i])?i in e?r[i]=Zih(e[i],t[i]):Object.assign(r,{[i]:t[i]}):Object.assign(r,{[i]:t[i]})}),r}function Yih(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function OLc(e,t,r){if(typeof t=="string"){let[n,a]=t.split(" ");r=Object.assign(a?{method:n,url:a}:{url:n},r)}else r=Object.assign({},t);r.headers=eqD(r.headers),Yih(r),Yih(r.headers);let i=Zih(e||{},r);return r.url==="/graphql"&&(e&&e.mediaType.previews?.length&&(i.mediaType.previews=e.mediaType.previews.filter(n=>!i.mediaType.previews.includes(n)).concat(i.mediaType.previews)),i.mediaType.previews=(i.mediaType.previews||[]).map(n=>n.replace(/-preview/,""))),i}function rqD(e,t){let r=/\?/.test(e)?"&":"?",i=Object.keys(t);return i.length===0?e:e+r+i.map(n=>n==="q"?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${n}=${encodeURIComponent(t[n])}`).join("&")}var iqD=/\{[^{}}]+\}/g;function nqD(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function aqD(e){let t=e.match(iqD);return t?t.map(nqD).reduce((r,i)=>r.concat(i),[]):[]}function Xih(e,t){let r={__proto__:null};for(let i of Object.keys(e))t.indexOf(i)===-1&&(r[i]=e[i]);return r}function kih(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(t){return/%[0-9A-Fa-f]/.test(t)||(t=encodeURI(t).replace(/%5B/g,"[").replace(/%5D/g,"]")),t}).join("")}function wna(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function mHa(e,t,r){return t=e==="+"||e==="#"?kih(t):wna(t),r?wna(r)+"="+t:t}function jna(e){return e!=null}function gLc(e){return e===";"||e==="&"||e==="?"}function oqD(e,t,r,i){var n=e[r],a=[];if(jna(n)&&n!=="")if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")n=n.toString(),i&&i!=="*"&&(n=n.substring(0,parseInt(i,10))),a.push(mHa(t,n,gLc(t)?r:""));else if(i==="*")Array.isArray(n)?n.filter(jna).forEach(function(o){a.push(mHa(t,o,gLc(t)?r:""))}):Object.keys(n).forEach(function(o){jna(n[o])&&a.push(mHa(t,n[o],o))});else{let o=[];Array.isArray(n)?n.filter(jna).forEach(function(c){o.push(mHa(t,c))}):Object.keys(n).forEach(function(c){jna(n[c])&&(o.push(wna(c)),o.push(mHa(t,n[c].toString())))}),gLc(t)?a.push(wna(r)+"="+o.join(",")):o.length!==0&&a.push(o.join(","))}else t===";"?jna(n)&&a.push(wna(r)):n===""&&(t==="&"||t==="?")?a.push(wna(r)+"="):n===""&&a.push("");return a}function uqD(e){return{expand:sqD.bind(null,e)}}function sqD(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(i,n,a){if(n){let c="",d=[];if(r.indexOf(n.charAt(0))!==-1&&(c=n.charAt(0),n=n.substr(1)),n.split(/,/g).forEach(function(s){var u=/([^:\*]*)(?::(\d+)|(\*))?/.exec(s);d.push(oqD(t,c,u[1],u[2]||u[3]))}),c&&c!=="+"){var o=",";return c==="?"?o="&":c!=="#"&&(o=c),(d.length!==0?c:"")+d.join(o)}else return d.join(",")}else return kih(a)}),e==="/"?e:e.replace(/\/$/,"")}function enh(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),i=Object.assign({},e.headers),n,a=Xih(e,["method","baseUrl","url","headers","request","mediaType"]),o=aqD(r);r=uqD(r).expand(a),/^http/.test(r)||(r=e.baseUrl+r);let c=Object.keys(e).filter(u=>o.includes(u)).concat("baseUrl"),d=Xih(a,c);if(!/application\/octet-stream/i.test(i.accept)&&(e.mediaType.format&&(i.accept=i.accept.split(/,/).map(u=>u.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),r.endsWith("/graphql")&&e.mediaType.previews?.length)){let u=i.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];i.accept=u.concat(e.mediaType.previews).map(f=>{let p=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${f}-preview${p}`}).join(",")}return["GET","HEAD"].includes(t)?r=rqD(r,d):"data"in d?n=d.data:Object.keys(d).length&&(n=d),!i["content-type"]&&typeof n<"u"&&(i["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(t)&&typeof n>"u"&&(n=""),Object.assign({method:t,url:r,headers:i},typeof n<"u"?{body:n}:null,e.request?{request:e.request}:null)}function cqD(e,t,r){return enh(OLc(e,t,r))}function tnh(e,t){let r=OLc(e,t),i=cqD.bind(null,r);return Object.assign(i,{DEFAULTS:r,defaults:tnh.bind(null,r),merge:OLc.bind(null,r),parse:enh})}var rnh=tnh(null,kCD);var snh=ce(onh(),1);var T3t=class extends Error{name;status;request;response;constructor(t,r,i){super(t),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0),"response"in i&&(this.response=i.response);let n=Object.assign({},i.request);i.request.headers.authorization&&(n.headers=Object.assign({},i.request.headers,{authorization:i.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),n.url=n.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=n}};var lqD="10.0.6",fqD={headers:{"user-agent":`octokit-request.js/${lqD} ${pN()}`}};function dqD(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}async function unh(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");let r=e.request?.log||console,i=e.request?.parseSuccessResponseBody!==!1,n=dqD(e.body)||Array.isArray(e.body)?JSON.stringify(e.body):e.body,a=Object.fromEntries(Object.entries(e.headers).map(([f,p])=>[f,String(p)])),o;try{o=await t(e.url,{method:e.method,body:n,redirect:e.request?.redirect,headers:a,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(f){let p="Unknown Error";if(f instanceof Error){if(f.name==="AbortError")throw f.status=500,f;p=f.message,f.name==="TypeError"&&"cause"in f&&(f.cause instanceof Error?p=f.cause.message:typeof f.cause=="string"&&(p=f.cause))}let _=new T3t(p,500,{request:e});throw _.cause=f,_}let c=o.status,d=o.url,s={};for(let[f,p]of o.headers)s[f]=p;let u={url:d,status:c,headers:s,data:""};if("deprecation"in s){let f=s.link&&s.link.match(/<([^<>]+)>; rel="deprecation"/),p=f&&f.pop();r.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${s.sunset}${p?`. See ${p}`:""}`)}if(c===204||c===205)return u;if(e.method==="HEAD"){if(c<400)return u;throw new T3t(o.statusText,c,{response:u,request:e})}if(c===304)throw u.data=await ALc(o),new T3t("Not modified",c,{response:u,request:e});if(c>=400)throw u.data=await ALc(o),new T3t(_qD(u.data),c,{response:u,request:e});return u.data=i?await ALc(o):o.body,u}async function ALc(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(()=>"");let r=(0,snh.safeParse)(t);if(pqD(r)){let i="";try{return i=await e.text(),JSON.parse(i)}catch{return i}}else return r.type.startsWith("text/")||r.parameters.charset?.toLowerCase()==="utf-8"?e.text().catch(()=>""):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function pqD(e){return e.type==="application/json"||e.type==="application/scim+json"}function _qD(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return"Unknown error";if("message"in e){let t="documentation_url"in e?` - ${e.documentation_url}`:"";return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(r=>JSON.stringify(r)).join(", ")}${t}`:`${e.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}function mLc(e,t){let r=e.defaults(t);return Object.assign(function(n,a){let o=r.merge(n,a);if(!o.request||!o.request.hook)return unh(r.parse(o));let c=(d,s)=>unh(r.parse(r.merge(d,s)));return Object.assign(c,{endpoint:r,defaults:mLc.bind(null,r)}),o.request.hook(c,o)},{endpoint:r,defaults:mLc.bind(null,r)})}var OA=mLc(rnh,fqD);var hqD="0.0.0-development";function yqD(e){return`Request failed due to following response errors:
@@ -1832,7 +1832,7 @@ The generated documentation will replace this placeholder page with complete API
1832
1832
  - Class and function references
1833
1833
  - Type annotations and signatures
1834
1834
  - Docstring content
1835
- `;return this.parsedDocsConfig.pages[He.of(o)]=d,{id:this.#e.get(c),type:"page",slug:a.get(),title:i,icon:void 0,hidden:!1,viewers:void 0,orphaned:void 0,pageId:c,authed:void 0,noindex:!0,featureFlags:void 0,availability:void 0}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Nt.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??UE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Nt.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??UE(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,f=n||r.hidden;return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:f,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:d,item:p,parentSlug:s,hideChildren:f,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return wln(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new Ovn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Nt.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??UE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??UE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):oG.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(ds),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:oG.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return wln(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:oG.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function fdB(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${oH(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function ddB(e){switch(e){case"beta":return Nt.V1.NavigationV1Availability.Beta;case"deprecated":return Nt.V1.NavigationV1Availability.Deprecated;case"ga":return Nt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Nt.V1.NavigationV1Availability.Stable;default:vt(e)}}async function uL(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof tS?t:null))).filter(ds)}async function Axc(e,t,r){if(e instanceof CEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof tS))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return aH({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var Ys={};Zt(Ys,{AlgoliaSearchIndex:()=>JMh,ApiDefinitionId:()=>hDh,ApiId:()=>gDh,Availability:()=>TDh,DocsConfigId:()=>ODh,EndpointId:()=>mDh,EndpointPathLiteral:()=>CDh,EnvironmentId:()=>ADh,FileId:()=>SDh,HttpMethod:()=>qDh,IndexSegmentId:()=>$Mh,JqString:()=>DDh,OrgId:()=>bDh,PageId:()=>EDh,PayloadLocation:()=>uBh,PropertyKey:()=>BDh,PullRequestState:()=>rBh,RoleId:()=>IDh,TokenId:()=>vDh,TypeId:()=>wDh,Url:()=>MDh,VersionId:()=>yDh,WebSocketId:()=>PDh,WebhookId:()=>jDh,algolia:()=>mxc,api:()=>Cxc,commons:()=>qxc,diff:()=>RDh,docs:()=>Vxc,generators:()=>Gxc,git:()=>Hxc,navigation:()=>Jxc,sdks:()=>Yxc,snippets:()=>aBh,snippetsFactory:()=>oBh,templates:()=>Xxc,tokens:()=>sBh});var mxc={};Zt(mxc,{AlgoliaSearchIndex:()=>JMh,IndexSegmentId:()=>$Mh});function JMh(e){return e}function $Mh(e){return e}var Cxc={};Zt(Cxc,{latest:()=>wxc,v1:()=>Ixc});var wxc={};Zt(wxc,{AuthSchemeId:()=>YMh,WebhookHttpMethod:()=>eDh,auth:()=>Pxc,commons:()=>XMh,endpoint:()=>ZMh,type_:()=>kMh,webhook:()=>jxc,websocket:()=>tDh});var Pxc={};Zt(Pxc,{AuthSchemeId:()=>YMh});function YMh(e){return e}var XMh={};var ZMh={};var kMh={};var jxc={};Zt(jxc,{WebhookHttpMethod:()=>eDh});var eDh={Get:"GET",Post:"POST"};var tDh={};var Ixc={};Zt(Ixc,{SubpackageId:()=>fDh,WebSocketMessageId:()=>dDh,WebSocketMessageOrigin:()=>pDh,WebhookHttpMethod:()=>_Dh,commons:()=>Bxc,db:()=>Exc,read:()=>Mxc,register:()=>Dxc});var Exc={};Zt(Exc,{endpoint:()=>rDh});var rDh={};var Mxc={};Zt(Mxc,{SupportedLanguage:()=>iDh,endpoint:()=>Sxc,type_:()=>nDh,webhook:()=>aDh,websocket:()=>oDh});var Sxc={};Zt(Sxc,{SupportedLanguage:()=>iDh});var iDh={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var nDh={};var aDh={};var oDh={};var Dxc={};Zt(Dxc,{SourceId:()=>pdB,endpoint:()=>uDh,type_:()=>sDh,webhook:()=>cDh,websocket:()=>lDh});var uDh={};var sDh={};var cDh={};var lDh={};function pdB(e){return e}var Bxc={};Zt(Bxc,{SubpackageId:()=>fDh,WebSocketMessageId:()=>dDh,WebSocketMessageOrigin:()=>pDh,WebhookHttpMethod:()=>_Dh});function fDh(e){return e}function dDh(e){return e}var pDh={Client:"client",Server:"server"};var _Dh={Get:"GET",Post:"POST"};var qxc={};Zt(qxc,{ApiDefinitionId:()=>hDh,ApiId:()=>gDh,Availability:()=>TDh,DocsConfigId:()=>ODh,EndpointId:()=>mDh,EndpointPathLiteral:()=>CDh,EnvironmentId:()=>ADh,FileId:()=>SDh,HttpMethod:()=>qDh,JqString:()=>DDh,OrgId:()=>bDh,PageId:()=>EDh,PropertyKey:()=>BDh,RoleId:()=>IDh,TokenId:()=>vDh,TypeId:()=>wDh,Url:()=>MDh,VersionId:()=>yDh,WebSocketId:()=>PDh,WebhookId:()=>jDh});function hDh(e){return e}function yDh(e){return e}function bDh(e){return e}function vDh(e){return e}function gDh(e){return e}function ODh(e){return e}function ADh(e){return e}function mDh(e){return e}function PDh(e){return e}function jDh(e){return e}function wDh(e){return e}function EDh(e){return e}function SDh(e){return e}function MDh(e){return e}function DDh(e){return e}function BDh(e){return e}function IDh(e){return e}function CDh(e){return e}var qDh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var TDh={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var RDh={};var Vxc={};Zt(Vxc,{latest:()=>zxc,v1:()=>Uxc,v2:()=>Lxc});var zxc={};Zt(zxc,{Layout:()=>NDh,MdxEngine:()=>_dB,TwitterCardSetting:()=>FDh,commons:()=>zDh,frontmatter:()=>Txc,seo:()=>Rxc});var _dB={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var zDh={};var Txc={};Zt(Txc,{Layout:()=>NDh});var NDh={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var Rxc={};Zt(Rxc,{TwitterCardSetting:()=>FDh});var FDh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Uxc={};Zt(Uxc,{commons:()=>Qxc,db:()=>QDh,read:()=>UDh,write:()=>Nxc});var QDh={};var UDh={};var Nxc={};Zt(Nxc,{DocsRegistrationId:()=>ydB,FilePath:()=>hdB});function hdB(e){return e}function ydB(e){return e}var Qxc={};Zt(Qxc,{ContentAlignment:()=>GDh,FontDisplay:()=>$Dh,FontStyle:()=>JDh,HeaderPosition:()=>HDh,JsScriptStrategy:()=>KDh,ProgrammingLanguage:()=>LDh,SearchbarPlacement:()=>VDh,TabsPlacement:()=>WDh,TwitterCardSetting:()=>xDh,commons:()=>Fxc});var Fxc={};Zt(Fxc,{ContentAlignment:()=>GDh,FontDisplay:()=>$Dh,FontStyle:()=>JDh,HeaderPosition:()=>HDh,JsScriptStrategy:()=>KDh,ProgrammingLanguage:()=>LDh,SearchbarPlacement:()=>VDh,TabsPlacement:()=>WDh,TwitterCardSetting:()=>xDh});var LDh={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var VDh={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var WDh={Header:"HEADER",Sidebar:"SIDEBAR"};var GDh={Center:"CENTER",Left:"LEFT"};var HDh={Fixed:"FIXED",Absolute:"ABSOLUTE"};var xDh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var KDh={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var JDh={Normal:"normal",Italic:"italic"};var $Dh={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Lxc={};Zt(Lxc,{read:()=>YDh,write:()=>XDh});var YDh={};var XDh={};var Gxc={};Zt(Gxc,{ChangelogEntryType:()=>kDh,GeneratorId:()=>bdB,GeneratorLanguage:()=>vdB,ReleaseType:()=>eBh,cli:()=>ZDh,commons:()=>Wxc,versions:()=>tBh});var ZDh={};var Wxc={};Zt(Wxc,{ChangelogEntryType:()=>kDh,ReleaseType:()=>eBh});var kDh={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var eBh={Ga:"GA",Rc:"RC"};var tBh={};function bdB(e){return e}var vdB={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Hxc={};Zt(Hxc,{PullRequestState:()=>rBh});var rBh={Open:"open",Closed:"closed",Merged:"merged"};var Jxc={};Zt(Jxc,{latest:()=>xxc,v1:()=>Kxc});var xxc={};Zt(xxc,{NodeId:()=>AdB,ProductId:()=>mdB,Slug:()=>gdB,TabId:()=>OdB});function gdB(e){return e}function OdB(e){return e}function AdB(e){return e}function mdB(e){return e}var Kxc={};Zt(Kxc,{NavigationV1Availability:()=>SdB,NodeId:()=>wdB,ProductId:()=>EdB,Slug:()=>PdB,TabId:()=>jdB});function PdB(e){return e}function jdB(e){return e}function wdB(e){return e}function EdB(e){return e}var SdB={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Yxc={};Zt(Yxc,{Language:()=>iBh,VersionBump:()=>nBh,versions:()=>$xc});var $xc={};Zt($xc,{Language:()=>iBh,VersionBump:()=>nBh});var iBh={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var nBh={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var aBh={};var oBh={};var Xxc={};Zt(Xxc,{PayloadLocation:()=>uBh});var uBh={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var sBh={};var cOu=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function No(e){return e!=null}var lBh=ce(xFa(),1);var cBh=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function CYt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,lBh.default)(e,{special:cBh}).replace(/V\s(\d)/g,"V$1")}function fBh({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=Ys.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:CYt(a)},n.push(a)})}),r}var lOu=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function dBh(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var po=class extends lOu{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((o,c)=>o===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${dBh(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},oC=class extends po{},eY=class extends oC{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var pBh="x-fern-base-path",_Bh="x-fern-availability",fOu="x-fern-sdk-group-name",hBh="x-fern-global-headers",yBh="x-fern-sdk-method-name";var bBh="x-fern-webhook",vBh="x-fern-access-token-locator",gBh="x-fern-basic",OBh="x-fern-username-variable-name",ABh="x-fern-password-variable-name",mBh="x-fern-bearer",PBh="x-fern-token-variable-name",jBh="x-fern-header",wBh="x-fern-header-variable-name",EBh="x-fern-server-name",SBh="x-fern-examples";var dOu=class extends po{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[EBh]}convert(){if(this.serverName!=null)return this.serverName}};var pOu=class extends po{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new dOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:Ys.EnvironmentId(t),baseUrl:this.url}}};function l$i(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new pOu({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...o]}function zv(e){return typeof e=="object"&&No(e)&&"$ref"in e&&typeof e.$ref=="string"}function sL(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(zv(n)&&(n=sL(n,t,r)),n)}function _Ou(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return zv(r)?sL(r,t,void 0):r}var vIh=ce(HS());var hOu=class extends po{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[gBh];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var yOu=class extends po{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[ABh]}convert(){return this.passwordVariableName}};var bOu=class extends po{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[OBh]}convert(){return this.usernameVariableName}};var vOu=class extends po{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[mBh];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var gOu=class extends po{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[PBh]}convert(){return this.tokenVariableName}};function MBh(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var DBh="x-bearer-format",BBh="x-code-samples",IBh="x-codeSamples";var OOu=class extends po{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[DBh]}convert(){return this.bearerFormat}};var AOu=class extends po{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[jBh];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var mOu=class extends po{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[wBh]}convert(){return this.headerVariableName}};function CBh(e){return e.type==="apiKey"}var qua=class extends po{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){CBh(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new AOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new mOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new OOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function POu(e){return e}function jOu(e){return e==="__proto__"}function wOu(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Tua(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function RKa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(RKa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function EOu(e){if(Array.isArray(e))return e.map(Tua);if(typeof e=="symbol")return[e];e=RKa(e);let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(n),n=""):n+=c:c==="["?(o=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function zKa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(jOu(t))return r;let i=e[t];return i===void 0?wOu(t)?zKa(e,EOu(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=Tua(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return MdB(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),jOu(t))return r;let i=e[t];return i===void 0?r:i}}}function MdB(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||jOu(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function qBh(e){return function(t){return zKa(t,e)}}function TBh(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function SOu(e){return e==null||typeof e!="object"&&typeof e!="function"}function Zxc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function eKc(e,t,r){return typeof r!="function"?eKc(e,t,()=>{}):kxc(e,t,function i(n,a,o,c,d,s){let u=r(n,a,o,c,d,s);return u!==void 0?!!u:kxc(n,a,i,s)},new Map)}function kxc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return DdB(e,t,r,i);case"function":return Object.keys(t).length>0?kxc(e,{...t},r,i):Zxc(e,t);default:return TBh(e)?typeof t=="string"?t==="":!0:Zxc(e,t)}}function DdB(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return RBh(e,t,r,i);if(t instanceof Map)return BdB(e,t,r,i);if(t instanceof Set)return IdB(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i?.has(t))return i.get(t)===e;i?.set(t,e);try{for(let a=0;a<n.length;a++){let o=n[a];if(!SOu(e)&&!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!r(e[o],t[o],o,e,t,i))return!1}return!0}finally{i?.delete(t)}}function BdB(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let o=e.get(n);if(r(o,a,n,e,t,i)===!1)return!1}return!0}function RBh(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let o=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],u=!1;if(r(s,o,a,e,t,i)&&(u=!0),u){n.add(d),c=!0;break}}if(!c)return!1}return!0}function IdB(e,t,r,i){return t.size===0?!0:e instanceof Set?RBh([...e],[...t],r,i):!1}function MOu(e,t){return eKc(e,t,()=>{})}function zBh(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function DOu(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}var NBh="[object RegExp]",BOu="[object String]",IOu="[object Number]",COu="[object Boolean]",qOu="[object Arguments]",FBh="[object Symbol]",QBh="[object Date]",UBh="[object Map]",LBh="[object Set]",VBh="[object Array]";var WBh="[object ArrayBuffer]",GBh="[object Object]";var HBh="[object DataView]",xBh="[object Uint8Array]",KBh="[object Uint8ClampedArray]",JBh="[object Uint16Array]",$Bh="[object Uint32Array]";var YBh="[object Int8Array]",XBh="[object Int16Array]",ZBh="[object Int32Array]";var kBh="[object Float32Array]",eIh="[object Float64Array]";function tIh(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function rIh(e,t){return f$i(e,void 0,e,new Map,t)}function f$i(e,t,r,i=new Map,n=void 0){let a=n?.(e,t,r,i);if(a!==void 0)return a;if(SOu(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){let o=new Array(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=f$i(e[c],c,r,i,n);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){let o=new Map;i.set(e,o);for(let[c,d]of e)o.set(c,f$i(d,c,r,i,n));return o}if(e instanceof Set){let o=new Set;i.set(e,o);for(let c of e)o.add(f$i(c,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(tIh(e)){let o=new(Object.getPrototypeOf(e)).constructor(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=f$i(e[c],c,r,i,n);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,o),l8t(o,e,r,i,n),o}if(typeof File<"u"&&e instanceof File){let o=new File([e],e.name,{type:e.type});return i.set(e,o),l8t(o,e,r,i,n),o}if(typeof Blob<"u"&&e instanceof Blob){let o=new Blob([e],{type:e.type});return i.set(e,o),l8t(o,e,r,i,n),o}if(e instanceof Error){let o=new e.constructor;return i.set(e,o),o.message=e.message,o.name=e.name,o.stack=e.stack,o.cause=e.cause,l8t(o,e,r,i,n),o}if(e instanceof Boolean){let o=new Boolean(e.valueOf());return i.set(e,o),l8t(o,e,r,i,n),o}if(e instanceof Number){let o=new Number(e.valueOf());return i.set(e,o),l8t(o,e,r,i,n),o}if(e instanceof String){let o=new String(e.valueOf());return i.set(e,o),l8t(o,e,r,i,n),o}if(typeof e=="object"&&CdB(e)){let o=Object.create(Object.getPrototypeOf(e));return i.set(e,o),l8t(o,e,r,i,n),o}return e}function l8t(e,t,r=e,i,n){let a=[...Object.keys(t),...zBh(t)];for(let o=0;o<a.length;o++){let c=a[o],d=Object.getOwnPropertyDescriptor(e,c);(d==null||d.writable)&&(e[c]=f$i(t[c],c,r,i,n))}}function CdB(e){switch(DOu(e)){case qOu:case VBh:case WBh:case HBh:case COu:case QBh:case kBh:case eIh:case YBh:case XBh:case ZBh:case UBh:case IOu:case GBh:case NBh:case LBh:case BOu:case FBh:case xBh:case KBh:case JBh:case $Bh:return!0;default:return!1}}function iIh(e){return f$i(e,void 0,e,new Map,void 0)}function nIh(e){return e=iIh(e),t=>MOu(t,e)}function aIh(e,t){return rIh(e,(r,i,n,a)=>{let o=t?.(r,i,n,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case IOu:case BOu:case COu:{let c=new e.constructor(e?.valueOf());return l8t(c,e),c}case qOu:{let c={};return l8t(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function oIh(e){return aIh(e)}var qdB=/^(?:0|[1-9]\d*)$/;function uIh(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return qdB.test(e)}}function sIh(e){return e!==null&&typeof e=="object"&&DOu(e)==="[object Arguments]"}function cIh(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&wOu(t)&&e?.[t]==null?r=EOu(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||sIh(i))&&uIh(a)&&a<i.length))return!1;i=i[a]}return!0}function lIh(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=Tua(e);break}}return t=oIh(t),function(r){let i=zKa(r,e);return i===void 0?cIh(r,e):t===void 0?i===void 0:MOu(i,t)}}function fIh(e){if(e==null)return POu;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?lIh(e[0],e[1]):nIh(e);case"string":case"symbol":case"number":return qBh(e)}}function dIh(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],o=e[a];r[a]=t(o,a,e)}return r}function TOu(e,t=POu){return e==null?{}:dIh(e,fIh(t))}function pIh(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var TdB=new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+","gu");function _Ih(e){return Array.from(e.match(TdB)??[])}function hIh(e){let t=_Ih(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>pIh(n)).join("")}`}function yIh(e){return typeof e!="string"&&(e=RKa(e)),e.replace(/['\u2019]/g,"")}function f8t(e){return hIh(yIh(e))}function NP(e){if(e!=null)return Array.isArray(e)?e:[e]}function ROu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${RdB(o)}${zdB(e)}.${NdB(i,n,a,c)}`}function RdB(e){return e?"webhook_":"endpoint_"}function zdB(e){return e!=null?NP(e)?.map(t=>f8t(t)).join("/"):""}function NdB(e,t,r,i){return e||t||f8t(r??"")||f8t(i??"")}function bIh(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var zOu=class extends po{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[vBh],this.accessTokenLocator!=null&&(bIh(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var NOu=class extends po{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new qua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new zOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=ROu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Ys.EndpointId(r),accessTokenLocator:Ys.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var Rua=class extends po{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new hOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new bOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new yOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new vOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new gOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{MBh(this.input)?(this.authScheme="header",this.headerAuthNode=new qua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new NOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new vIh.UnreachableCaseError(this.authScheme);return}}};var zua=class extends po{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=_Ou(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new Rua({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(No))}};var FOu=class extends po{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[pBh],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function gIh(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function OIh(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function Nua(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>NP(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!gIh(n))&&(o=OIh(o,o.type==="enum"?o.default:void 0)),{key:Ys.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(No)).filter(No).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function QOu(e,t){return zv(e)?sL(e,t,void 0):e}function d$i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function AIh(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function mIh(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var PIh=ce(HS());var tKc=["decimal","decimal128","double-int","double","float","sf-decimal"],rKc=["int16","int32","int64","int8","sf-integer","uint8"],iKc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],nKc=["beta","pre-release","in-development","generally-available","deprecated"];function uC(e,t){return zv(e)?sL(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var WEe=class extends po{availability;constructor(t){super(t),this.safeParse()}parse(){if(uC(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[_Bh];r!=null&&(nKc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${nKc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Ys.Availability.Beta;case"in-development":return Ys.Availability.InDevelopment;case"generally-available":return Ys.Availability.GenerallyAvailable;case"deprecated":return Ys.Availability.Deprecated;case void 0:return;default:new PIh.UnreachableCaseError(this.availability);return}}};var LOu=ce(HS());function jIh(e){return typeof e=="object"&&e!=null&&"language"in e}function wIh(e){return typeof e=="object"&&e!=null&&"sdk"in e}function EIh(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function SIh(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function UOu(e){return typeof e=="object"&&e!=null&&"event"in e}function aKc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(UOu)}function p$i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function MIh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var VOu=class extends po{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[SBh]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let o=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return p$i(o)?[n,{type:"filenameWithData",filename:o.filename,data:Ys.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>p$i(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:Ys.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[n,{type:"filenames",value:o}]}return}case"property":return[n,{type:"json",value:o}];case void 0:return;default:new LOu.UnreachableCaseError(a.multipartType);return}}).filter(No))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=MIh(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new LOu.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{EIh(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{aKc(r.response)&&(o={type:"sse",value:r.response.stream.map(f=>({event:f.event,data:f.data}))});break}case"application/octet-stream":!aKc(r.response)&&SIh(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new LOu.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(f=>{jIh(f)?f.language!=null&&(c[f.language]??=[],c[f.language]?.push({name:f.name,language:f.language,install:f.install,code:f.code,generated:!1,description:f.docs})):wIh(f)&&f.sdk!=null&&(c[f.sdk]??=[],c[f.sdk]?.push({name:f.name,language:f.sdk,install:void 0,code:f.code,generated:!1,description:f.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([f,p])=>[Ys.PropertyKey(f),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([f,p])=>[Ys.PropertyKey(f),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([f,p])=>[Ys.PropertyKey(f),p]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(u).length>0?u:void 0,requestBody:a,responseBody:o,snippets:c}}))}};var NKa=class extends po{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[fOu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Ys.api.v1.SubpackageId(f8t(r)))}};var WOu=class extends po{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[yBh]}convert(){return this.sdkMethodName}};var GOu=class extends po{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[bBh]}convert(){return this.isWebhook}};var HOu=class extends po{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[BBh]??[],...this.input[IBh]??[]],this.codeSamples.forEach(t=>{[...Object.values(Ys.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var Avn=ce(HS());function oKc(e,t){return zv(e)?sL(e,t,void 0):e}function DIh(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var cF="",qYt=class extends po{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(p$i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>p$i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new Avn.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=oKc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=oKc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new Avn.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(UOu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new Avn.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return p$i(n)?[r,{type:"filenameWithData",filename:n.filename,data:Ys.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>p$i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:Ys.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new Avn.UnreachableCaseError(i.multipartType);return}}).filter(No))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new Avn.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new Avn.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(No));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(No));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:DIh(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?CYt(this.name):this.summary!=null?CYt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function BIh(e,t){return zv(e)?sL(e,t,void 0):e}var WIh=ce(HS());var IIh="#/components/schemas/";function Fua(e){if(e.$ref.startsWith(IIh))return e.$ref.replace(IIh,"")}function jUi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function _$i(e){return typeof e.type=="string"&&e.type==="array"}function CIh(e){return e.type==="boolean"}function qIh(e){return e.type==="integer"}function h$i(e){return!Array.isArray(e.type)&&!_$i(e)}function TIh(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||h$i(t)||_$i(t))}function RIh(e){return"nullable"in e&&typeof e.nullable=="boolean"}function zIh(e){return e.type==="null"}function NIh(e){return e.type==="number"}function uKc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function FIh(e){return e.type==="string"}var xOu=class extends eY{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new K0({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return NP(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var KOu=class extends oC{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new WEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var JOu=class extends eY{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new K0({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(No)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>NP(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(No).reduce((n,a)=>n.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(jUi).filter(No):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function $Ou(e){return e!=null&&e.length>0?e:[void 0]}var Qua=class extends eY{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new K0({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new K0({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(zv(t))return Fua(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new K0({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(No))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return Nua(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:NP(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(No)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>$Ou(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>Ys.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=uC(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new K0({input:o,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var YOu=class extends eY{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>uC(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>uC(t,this.context.document)?.type!=="null"?new K0({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(No);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=uC({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new K0({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(No);return this.isNullable&&n!=null?n.map(jUi).filter(No):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Ys.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>NP(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??CYt(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(No)).filter(No)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>NP(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?CYt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?CYt(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(No)).filter(No)}:void 0,i=this.isNullable?jUi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var XOu=class extends oC{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var y$i=class extends oC{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(zv(r)){let n=uC(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(No),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var QIh=ce(HS());function FdB(e){return rKc.includes(e)}var ZOu=class extends oC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(FdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${rKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new QIh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var kOu=class extends oC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return jUi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var UIh=ce(HS());function QdB(e){return tKc.includes(e)}var eAu=class extends oC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(QdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${tKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new UIh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var LIh=ce(HS());function UdB(e){return iKc.includes(e)}var tAu=class extends oC{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new LIh.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(UdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${iKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new y$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var VIh=ce(HS());var rAu=class extends oC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,VIh.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var mvn=class extends eY{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=Fua(this.input);let t=uC(this.input,this.context.document);t?.enum!=null&&h$i(t)&&(this.maybeEnumConverterNode=new y$i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:Ys.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=uC(this.input,this.context.document);if(r!=null)return new K0({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var K0=class e extends eY{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new WEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),h$i(this.input)&&RIh(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),zv(this.input)){let t=Fua(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new mvn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new KOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(TIh(this.input))this.typeShapeNode=new JOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(h$i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new YOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(uKc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new Qua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(h$i(this.input)&&this.input.enum!=null)this.typeShapeNode=new y$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":uKc(this.input)&&(this.typeShapeNode=new Qua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":_$i(this.input)&&(this.typeShapeNode=new xOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":CIh(this.input)&&(this.typeShapeNode=new XOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":qIh(this.input)&&(this.typeShapeNode=new ZOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":NIh(this.input)&&(this.typeShapeNode=new eAu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":FIh(this.input)&&(this.typeShapeNode=new tAu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":zIh(this.input)&&(this.typeShapeNode=new kOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new WIh.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new Qua({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new rAu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!zv(this.input)&&(!_$i(this.input)&&this.input==null||_$i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=NP(t)?.map(i=>this.nullable?jUi(i):i).filter(No);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function b$i(e){if(e!=null)return Nua(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(No))}var TYt=class extends oC{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;zv(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new WEe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new K0({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=BIh(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function GIh(e,t){return zv(e)?sL(e,t,void 0):e}var sKc=ce(HS());function iAu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[Ys.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var HIh=ce(D2s(),1),Uua=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,o){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=o}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=HIh.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function LdB(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var nAu=class extends po{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new K0({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),LdB(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(zv(r)?n=_Ou(r.$ref,this.context.document):n=r,n!=null)return[t,new Rua({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(No)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[Ys.api.latest.AuthSchemeId(t),i]}).filter(No)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=NP(r.convert());return n==null?[t,void 0]:[Ys.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>No(r))):void 0}}};var aAu=class extends K0{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=uC(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${zv(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=uC(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var oAu=class extends po{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=uC(this.input.schema,this.context.document);this.availability=new WEe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=zv(this.input.schema)?new mvn({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=Uua.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new K0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new aAu({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(No))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[cF]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[cF]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:NP(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=f8t([this.method,this.path,this.contentType,"request"].join("_"));return iAu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Ys.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new sKc.UnreachableCaseError(n);return}}).filter(No)}convert(){if(this.schema instanceof mvn)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:Ys.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:Ys.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=NP(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:Ys.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new sKc.UnreachableCaseError(n.multipartType),[]}}).filter(No).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var uAu=class extends po{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=GIh(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new oAu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>NP(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(No)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>NP(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(No)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var xIh={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function KIh(e,t){if(zv(e)){let r=sL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var sAu=ce(HS());var JIh="application/json";var $Ih="application/octet-stream";function YIh(e,t){return e===t||t===cF||e===cF}var FKa=class extends po{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,o,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=o,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,o]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)YIh(c,a)&&(i.add(c),this.examples?.push(new qYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,d$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[o,c]of r){if(a===i){let[d,s,u]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(f=>new qYt({input:{requestExample:u,responseExample:f},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,d$i(s,o),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new qYt({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,d$i(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,o]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new qYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,d$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[cF];if(a!=null)for(let o of a)this.examples?.push(new qYt({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,d$i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=Uua.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=JIh,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new K0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=$Ih,this.contentSubtype=uC(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new K0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=TOu(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[cF]??=[],r[cF]=[{value:this.input.example}]);let i=uC(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=TOu(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[cF]??=[],r[cF]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[cF]??=[],r[cF]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==cF).map(([d,s])=>[c,d,s]));let o=Object.entries(r).filter(([c,d])=>!n.has(c)&&No(d)&&c!==cF);Object.keys(r).every(c=>c===cF)||this.matchExamplesByIndex(a,o),!n.has(cF)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return NP(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new sAu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return NP(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=f8t([this.method,this.path,this.statusCode,"response"].join("_"));return iAu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Ys.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new sAu.UnreachableCaseError(i);return}}).filter(No)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new sAu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var QKa=class extends po{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,o){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=KIh(this.input,this.context.document);if(r==null){this.context.errors.error({message:zv(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new TYt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new FKa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new FKa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(No)}};var cAu=class extends po{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new QKa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new QKa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return $Ou(b$i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(No))})))}).filter(No)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=NP(n?.convert());if(n!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??xIh[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(No)})).filter(No)})).filter(No)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var v$i=class extends po{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new qYt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,d$i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new WEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=l$i(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new GOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(zv(i)){let a=QOu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new TYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new TYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new TYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new HOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new uAu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new cAu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new zua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new NKa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new NKa({input:{[fOu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new WOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>ROu({namespace:NP(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(No),this.xFernExamplesNode=new VOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(No)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:Ys.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(u=>u.convert()).filter(No),n=mIh(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:AIh(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,f)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Ys.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[f]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:b$i(this.queryParameters)?.flat(),headers:b$i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(No)}}).filter(No);let a=this.servers?.map(u=>u.convert()).filter(No),o=this.convertPathToPathParts();if(o==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(u=>u.headers).filter(No);return this.endpointIds.map((u,f)=>({id:Ys.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[f]?.convert()?.map(p=>Ys.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>Ys.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:b$i(this.pathParameters)?.flat(),queryParameters:b$i(this.queryParameters)?.flat(),requestHeaders:b$i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(p=>p.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var Lua=class extends po{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=l$i(t,this.input.servers,this.context,this.accessPath),o=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new v$i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new v$i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new v$i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new v$i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new v$i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(No)}};function lAu(e){return"payloads"in e}var fAu=class extends po{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new Lua({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:l$i(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(No)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{lAu(a)?r[Ys.WebhookId(a.id)]=a:t[Ys.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var dAu=class extends po{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[hBh]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||QOu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new TYt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return Nua(this.globalHeaders,this.requiredProperties)?.flat()}};function XIh(e,t){if(zv(e)){let r=sL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var pAu=class extends po{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let o=XIh(a,this.context.document);if(o!=null)return new Lua({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(No)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{lAu(i)&&(t[Ys.WebhookId(i.id)]=i)}),t),{})}};var _Au=class extends po{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=l$i(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new zua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new FOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new fAu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new pAu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new nAu({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new dAu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Xbe(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=fBh({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:Ys.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function cKc(e,t){if(e instanceof CEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof tS))return;let r=new k3t(e.absoluteFilePath),i=await TEe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new cOu,generatedTypes:{}},d=new _Au({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=wKn(a,d.convert())}return a}var hLh=ce(dKc(),1),yLh=ce(rmu(),1),EPu=require("fs/promises"),bLh=ce(require("http"),1),vLh=ce(require("path"),1);var tzh=require("events"),umu=ce(require("fs"),1),Cvn=ce(require("path"),1);var NRh=ce(require("os"),1),FRh=300,w$i=20,sJa=1e7,QRh=NRh.default.platform();var cOB=QRh==="darwin",CJc=QRh==="win32",E$i=cOB||CJc,URh=3e3,LRh=2e4,qJc=1250;var FYt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(FYt||(FYt={}));var Ivn;(function(e){e.CHANGE="change",e.RENAME="rename"})(Ivn||(Ivn={}));var cJa;(function(e){e.CHANGE="change",e.ERROR="error"})(cJa||(cJa={}));var Hl;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Hl||(Hl={}));var cH;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(cH||(cH={}));var lOB=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),m=g-d,j=g-s,M=m>=t||j>=a;return[g,M]},f=g=>{if(s=g,!o)return;let m=o;o=void 0,e.apply(void 0,m)},p=()=>{O(0)},_=()=>{c&&(p(),f(Date.now()))},h=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,m]=u();return m?y(g):v(g)},v=g=>{let m=g-d,j=g-s,M=t-m,w=a-j,D=Math.min(M,w);return O(D)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},A=(...g)=>{let[m,j]=u(),M=!!c;if(o=g,d=m,(j||!c)&&O(t),j)return M?f(m):h(m)};return A.cancel=p,A.flush=_,A},imu=lOB;var NJc=ce(require("fs"),1),amu=ce(require("path"),1);var KO=ce(require("fs"),1),cL=require("util");var EUi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},QYt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var TJc=ce(require("process"),1),VRh=TJc.default.getuid?!TJc.default.getuid():!1,WRh=1e4,nY=()=>{};var lJa={isChangeErrorOk:e=>{if(!lJa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!VRh&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!lJa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!lJa.isNodeError(e))throw e;if(!lJa.isChangeErrorOk(e))throw e}},sC=lJa;var RJc=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=WRh,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},GRh=new RJc;var SUi=(e,t)=>function(i){return function n(...a){return GRh.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},MUi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var fOB={attempt:{chmod:EUi((0,cL.promisify)(KO.default.chmod),sC.onChangeError),chown:EUi((0,cL.promisify)(KO.default.chown),sC.onChangeError),close:EUi((0,cL.promisify)(KO.default.close),nY),fsync:EUi((0,cL.promisify)(KO.default.fsync),nY),mkdir:EUi((0,cL.promisify)(KO.default.mkdir),nY),realpath:EUi((0,cL.promisify)(KO.default.realpath),nY),stat:EUi((0,cL.promisify)(KO.default.stat),nY),unlink:EUi((0,cL.promisify)(KO.default.unlink),nY),chmodSync:QYt(KO.default.chmodSync,sC.onChangeError),chownSync:QYt(KO.default.chownSync,sC.onChangeError),closeSync:QYt(KO.default.closeSync,nY),existsSync:QYt(KO.default.existsSync,nY),fsyncSync:QYt(KO.default.fsync,nY),mkdirSync:QYt(KO.default.mkdirSync,nY),realpathSync:QYt(KO.default.realpathSync,nY),statSync:QYt(KO.default.statSync,nY),unlinkSync:QYt(KO.default.unlinkSync,nY)},retry:{close:SUi((0,cL.promisify)(KO.default.close),sC.isRetriableError),fsync:SUi((0,cL.promisify)(KO.default.fsync),sC.isRetriableError),open:SUi((0,cL.promisify)(KO.default.open),sC.isRetriableError),readFile:SUi((0,cL.promisify)(KO.default.readFile),sC.isRetriableError),rename:SUi((0,cL.promisify)(KO.default.rename),sC.isRetriableError),stat:SUi((0,cL.promisify)(KO.default.stat),sC.isRetriableError),write:SUi((0,cL.promisify)(KO.default.write),sC.isRetriableError),writeFile:SUi((0,cL.promisify)(KO.default.writeFile),sC.isRetriableError),closeSync:MUi(KO.default.closeSync,sC.isRetriableError),fsyncSync:MUi(KO.default.fsyncSync,sC.isRetriableError),openSync:MUi(KO.default.openSync,sC.isRetriableError),readFileSync:MUi(KO.default.readFileSync,sC.isRetriableError),renameSync:MUi(KO.default.renameSync,sC.isRetriableError),statSync:MUi(KO.default.statSync,sC.isRetriableError),writeSync:MUi(KO.default.writeSync,sC.isRetriableError),writeFileSync:MUi(KO.default.writeFileSync,sC.isRetriableError)}},HRh=fOB;var nmu=ce(require("fs"),1),fJa=ce(require("path"),1);var zJc=()=>{};var dOB=()=>{let e=zJc,t=zJc,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},xRh=dOB;var pOB=()=>{let{promise:e,resolve:t,isPending:r}=xRh(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},KRh=pOB;var JRh={then:e=>{e()}};var $Rh=e=>Array.isArray(e)?e:[e],YRh=e=>typeof e=="function";var _OB=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=$Rh(a).map(H=>YRh(H)?H:G=>H.test(G)),c=H=>o.some(G=>G(H)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},A={},g=new Set,m={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:A},{promise:M,increment:w,decrement:D}=KRh(),B=0,z=(H,G,Ee,se)=>{g.has(G)||B>=n||(B+=1,H.directories.push(G),H.directoriesNames.add(Ee),u.push(G),f.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(G),g.add(G),!(se>=i)&&(B>=n||ee(G,se+1)))},F=(H,G,Ee)=>{g.has(G)||B>=n||(B+=1,H.files.push(G),H.filesNames.add(Ee),_.push(G),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(G),g.add(G))},q=(H,G,Ee,se)=>{g.has(G)||B>=n||(B+=1,H.symlinks.push(G),H.symlinksNames.add(Ee),b.push(G),v.add(Ee),O.propertyIsEnumerable(Ee)||(O[Ee]=[]),O[Ee].push(G),g.add(G),r&&(se>=i||B>=n||ve(G,se+1)))},N=(H,G,Ee,se,Ae)=>{d.aborted||c(G)||(se.isDirectory()?z(H,G,Ee,Ae):se.isFile()?F(H,G,Ee):se.isSymbolicLink()&&q(H,G,Ee,Ae))},Q=(H,G,Ee,se)=>{if(d.aborted)return;let Ae=G===fJa.default.sep?"":fJa.default.sep,Fe=Ee.name,oe=`${G}${Ae}${Fe}`;c(oe)||(Ee.isDirectory()?z(H,oe,Fe,se):Ee.isFile()?F(H,oe,Fe):Ee.isSymbolicLink()&&q(H,oe,Fe,se))},x=(H,G,Ee,se)=>{for(let Ae=0,Fe=Ee.length;Ae<Fe;Ae++)Q(H,G,Ee[Ae],se)},ee=(H,G)=>{d.aborted||G>i||B>=n||(w(),nmu.default.readdir(H,{withFileTypes:!0},(Ee,se)=>{if(Ee||d.aborted||!se.length)return D();(s(se)||JRh).then(()=>{let Fe=A[H]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};x(Fe,H,se,G),D()})}))},ve=(H,G)=>{w(),nmu.default.realpath(H,(Ee,se)=>{if(Ee||d.aborted)return D();nmu.default.stat(se,(Ae,Fe)=>{if(Ae||d.aborted)return D();let oe=fJa.default.basename(se),ne=A[H]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};N(ne,se,oe,Fe,G),D()})})};return(async(H,G=1)=>(H=fJa.default.normalize(H),g.add(H),ee(H,G),await M,d.aborted?m:j))(e)},XRh=_OB;var UYt={lang:{debounce:imu,attempt:e=>{try{return e()}catch(t){return UYt.lang.castError(t)}},castArray:e=>UYt.lang.isArray(e)?e:[e],castError:e=>UYt.lang.isError(e)?e:UYt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(UYt.lang.isNaN(e))return UYt.lang.isNaN(t);if(UYt.lang.isPrimitive(e)||UYt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(amu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?NJc.default.realpathSync.native(e):NJc.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===amu.default.sep&&t.length-e.length>amu.default.sep.length,poll:(e,t=LRh)=>HRh.retry.stat(t)(e,{bigint:!0}).catch(UYt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await XRh(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Dp=UYt;var omu=ce(require("path"),1);var FJc=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Dp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=FRh){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=Dp.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Hl.CHANGE&&c===Hl.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Hl.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Hl.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??w$i:Math.min(1,this.options.depth??w$i),o=this.options.limit??sJa,[c,d]=await Dp.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Dp.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Hl.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!E$i&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Hl.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Hl.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(omu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Hl.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(omu.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Hl.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Hl.ADD?this.onTargetAdd(i):r===Hl.ADD_DIR?this.onTargetAddDir(i):r===Hl.CHANGE?this.onTargetChange(i):r===Hl.UNLINK?this.onTargetUnlink(i):r===Hl.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Ivn.CHANGE,r){if(this.watcher.isClosed())return;let i=omu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){CJc&&t.code==="EPERM"?this.onWatcherChange(Ivn.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(cJa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(cJa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Ivn.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&E$i&&this.options.native!==!1?this.options.depth??w$i:Math.min(1,this.options.depth??w$i),i=this.options.limit??sJa,[n,a]=await Dp.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(Ivn.CHANGE,c,t)}))}}},ZRh=FJc;var lH={interval:100,intervalId:void 0,fns:new Map,init:()=>{lH.intervalId||(lH.intervalId=setInterval(lH.resolve,lH.interval))},reset:()=>{lH.intervalId&&(clearInterval(lH.intervalId),delete lH.intervalId)},add:(e,t)=>{lH.fns.set(e,Date.now()+t),lH.init()},remove:e=>{lH.fns.delete(e)},resolve:()=>{if(!lH.fns.size)return lH.reset();let e=Date.now();for(let[t,r]of lH.fns)r>=e||(lH.remove(t),t())}},dJa=lH;var pJa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=qJc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(Dp.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),dJa.remove(s)},s=()=>{d(),c()};dJa.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=qJc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),dJa.remove(s)},s=()=>{d(),c()};dJa.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Hl.ADD,FYt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Hl.ADD_DIR,FYt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Hl.UNLINK,FYt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Hl.UNLINK_DIR,FYt.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};pJa.DIR_EVENTS={add:Hl.ADD_DIR,rename:Hl.RENAME_DIR,unlink:Hl.UNLINK_DIR};pJa.FILE_EVENTS={add:Hl.ADD,change:Hl.CHANGE,rename:Hl.RENAME,unlink:Hl.UNLINK};var kRh=pJa;var QJc=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Dp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Dp.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Dp.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Dp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Dp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Dp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},UJc=QJc;var LJc=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},ezh=LJc;var VJc=class{constructor(){this.inos={},this.paths=new UJc,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Dp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new ezh(i)}reset(){this.inos={},this.paths=new UJc,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Hl.ADD,n),[Hl.ADD];if(n.isDirectory())return this.updateIno(t,Hl.ADD_DIR,n),[Hl.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Hl.UNLINK,i),[Hl.UNLINK];if(i.isDirectory())return this.updateIno(t,Hl.UNLINK_DIR,i),[Hl.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Hl.CHANGE,n),[Hl.CHANGE]);if(n.isDirectory())return this.updateIno(t,Hl.UNLINK,i),this.updateIno(t,Hl.ADD_DIR,n),[Hl.UNLINK,Hl.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Hl.UNLINK_DIR,i),this.updateIno(t,Hl.ADD,n),[Hl.UNLINK_DIR,Hl.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Hl.UNLINK_DIR,i),this.updateIno(t,Hl.ADD_DIR,n),[Hl.UNLINK_DIR,Hl.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?FYt.FILE:FYt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},WJc=VJc;var GJc=class e extends tzh.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(cH.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(cH.CLOSE,n)),this._readyWait=new Promise(n=>this.on(cH.READY,n)),this._locker=new kRh(this),this._roots=new Set,this._poller=new WJc,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Dp.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(cH.CLOSE))}error(t){if(this.isClosed())return!1;let r=Dp.lang.castError(t);return this.emit(cH.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(cH.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(cH.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Dp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Dp.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Dp.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new ZRh(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Dp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=Cvn.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??w$i))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&E$i&&u.options.native!==!1)))return!0;if(!E$i)break;let s=Cvn.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Dp.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||E$i&&r.native!==!1?r:{...r,recursive:!1},u={watcher:umu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=Cvn.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,f)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||E$i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??w$i,c=r.limit??sJa,[d]=await Dp.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=Dp.fs.getDepth(t);for(let f of d){let p=Dp.fs.getDepth(f),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([f],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(cH.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(cH.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=Cvn.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new WJc,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Dp.lang.noop;if(this.pollerExists(t,r))return Dp.lang.noop;let n={...r,interval:r.pollingInterval??URh},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(cH.CLOSE,c),umu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(cH.CLOSE,c),umu.default.unwatchFile(t,i)};return Dp.lang.attempt(o),()=>Dp.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Dp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Dp.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=Cvn.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Dp.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=Cvn.default.dirname(t);return(await Dp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Dp.lang.noop){if(Dp.lang.isFunction(t))return this.watch([],{},t);if(Dp.lang.isUndefined(t))return this.watch([],r,i);if(Dp.lang.isFunction(r))return this.watch(t,{},r);if(Dp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Dp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Dp.lang.noop&&this.on(cH.ALL,i),r.readdirMap=void 0,this.ready())}},smu=GJc;TXo();var isa=require("fs/promises"),rzh=require("os"),izh=ce(require("path"),1),hOB=".fern",yOB="logs";function bOB(){return"cli@3.42.4"}var _Ja=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Ct(Sr.of((0,rzh.homedir)()),He.of(hOB)),r=Ct(t,He.of(yOB));await mi(r)||await(0,isa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Ct(r,He.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${izh.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
1835
+ `;return this.parsedDocsConfig.pages[He.of(o)]=d,{id:this.#e.get(c),type:"page",slug:a.get(),title:i,icon:void 0,hidden:!1,viewers:void 0,orphaned:void 0,pageId:c,authed:void 0,noindex:!0,featureFlags:void 0,availability:void 0}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Nt.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??UE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Nt.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??UE(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,f=n||r.hidden;return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:f,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:d,item:p,parentSlug:s,hideChildren:f,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return wln(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new Ovn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Nt.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??UE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??UE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):oG.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(ds),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:oG.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return wln(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:oG.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function fdB(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${oH(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function ddB(e){switch(e){case"beta":return Nt.V1.NavigationV1Availability.Beta;case"deprecated":return Nt.V1.NavigationV1Availability.Deprecated;case"ga":return Nt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Nt.V1.NavigationV1Availability.Stable;default:vt(e)}}async function uL(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof tS?t:null))).filter(ds)}async function Axc(e,t,r){if(e instanceof CEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof tS))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return aH({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var Ys={};Zt(Ys,{AlgoliaSearchIndex:()=>JMh,ApiDefinitionId:()=>hDh,ApiId:()=>gDh,Availability:()=>TDh,DocsConfigId:()=>ODh,EndpointId:()=>mDh,EndpointPathLiteral:()=>CDh,EnvironmentId:()=>ADh,FileId:()=>SDh,HttpMethod:()=>qDh,IndexSegmentId:()=>$Mh,JqString:()=>DDh,OrgId:()=>bDh,PageId:()=>EDh,PayloadLocation:()=>uBh,PropertyKey:()=>BDh,PullRequestState:()=>rBh,RoleId:()=>IDh,TokenId:()=>vDh,TypeId:()=>wDh,Url:()=>MDh,VersionId:()=>yDh,WebSocketId:()=>PDh,WebhookId:()=>jDh,algolia:()=>mxc,api:()=>Cxc,commons:()=>qxc,diff:()=>RDh,docs:()=>Vxc,generators:()=>Gxc,git:()=>Hxc,navigation:()=>Jxc,sdks:()=>Yxc,snippets:()=>aBh,snippetsFactory:()=>oBh,templates:()=>Xxc,tokens:()=>sBh});var mxc={};Zt(mxc,{AlgoliaSearchIndex:()=>JMh,IndexSegmentId:()=>$Mh});function JMh(e){return e}function $Mh(e){return e}var Cxc={};Zt(Cxc,{latest:()=>wxc,v1:()=>Ixc});var wxc={};Zt(wxc,{AuthSchemeId:()=>YMh,WebhookHttpMethod:()=>eDh,auth:()=>Pxc,commons:()=>XMh,endpoint:()=>ZMh,type_:()=>kMh,webhook:()=>jxc,websocket:()=>tDh});var Pxc={};Zt(Pxc,{AuthSchemeId:()=>YMh});function YMh(e){return e}var XMh={};var ZMh={};var kMh={};var jxc={};Zt(jxc,{WebhookHttpMethod:()=>eDh});var eDh={Get:"GET",Post:"POST"};var tDh={};var Ixc={};Zt(Ixc,{SubpackageId:()=>fDh,WebSocketMessageId:()=>dDh,WebSocketMessageOrigin:()=>pDh,WebhookHttpMethod:()=>_Dh,commons:()=>Bxc,db:()=>Exc,read:()=>Mxc,register:()=>Dxc});var Exc={};Zt(Exc,{endpoint:()=>rDh});var rDh={};var Mxc={};Zt(Mxc,{SupportedLanguage:()=>iDh,endpoint:()=>Sxc,type_:()=>nDh,webhook:()=>aDh,websocket:()=>oDh});var Sxc={};Zt(Sxc,{SupportedLanguage:()=>iDh});var iDh={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var nDh={};var aDh={};var oDh={};var Dxc={};Zt(Dxc,{SourceId:()=>pdB,endpoint:()=>uDh,type_:()=>sDh,webhook:()=>cDh,websocket:()=>lDh});var uDh={};var sDh={};var cDh={};var lDh={};function pdB(e){return e}var Bxc={};Zt(Bxc,{SubpackageId:()=>fDh,WebSocketMessageId:()=>dDh,WebSocketMessageOrigin:()=>pDh,WebhookHttpMethod:()=>_Dh});function fDh(e){return e}function dDh(e){return e}var pDh={Client:"client",Server:"server"};var _Dh={Get:"GET",Post:"POST"};var qxc={};Zt(qxc,{ApiDefinitionId:()=>hDh,ApiId:()=>gDh,Availability:()=>TDh,DocsConfigId:()=>ODh,EndpointId:()=>mDh,EndpointPathLiteral:()=>CDh,EnvironmentId:()=>ADh,FileId:()=>SDh,HttpMethod:()=>qDh,JqString:()=>DDh,OrgId:()=>bDh,PageId:()=>EDh,PropertyKey:()=>BDh,RoleId:()=>IDh,TokenId:()=>vDh,TypeId:()=>wDh,Url:()=>MDh,VersionId:()=>yDh,WebSocketId:()=>PDh,WebhookId:()=>jDh});function hDh(e){return e}function yDh(e){return e}function bDh(e){return e}function vDh(e){return e}function gDh(e){return e}function ODh(e){return e}function ADh(e){return e}function mDh(e){return e}function PDh(e){return e}function jDh(e){return e}function wDh(e){return e}function EDh(e){return e}function SDh(e){return e}function MDh(e){return e}function DDh(e){return e}function BDh(e){return e}function IDh(e){return e}function CDh(e){return e}var qDh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var TDh={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var RDh={};var Vxc={};Zt(Vxc,{latest:()=>zxc,v1:()=>Uxc,v2:()=>Lxc});var zxc={};Zt(zxc,{Layout:()=>NDh,MdxEngine:()=>_dB,TwitterCardSetting:()=>FDh,commons:()=>zDh,frontmatter:()=>Txc,seo:()=>Rxc});var _dB={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var zDh={};var Txc={};Zt(Txc,{Layout:()=>NDh});var NDh={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var Rxc={};Zt(Rxc,{TwitterCardSetting:()=>FDh});var FDh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Uxc={};Zt(Uxc,{commons:()=>Qxc,db:()=>QDh,read:()=>UDh,write:()=>Nxc});var QDh={};var UDh={};var Nxc={};Zt(Nxc,{DocsRegistrationId:()=>ydB,FilePath:()=>hdB});function hdB(e){return e}function ydB(e){return e}var Qxc={};Zt(Qxc,{ContentAlignment:()=>GDh,FontDisplay:()=>$Dh,FontStyle:()=>JDh,HeaderPosition:()=>HDh,JsScriptStrategy:()=>KDh,ProgrammingLanguage:()=>LDh,SearchbarPlacement:()=>VDh,TabsPlacement:()=>WDh,TwitterCardSetting:()=>xDh,commons:()=>Fxc});var Fxc={};Zt(Fxc,{ContentAlignment:()=>GDh,FontDisplay:()=>$Dh,FontStyle:()=>JDh,HeaderPosition:()=>HDh,JsScriptStrategy:()=>KDh,ProgrammingLanguage:()=>LDh,SearchbarPlacement:()=>VDh,TabsPlacement:()=>WDh,TwitterCardSetting:()=>xDh});var LDh={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var VDh={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var WDh={Header:"HEADER",Sidebar:"SIDEBAR"};var GDh={Center:"CENTER",Left:"LEFT"};var HDh={Fixed:"FIXED",Absolute:"ABSOLUTE"};var xDh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var KDh={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var JDh={Normal:"normal",Italic:"italic"};var $Dh={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Lxc={};Zt(Lxc,{read:()=>YDh,write:()=>XDh});var YDh={};var XDh={};var Gxc={};Zt(Gxc,{ChangelogEntryType:()=>kDh,GeneratorId:()=>bdB,GeneratorLanguage:()=>vdB,ReleaseType:()=>eBh,cli:()=>ZDh,commons:()=>Wxc,versions:()=>tBh});var ZDh={};var Wxc={};Zt(Wxc,{ChangelogEntryType:()=>kDh,ReleaseType:()=>eBh});var kDh={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var eBh={Ga:"GA",Rc:"RC"};var tBh={};function bdB(e){return e}var vdB={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Hxc={};Zt(Hxc,{PullRequestState:()=>rBh});var rBh={Open:"open",Closed:"closed",Merged:"merged"};var Jxc={};Zt(Jxc,{latest:()=>xxc,v1:()=>Kxc});var xxc={};Zt(xxc,{NodeId:()=>AdB,ProductId:()=>mdB,Slug:()=>gdB,TabId:()=>OdB});function gdB(e){return e}function OdB(e){return e}function AdB(e){return e}function mdB(e){return e}var Kxc={};Zt(Kxc,{NavigationV1Availability:()=>SdB,NodeId:()=>wdB,ProductId:()=>EdB,Slug:()=>PdB,TabId:()=>jdB});function PdB(e){return e}function jdB(e){return e}function wdB(e){return e}function EdB(e){return e}var SdB={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Yxc={};Zt(Yxc,{Language:()=>iBh,VersionBump:()=>nBh,versions:()=>$xc});var $xc={};Zt($xc,{Language:()=>iBh,VersionBump:()=>nBh});var iBh={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var nBh={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var aBh={};var oBh={};var Xxc={};Zt(Xxc,{PayloadLocation:()=>uBh});var uBh={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var sBh={};var cOu=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function No(e){return e!=null}var lBh=ce(xFa(),1);var cBh=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function CYt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,lBh.default)(e,{special:cBh}).replace(/V\s(\d)/g,"V$1")}function fBh({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=Ys.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:CYt(a)},n.push(a)})}),r}var lOu=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function dBh(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var po=class extends lOu{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((o,c)=>o===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${dBh(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},oC=class extends po{},eY=class extends oC{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var pBh="x-fern-base-path",_Bh="x-fern-availability",fOu="x-fern-sdk-group-name",hBh="x-fern-global-headers",yBh="x-fern-sdk-method-name";var bBh="x-fern-webhook",vBh="x-fern-access-token-locator",gBh="x-fern-basic",OBh="x-fern-username-variable-name",ABh="x-fern-password-variable-name",mBh="x-fern-bearer",PBh="x-fern-token-variable-name",jBh="x-fern-header",wBh="x-fern-header-variable-name",EBh="x-fern-server-name",SBh="x-fern-examples";var dOu=class extends po{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[EBh]}convert(){if(this.serverName!=null)return this.serverName}};var pOu=class extends po{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new dOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:Ys.EnvironmentId(t),baseUrl:this.url}}};function l$i(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new pOu({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...o]}function zv(e){return typeof e=="object"&&No(e)&&"$ref"in e&&typeof e.$ref=="string"}function sL(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(zv(n)&&(n=sL(n,t,r)),n)}function _Ou(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return zv(r)?sL(r,t,void 0):r}var vIh=ce(HS());var hOu=class extends po{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[gBh];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var yOu=class extends po{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[ABh]}convert(){return this.passwordVariableName}};var bOu=class extends po{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[OBh]}convert(){return this.usernameVariableName}};var vOu=class extends po{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[mBh];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var gOu=class extends po{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[PBh]}convert(){return this.tokenVariableName}};function MBh(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var DBh="x-bearer-format",BBh="x-code-samples",IBh="x-codeSamples";var OOu=class extends po{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[DBh]}convert(){return this.bearerFormat}};var AOu=class extends po{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[jBh];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var mOu=class extends po{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[wBh]}convert(){return this.headerVariableName}};function CBh(e){return e.type==="apiKey"}var qua=class extends po{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){CBh(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new AOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new mOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new OOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function POu(e){return e}function jOu(e){return e==="__proto__"}function wOu(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Tua(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function RKa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(RKa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function EOu(e){if(Array.isArray(e))return e.map(Tua);if(typeof e=="symbol")return[e];e=RKa(e);let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(n),n=""):n+=c:c==="["?(o=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function zKa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(jOu(t))return r;let i=e[t];return i===void 0?wOu(t)?zKa(e,EOu(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=Tua(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return MdB(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),jOu(t))return r;let i=e[t];return i===void 0?r:i}}}function MdB(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||jOu(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function qBh(e){return function(t){return zKa(t,e)}}function TBh(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function SOu(e){return e==null||typeof e!="object"&&typeof e!="function"}function Zxc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function eKc(e,t,r){return typeof r!="function"?eKc(e,t,()=>{}):kxc(e,t,function i(n,a,o,c,d,s){let u=r(n,a,o,c,d,s);return u!==void 0?!!u:kxc(n,a,i,s)},new Map)}function kxc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return DdB(e,t,r,i);case"function":return Object.keys(t).length>0?kxc(e,{...t},r,i):Zxc(e,t);default:return TBh(e)?typeof t=="string"?t==="":!0:Zxc(e,t)}}function DdB(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return RBh(e,t,r,i);if(t instanceof Map)return BdB(e,t,r,i);if(t instanceof Set)return IdB(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i?.has(t))return i.get(t)===e;i?.set(t,e);try{for(let a=0;a<n.length;a++){let o=n[a];if(!SOu(e)&&!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!r(e[o],t[o],o,e,t,i))return!1}return!0}finally{i?.delete(t)}}function BdB(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let o=e.get(n);if(r(o,a,n,e,t,i)===!1)return!1}return!0}function RBh(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let o=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],u=!1;if(r(s,o,a,e,t,i)&&(u=!0),u){n.add(d),c=!0;break}}if(!c)return!1}return!0}function IdB(e,t,r,i){return t.size===0?!0:e instanceof Set?RBh([...e],[...t],r,i):!1}function MOu(e,t){return eKc(e,t,()=>{})}function zBh(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function DOu(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}var NBh="[object RegExp]",BOu="[object String]",IOu="[object Number]",COu="[object Boolean]",qOu="[object Arguments]",FBh="[object Symbol]",QBh="[object Date]",UBh="[object Map]",LBh="[object Set]",VBh="[object Array]";var WBh="[object ArrayBuffer]",GBh="[object Object]";var HBh="[object DataView]",xBh="[object Uint8Array]",KBh="[object Uint8ClampedArray]",JBh="[object Uint16Array]",$Bh="[object Uint32Array]";var YBh="[object Int8Array]",XBh="[object Int16Array]",ZBh="[object Int32Array]";var kBh="[object Float32Array]",eIh="[object Float64Array]";function tIh(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function rIh(e,t){return f$i(e,void 0,e,new Map,t)}function f$i(e,t,r,i=new Map,n=void 0){let a=n?.(e,t,r,i);if(a!==void 0)return a;if(SOu(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){let o=new Array(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=f$i(e[c],c,r,i,n);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){let o=new Map;i.set(e,o);for(let[c,d]of e)o.set(c,f$i(d,c,r,i,n));return o}if(e instanceof Set){let o=new Set;i.set(e,o);for(let c of e)o.add(f$i(c,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(tIh(e)){let o=new(Object.getPrototypeOf(e)).constructor(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=f$i(e[c],c,r,i,n);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,o),l8t(o,e,r,i,n),o}if(typeof File<"u"&&e instanceof File){let o=new File([e],e.name,{type:e.type});return i.set(e,o),l8t(o,e,r,i,n),o}if(typeof Blob<"u"&&e instanceof Blob){let o=new Blob([e],{type:e.type});return i.set(e,o),l8t(o,e,r,i,n),o}if(e instanceof Error){let o=new e.constructor;return i.set(e,o),o.message=e.message,o.name=e.name,o.stack=e.stack,o.cause=e.cause,l8t(o,e,r,i,n),o}if(e instanceof Boolean){let o=new Boolean(e.valueOf());return i.set(e,o),l8t(o,e,r,i,n),o}if(e instanceof Number){let o=new Number(e.valueOf());return i.set(e,o),l8t(o,e,r,i,n),o}if(e instanceof String){let o=new String(e.valueOf());return i.set(e,o),l8t(o,e,r,i,n),o}if(typeof e=="object"&&CdB(e)){let o=Object.create(Object.getPrototypeOf(e));return i.set(e,o),l8t(o,e,r,i,n),o}return e}function l8t(e,t,r=e,i,n){let a=[...Object.keys(t),...zBh(t)];for(let o=0;o<a.length;o++){let c=a[o],d=Object.getOwnPropertyDescriptor(e,c);(d==null||d.writable)&&(e[c]=f$i(t[c],c,r,i,n))}}function CdB(e){switch(DOu(e)){case qOu:case VBh:case WBh:case HBh:case COu:case QBh:case kBh:case eIh:case YBh:case XBh:case ZBh:case UBh:case IOu:case GBh:case NBh:case LBh:case BOu:case FBh:case xBh:case KBh:case JBh:case $Bh:return!0;default:return!1}}function iIh(e){return f$i(e,void 0,e,new Map,void 0)}function nIh(e){return e=iIh(e),t=>MOu(t,e)}function aIh(e,t){return rIh(e,(r,i,n,a)=>{let o=t?.(r,i,n,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case IOu:case BOu:case COu:{let c=new e.constructor(e?.valueOf());return l8t(c,e),c}case qOu:{let c={};return l8t(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function oIh(e){return aIh(e)}var qdB=/^(?:0|[1-9]\d*)$/;function uIh(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return qdB.test(e)}}function sIh(e){return e!==null&&typeof e=="object"&&DOu(e)==="[object Arguments]"}function cIh(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&wOu(t)&&e?.[t]==null?r=EOu(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||sIh(i))&&uIh(a)&&a<i.length))return!1;i=i[a]}return!0}function lIh(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=Tua(e);break}}return t=oIh(t),function(r){let i=zKa(r,e);return i===void 0?cIh(r,e):t===void 0?i===void 0:MOu(i,t)}}function fIh(e){if(e==null)return POu;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?lIh(e[0],e[1]):nIh(e);case"string":case"symbol":case"number":return qBh(e)}}function dIh(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],o=e[a];r[a]=t(o,a,e)}return r}function TOu(e,t=POu){return e==null?{}:dIh(e,fIh(t))}function pIh(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var TdB=new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+","gu");function _Ih(e){return Array.from(e.match(TdB)??[])}function hIh(e){let t=_Ih(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>pIh(n)).join("")}`}function yIh(e){return typeof e!="string"&&(e=RKa(e)),e.replace(/['\u2019]/g,"")}function f8t(e){return hIh(yIh(e))}function NP(e){if(e!=null)return Array.isArray(e)?e:[e]}function ROu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${RdB(o)}${zdB(e)}.${NdB(i,n,a,c)}`}function RdB(e){return e?"webhook_":"endpoint_"}function zdB(e){return e!=null?NP(e)?.map(t=>f8t(t)).join("/"):""}function NdB(e,t,r,i){return e||t||f8t(r??"")||f8t(i??"")}function bIh(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var zOu=class extends po{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[vBh],this.accessTokenLocator!=null&&(bIh(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var NOu=class extends po{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new qua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new zOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=ROu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Ys.EndpointId(r),accessTokenLocator:Ys.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var Rua=class extends po{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new hOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new bOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new yOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new vOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new gOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{MBh(this.input)?(this.authScheme="header",this.headerAuthNode=new qua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new NOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new vIh.UnreachableCaseError(this.authScheme);return}}};var zua=class extends po{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=_Ou(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new Rua({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(No))}};var FOu=class extends po{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[pBh],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function gIh(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function OIh(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function Nua(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>NP(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!gIh(n))&&(o=OIh(o,o.type==="enum"?o.default:void 0)),{key:Ys.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(No)).filter(No).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function QOu(e,t){return zv(e)?sL(e,t,void 0):e}function d$i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function AIh(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function mIh(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var PIh=ce(HS());var tKc=["decimal","decimal128","double-int","double","float","sf-decimal"],rKc=["int16","int32","int64","int8","sf-integer","uint8"],iKc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],nKc=["beta","pre-release","in-development","generally-available","deprecated"];function uC(e,t){return zv(e)?sL(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var WEe=class extends po{availability;constructor(t){super(t),this.safeParse()}parse(){if(uC(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[_Bh];r!=null&&(nKc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${nKc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Ys.Availability.Beta;case"in-development":return Ys.Availability.InDevelopment;case"generally-available":return Ys.Availability.GenerallyAvailable;case"deprecated":return Ys.Availability.Deprecated;case void 0:return;default:new PIh.UnreachableCaseError(this.availability);return}}};var LOu=ce(HS());function jIh(e){return typeof e=="object"&&e!=null&&"language"in e}function wIh(e){return typeof e=="object"&&e!=null&&"sdk"in e}function EIh(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function SIh(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function UOu(e){return typeof e=="object"&&e!=null&&"event"in e}function aKc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(UOu)}function p$i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function MIh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var VOu=class extends po{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[SBh]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let o=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return p$i(o)?[n,{type:"filenameWithData",filename:o.filename,data:Ys.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>p$i(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:Ys.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[n,{type:"filenames",value:o}]}return}case"property":return[n,{type:"json",value:o}];case void 0:return;default:new LOu.UnreachableCaseError(a.multipartType);return}}).filter(No))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=MIh(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new LOu.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{EIh(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{aKc(r.response)&&(o={type:"sse",value:r.response.stream.map(f=>({event:f.event,data:f.data}))});break}case"application/octet-stream":!aKc(r.response)&&SIh(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new LOu.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(f=>{jIh(f)?f.language!=null&&(c[f.language]??=[],c[f.language]?.push({name:f.name,language:f.language,install:f.install,code:f.code,generated:!1,description:f.docs})):wIh(f)&&f.sdk!=null&&(c[f.sdk]??=[],c[f.sdk]?.push({name:f.name,language:f.sdk,install:void 0,code:f.code,generated:!1,description:f.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([f,p])=>[Ys.PropertyKey(f),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([f,p])=>[Ys.PropertyKey(f),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([f,p])=>[Ys.PropertyKey(f),p]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(u).length>0?u:void 0,requestBody:a,responseBody:o,snippets:c}}))}};var NKa=class extends po{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[fOu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Ys.api.v1.SubpackageId(f8t(r)))}};var WOu=class extends po{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[yBh]}convert(){return this.sdkMethodName}};var GOu=class extends po{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[bBh]}convert(){return this.isWebhook}};var HOu=class extends po{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[BBh]??[],...this.input[IBh]??[]],this.codeSamples.forEach(t=>{[...Object.values(Ys.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var Avn=ce(HS());function oKc(e,t){return zv(e)?sL(e,t,void 0):e}function DIh(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var cF="",qYt=class extends po{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(p$i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>p$i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new Avn.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=oKc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=oKc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new Avn.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(UOu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new Avn.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return p$i(n)?[r,{type:"filenameWithData",filename:n.filename,data:Ys.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>p$i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:Ys.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new Avn.UnreachableCaseError(i.multipartType);return}}).filter(No))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new Avn.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new Avn.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(No));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(No));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:DIh(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?CYt(this.name):this.summary!=null?CYt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function BIh(e,t){return zv(e)?sL(e,t,void 0):e}var WIh=ce(HS());var IIh="#/components/schemas/";function Fua(e){if(e.$ref.startsWith(IIh))return e.$ref.replace(IIh,"")}function jUi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function _$i(e){return typeof e.type=="string"&&e.type==="array"}function CIh(e){return e.type==="boolean"}function qIh(e){return e.type==="integer"}function h$i(e){return!Array.isArray(e.type)&&!_$i(e)}function TIh(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||h$i(t)||_$i(t))}function RIh(e){return"nullable"in e&&typeof e.nullable=="boolean"}function zIh(e){return e.type==="null"}function NIh(e){return e.type==="number"}function uKc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function FIh(e){return e.type==="string"}var xOu=class extends eY{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new K0({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return NP(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var KOu=class extends oC{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new WEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var JOu=class extends eY{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new K0({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(No)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>NP(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(No).reduce((n,a)=>n.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(jUi).filter(No):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function $Ou(e){return e!=null&&e.length>0?e:[void 0]}var Qua=class extends eY{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new K0({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new K0({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(zv(t))return Fua(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new K0({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(No))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return Nua(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:NP(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(No)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>$Ou(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>Ys.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=uC(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new K0({input:o,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var YOu=class extends eY{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>uC(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>uC(t,this.context.document)?.type!=="null"?new K0({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(No);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=uC({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new K0({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(No);return this.isNullable&&n!=null?n.map(jUi).filter(No):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Ys.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>NP(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??CYt(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(No)).filter(No)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>NP(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?CYt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?CYt(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(No)).filter(No)}:void 0,i=this.isNullable?jUi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var XOu=class extends oC{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var y$i=class extends oC{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(zv(r)){let n=uC(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(No),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var QIh=ce(HS());function FdB(e){return rKc.includes(e)}var ZOu=class extends oC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(FdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${rKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new QIh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var kOu=class extends oC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return jUi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var UIh=ce(HS());function QdB(e){return tKc.includes(e)}var eAu=class extends oC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(QdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${tKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new UIh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var LIh=ce(HS());function UdB(e){return iKc.includes(e)}var tAu=class extends oC{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new LIh.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(UdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${iKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new y$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var VIh=ce(HS());var rAu=class extends oC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,VIh.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var mvn=class extends eY{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=Fua(this.input);let t=uC(this.input,this.context.document);t?.enum!=null&&h$i(t)&&(this.maybeEnumConverterNode=new y$i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:Ys.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=uC(this.input,this.context.document);if(r!=null)return new K0({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var K0=class e extends eY{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new WEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),h$i(this.input)&&RIh(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),zv(this.input)){let t=Fua(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new mvn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new KOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(TIh(this.input))this.typeShapeNode=new JOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(h$i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new YOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(uKc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new Qua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(h$i(this.input)&&this.input.enum!=null)this.typeShapeNode=new y$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":uKc(this.input)&&(this.typeShapeNode=new Qua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":_$i(this.input)&&(this.typeShapeNode=new xOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":CIh(this.input)&&(this.typeShapeNode=new XOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":qIh(this.input)&&(this.typeShapeNode=new ZOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":NIh(this.input)&&(this.typeShapeNode=new eAu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":FIh(this.input)&&(this.typeShapeNode=new tAu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":zIh(this.input)&&(this.typeShapeNode=new kOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new WIh.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new Qua({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new rAu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!zv(this.input)&&(!_$i(this.input)&&this.input==null||_$i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=NP(t)?.map(i=>this.nullable?jUi(i):i).filter(No);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function b$i(e){if(e!=null)return Nua(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(No))}var TYt=class extends oC{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;zv(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new WEe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new K0({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=BIh(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function GIh(e,t){return zv(e)?sL(e,t,void 0):e}var sKc=ce(HS());function iAu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[Ys.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var HIh=ce(D2s(),1),Uua=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,o){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=o}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=HIh.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function LdB(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var nAu=class extends po{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new K0({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),LdB(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(zv(r)?n=_Ou(r.$ref,this.context.document):n=r,n!=null)return[t,new Rua({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(No)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[Ys.api.latest.AuthSchemeId(t),i]}).filter(No)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=NP(r.convert());return n==null?[t,void 0]:[Ys.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>No(r))):void 0}}};var aAu=class extends K0{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=uC(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${zv(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=uC(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var oAu=class extends po{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=uC(this.input.schema,this.context.document);this.availability=new WEe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=zv(this.input.schema)?new mvn({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=Uua.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new K0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new aAu({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(No))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[cF]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[cF]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:NP(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=f8t([this.method,this.path,this.contentType,"request"].join("_"));return iAu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Ys.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new sKc.UnreachableCaseError(n);return}}).filter(No)}convert(){if(this.schema instanceof mvn)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:Ys.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:Ys.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=NP(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:Ys.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new sKc.UnreachableCaseError(n.multipartType),[]}}).filter(No).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var uAu=class extends po{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=GIh(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new oAu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>NP(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(No)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>NP(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(No)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var xIh={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function KIh(e,t){if(zv(e)){let r=sL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var sAu=ce(HS());var JIh="application/json";var $Ih="application/octet-stream";function YIh(e,t){return e===t||t===cF||e===cF}var FKa=class extends po{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,o,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=o,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,o]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)YIh(c,a)&&(i.add(c),this.examples?.push(new qYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,d$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[o,c]of r){if(a===i){let[d,s,u]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(f=>new qYt({input:{requestExample:u,responseExample:f},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,d$i(s,o),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new qYt({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,d$i(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,o]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new qYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,d$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[cF];if(a!=null)for(let o of a)this.examples?.push(new qYt({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,d$i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=Uua.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=JIh,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new K0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=$Ih,this.contentSubtype=uC(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new K0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=TOu(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[cF]??=[],r[cF]=[{value:this.input.example}]);let i=uC(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=TOu(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[cF]??=[],r[cF]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[cF]??=[],r[cF]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==cF).map(([d,s])=>[c,d,s]));let o=Object.entries(r).filter(([c,d])=>!n.has(c)&&No(d)&&c!==cF);Object.keys(r).every(c=>c===cF)||this.matchExamplesByIndex(a,o),!n.has(cF)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return NP(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new sAu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return NP(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=f8t([this.method,this.path,this.statusCode,"response"].join("_"));return iAu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Ys.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new sAu.UnreachableCaseError(i);return}}).filter(No)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new sAu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var QKa=class extends po{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,o){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=KIh(this.input,this.context.document);if(r==null){this.context.errors.error({message:zv(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new TYt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new FKa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new FKa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(No)}};var cAu=class extends po{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new QKa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new QKa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return $Ou(b$i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(No))})))}).filter(No)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=NP(n?.convert());if(n!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??xIh[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(No)})).filter(No)})).filter(No)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var v$i=class extends po{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new qYt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,d$i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new WEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=l$i(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new GOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(zv(i)){let a=QOu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new TYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new TYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new TYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new HOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new uAu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new cAu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new zua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new NKa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new NKa({input:{[fOu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new WOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>ROu({namespace:NP(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(No),this.xFernExamplesNode=new VOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(No)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:Ys.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(u=>u.convert()).filter(No),n=mIh(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:AIh(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,f)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Ys.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[f]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:b$i(this.queryParameters)?.flat(),headers:b$i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(No)}}).filter(No);let a=this.servers?.map(u=>u.convert()).filter(No),o=this.convertPathToPathParts();if(o==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(u=>u.headers).filter(No);return this.endpointIds.map((u,f)=>({id:Ys.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[f]?.convert()?.map(p=>Ys.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>Ys.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:b$i(this.pathParameters)?.flat(),queryParameters:b$i(this.queryParameters)?.flat(),requestHeaders:b$i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(p=>p.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var Lua=class extends po{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=l$i(t,this.input.servers,this.context,this.accessPath),o=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new v$i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new v$i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new v$i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new v$i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new v$i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(No)}};function lAu(e){return"payloads"in e}var fAu=class extends po{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new Lua({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:l$i(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(No)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{lAu(a)?r[Ys.WebhookId(a.id)]=a:t[Ys.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var dAu=class extends po{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[hBh]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||QOu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new TYt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return Nua(this.globalHeaders,this.requiredProperties)?.flat()}};function XIh(e,t){if(zv(e)){let r=sL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var pAu=class extends po{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let o=XIh(a,this.context.document);if(o!=null)return new Lua({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(No)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{lAu(i)&&(t[Ys.WebhookId(i.id)]=i)}),t),{})}};var _Au=class extends po{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=l$i(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new zua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new FOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new fAu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new pAu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new nAu({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new dAu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Xbe(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=fBh({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:Ys.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function cKc(e,t){if(e instanceof CEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof tS))return;let r=new k3t(e.absoluteFilePath),i=await TEe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new cOu,generatedTypes:{}},d=new _Au({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=wKn(a,d.convert())}return a}var hLh=ce(dKc(),1),yLh=ce(rmu(),1),EPu=require("fs/promises"),bLh=ce(require("http"),1),vLh=ce(require("path"),1);var tzh=require("events"),umu=ce(require("fs"),1),Cvn=ce(require("path"),1);var NRh=ce(require("os"),1),FRh=300,w$i=20,sJa=1e7,QRh=NRh.default.platform();var cOB=QRh==="darwin",CJc=QRh==="win32",E$i=cOB||CJc,URh=3e3,LRh=2e4,qJc=1250;var FYt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(FYt||(FYt={}));var Ivn;(function(e){e.CHANGE="change",e.RENAME="rename"})(Ivn||(Ivn={}));var cJa;(function(e){e.CHANGE="change",e.ERROR="error"})(cJa||(cJa={}));var Hl;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Hl||(Hl={}));var cH;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(cH||(cH={}));var lOB=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),m=g-d,j=g-s,M=m>=t||j>=a;return[g,M]},f=g=>{if(s=g,!o)return;let m=o;o=void 0,e.apply(void 0,m)},p=()=>{O(0)},_=()=>{c&&(p(),f(Date.now()))},h=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,m]=u();return m?y(g):v(g)},v=g=>{let m=g-d,j=g-s,M=t-m,w=a-j,D=Math.min(M,w);return O(D)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},A=(...g)=>{let[m,j]=u(),M=!!c;if(o=g,d=m,(j||!c)&&O(t),j)return M?f(m):h(m)};return A.cancel=p,A.flush=_,A},imu=lOB;var NJc=ce(require("fs"),1),amu=ce(require("path"),1);var KO=ce(require("fs"),1),cL=require("util");var EUi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},QYt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var TJc=ce(require("process"),1),VRh=TJc.default.getuid?!TJc.default.getuid():!1,WRh=1e4,nY=()=>{};var lJa={isChangeErrorOk:e=>{if(!lJa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!VRh&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!lJa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!lJa.isNodeError(e))throw e;if(!lJa.isChangeErrorOk(e))throw e}},sC=lJa;var RJc=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=WRh,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},GRh=new RJc;var SUi=(e,t)=>function(i){return function n(...a){return GRh.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},MUi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var fOB={attempt:{chmod:EUi((0,cL.promisify)(KO.default.chmod),sC.onChangeError),chown:EUi((0,cL.promisify)(KO.default.chown),sC.onChangeError),close:EUi((0,cL.promisify)(KO.default.close),nY),fsync:EUi((0,cL.promisify)(KO.default.fsync),nY),mkdir:EUi((0,cL.promisify)(KO.default.mkdir),nY),realpath:EUi((0,cL.promisify)(KO.default.realpath),nY),stat:EUi((0,cL.promisify)(KO.default.stat),nY),unlink:EUi((0,cL.promisify)(KO.default.unlink),nY),chmodSync:QYt(KO.default.chmodSync,sC.onChangeError),chownSync:QYt(KO.default.chownSync,sC.onChangeError),closeSync:QYt(KO.default.closeSync,nY),existsSync:QYt(KO.default.existsSync,nY),fsyncSync:QYt(KO.default.fsync,nY),mkdirSync:QYt(KO.default.mkdirSync,nY),realpathSync:QYt(KO.default.realpathSync,nY),statSync:QYt(KO.default.statSync,nY),unlinkSync:QYt(KO.default.unlinkSync,nY)},retry:{close:SUi((0,cL.promisify)(KO.default.close),sC.isRetriableError),fsync:SUi((0,cL.promisify)(KO.default.fsync),sC.isRetriableError),open:SUi((0,cL.promisify)(KO.default.open),sC.isRetriableError),readFile:SUi((0,cL.promisify)(KO.default.readFile),sC.isRetriableError),rename:SUi((0,cL.promisify)(KO.default.rename),sC.isRetriableError),stat:SUi((0,cL.promisify)(KO.default.stat),sC.isRetriableError),write:SUi((0,cL.promisify)(KO.default.write),sC.isRetriableError),writeFile:SUi((0,cL.promisify)(KO.default.writeFile),sC.isRetriableError),closeSync:MUi(KO.default.closeSync,sC.isRetriableError),fsyncSync:MUi(KO.default.fsyncSync,sC.isRetriableError),openSync:MUi(KO.default.openSync,sC.isRetriableError),readFileSync:MUi(KO.default.readFileSync,sC.isRetriableError),renameSync:MUi(KO.default.renameSync,sC.isRetriableError),statSync:MUi(KO.default.statSync,sC.isRetriableError),writeSync:MUi(KO.default.writeSync,sC.isRetriableError),writeFileSync:MUi(KO.default.writeFileSync,sC.isRetriableError)}},HRh=fOB;var nmu=ce(require("fs"),1),fJa=ce(require("path"),1);var zJc=()=>{};var dOB=()=>{let e=zJc,t=zJc,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},xRh=dOB;var pOB=()=>{let{promise:e,resolve:t,isPending:r}=xRh(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},KRh=pOB;var JRh={then:e=>{e()}};var $Rh=e=>Array.isArray(e)?e:[e],YRh=e=>typeof e=="function";var _OB=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=$Rh(a).map(H=>YRh(H)?H:G=>H.test(G)),c=H=>o.some(G=>G(H)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},A={},g=new Set,m={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:A},{promise:M,increment:w,decrement:D}=KRh(),B=0,z=(H,G,Ee,se)=>{g.has(G)||B>=n||(B+=1,H.directories.push(G),H.directoriesNames.add(Ee),u.push(G),f.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(G),g.add(G),!(se>=i)&&(B>=n||ee(G,se+1)))},F=(H,G,Ee)=>{g.has(G)||B>=n||(B+=1,H.files.push(G),H.filesNames.add(Ee),_.push(G),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(G),g.add(G))},q=(H,G,Ee,se)=>{g.has(G)||B>=n||(B+=1,H.symlinks.push(G),H.symlinksNames.add(Ee),b.push(G),v.add(Ee),O.propertyIsEnumerable(Ee)||(O[Ee]=[]),O[Ee].push(G),g.add(G),r&&(se>=i||B>=n||ve(G,se+1)))},N=(H,G,Ee,se,Ae)=>{d.aborted||c(G)||(se.isDirectory()?z(H,G,Ee,Ae):se.isFile()?F(H,G,Ee):se.isSymbolicLink()&&q(H,G,Ee,Ae))},Q=(H,G,Ee,se)=>{if(d.aborted)return;let Ae=G===fJa.default.sep?"":fJa.default.sep,Fe=Ee.name,oe=`${G}${Ae}${Fe}`;c(oe)||(Ee.isDirectory()?z(H,oe,Fe,se):Ee.isFile()?F(H,oe,Fe):Ee.isSymbolicLink()&&q(H,oe,Fe,se))},x=(H,G,Ee,se)=>{for(let Ae=0,Fe=Ee.length;Ae<Fe;Ae++)Q(H,G,Ee[Ae],se)},ee=(H,G)=>{d.aborted||G>i||B>=n||(w(),nmu.default.readdir(H,{withFileTypes:!0},(Ee,se)=>{if(Ee||d.aborted||!se.length)return D();(s(se)||JRh).then(()=>{let Fe=A[H]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};x(Fe,H,se,G),D()})}))},ve=(H,G)=>{w(),nmu.default.realpath(H,(Ee,se)=>{if(Ee||d.aborted)return D();nmu.default.stat(se,(Ae,Fe)=>{if(Ae||d.aborted)return D();let oe=fJa.default.basename(se),ne=A[H]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};N(ne,se,oe,Fe,G),D()})})};return(async(H,G=1)=>(H=fJa.default.normalize(H),g.add(H),ee(H,G),await M,d.aborted?m:j))(e)},XRh=_OB;var UYt={lang:{debounce:imu,attempt:e=>{try{return e()}catch(t){return UYt.lang.castError(t)}},castArray:e=>UYt.lang.isArray(e)?e:[e],castError:e=>UYt.lang.isError(e)?e:UYt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(UYt.lang.isNaN(e))return UYt.lang.isNaN(t);if(UYt.lang.isPrimitive(e)||UYt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(amu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?NJc.default.realpathSync.native(e):NJc.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===amu.default.sep&&t.length-e.length>amu.default.sep.length,poll:(e,t=LRh)=>HRh.retry.stat(t)(e,{bigint:!0}).catch(UYt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await XRh(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Dp=UYt;var omu=ce(require("path"),1);var FJc=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Dp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=FRh){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=Dp.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Hl.CHANGE&&c===Hl.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Hl.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Hl.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??w$i:Math.min(1,this.options.depth??w$i),o=this.options.limit??sJa,[c,d]=await Dp.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Dp.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Hl.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!E$i&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Hl.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Hl.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(omu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Hl.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(omu.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Hl.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Hl.ADD?this.onTargetAdd(i):r===Hl.ADD_DIR?this.onTargetAddDir(i):r===Hl.CHANGE?this.onTargetChange(i):r===Hl.UNLINK?this.onTargetUnlink(i):r===Hl.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Ivn.CHANGE,r){if(this.watcher.isClosed())return;let i=omu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){CJc&&t.code==="EPERM"?this.onWatcherChange(Ivn.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(cJa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(cJa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Ivn.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&E$i&&this.options.native!==!1?this.options.depth??w$i:Math.min(1,this.options.depth??w$i),i=this.options.limit??sJa,[n,a]=await Dp.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(Ivn.CHANGE,c,t)}))}}},ZRh=FJc;var lH={interval:100,intervalId:void 0,fns:new Map,init:()=>{lH.intervalId||(lH.intervalId=setInterval(lH.resolve,lH.interval))},reset:()=>{lH.intervalId&&(clearInterval(lH.intervalId),delete lH.intervalId)},add:(e,t)=>{lH.fns.set(e,Date.now()+t),lH.init()},remove:e=>{lH.fns.delete(e)},resolve:()=>{if(!lH.fns.size)return lH.reset();let e=Date.now();for(let[t,r]of lH.fns)r>=e||(lH.remove(t),t())}},dJa=lH;var pJa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=qJc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(Dp.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),dJa.remove(s)},s=()=>{d(),c()};dJa.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=qJc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),dJa.remove(s)},s=()=>{d(),c()};dJa.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Hl.ADD,FYt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Hl.ADD_DIR,FYt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Hl.UNLINK,FYt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Hl.UNLINK_DIR,FYt.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};pJa.DIR_EVENTS={add:Hl.ADD_DIR,rename:Hl.RENAME_DIR,unlink:Hl.UNLINK_DIR};pJa.FILE_EVENTS={add:Hl.ADD,change:Hl.CHANGE,rename:Hl.RENAME,unlink:Hl.UNLINK};var kRh=pJa;var QJc=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Dp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Dp.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Dp.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Dp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Dp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Dp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},UJc=QJc;var LJc=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},ezh=LJc;var VJc=class{constructor(){this.inos={},this.paths=new UJc,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Dp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new ezh(i)}reset(){this.inos={},this.paths=new UJc,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Hl.ADD,n),[Hl.ADD];if(n.isDirectory())return this.updateIno(t,Hl.ADD_DIR,n),[Hl.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Hl.UNLINK,i),[Hl.UNLINK];if(i.isDirectory())return this.updateIno(t,Hl.UNLINK_DIR,i),[Hl.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Hl.CHANGE,n),[Hl.CHANGE]);if(n.isDirectory())return this.updateIno(t,Hl.UNLINK,i),this.updateIno(t,Hl.ADD_DIR,n),[Hl.UNLINK,Hl.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Hl.UNLINK_DIR,i),this.updateIno(t,Hl.ADD,n),[Hl.UNLINK_DIR,Hl.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Hl.UNLINK_DIR,i),this.updateIno(t,Hl.ADD_DIR,n),[Hl.UNLINK_DIR,Hl.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?FYt.FILE:FYt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},WJc=VJc;var GJc=class e extends tzh.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(cH.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(cH.CLOSE,n)),this._readyWait=new Promise(n=>this.on(cH.READY,n)),this._locker=new kRh(this),this._roots=new Set,this._poller=new WJc,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Dp.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(cH.CLOSE))}error(t){if(this.isClosed())return!1;let r=Dp.lang.castError(t);return this.emit(cH.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(cH.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(cH.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Dp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Dp.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Dp.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new ZRh(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Dp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=Cvn.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??w$i))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&E$i&&u.options.native!==!1)))return!0;if(!E$i)break;let s=Cvn.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Dp.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||E$i&&r.native!==!1?r:{...r,recursive:!1},u={watcher:umu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=Cvn.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,f)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||E$i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??w$i,c=r.limit??sJa,[d]=await Dp.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=Dp.fs.getDepth(t);for(let f of d){let p=Dp.fs.getDepth(f),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([f],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(cH.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(cH.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=Cvn.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new WJc,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Dp.lang.noop;if(this.pollerExists(t,r))return Dp.lang.noop;let n={...r,interval:r.pollingInterval??URh},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(cH.CLOSE,c),umu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(cH.CLOSE,c),umu.default.unwatchFile(t,i)};return Dp.lang.attempt(o),()=>Dp.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Dp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Dp.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=Cvn.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Dp.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=Cvn.default.dirname(t);return(await Dp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Dp.lang.noop){if(Dp.lang.isFunction(t))return this.watch([],{},t);if(Dp.lang.isUndefined(t))return this.watch([],r,i);if(Dp.lang.isFunction(r))return this.watch(t,{},r);if(Dp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Dp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Dp.lang.noop&&this.on(cH.ALL,i),r.readdirMap=void 0,this.ready())}},smu=GJc;TXo();var isa=require("fs/promises"),rzh=require("os"),izh=ce(require("path"),1),hOB=".fern",yOB="logs";function bOB(){return"cli@3.43.0"}var _Ja=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Ct(Sr.of((0,rzh.homedir)()),He.of(hOB)),r=Ct(t,He.of(yOB));await mi(r)||await(0,isa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Ct(r,He.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${izh.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
1836
1836
  `);await(0,isa.writeFile)(this.logFilePath,a,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
1837
1837
  `;try{await(0,isa.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 i={timestamp:t.timestamp,source:bOB(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(i)}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 i={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliDocsGeneration(t,r){let i={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliValidation(t,r){let i={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(i)}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 bYc=ce(kJc(),1),$4h=ce(kmu(),1),aY=require("fs/promises"),Y4h=require("os"),X4h=ce(e4(),1),Z4h=ce(K4h(),1),yPu=process.platform==="win32",yYc=qt.cyan("[docs]:"),NjB="etag",FjB=23,J4h=e=>e.padEnd(FjB," "),QjB="preview",UjB="app-preview",LjB="bundle",VjB=".next",WjB="standalone",GjB=".fern",HjB="packages/fern-docs/bundle/.next/server/instrumentation.js",xjB=".npmrc",KjB=".pnpmfile.cjs",JjB="pnpm-workspace.yaml",$jB='Cannot find matching keyid: {"signatures":';function YjB(){return Ct(Sr.of((0,Y4h.homedir)()),He.of(GjB))}function Osa({app:e=!1}){return Ct(YjB(),He.of(e?UjB:QjB))}function R$i({app:e=!1}){return Ct(Osa({app:e}),He.of(e?VjB:LjB))}function FJa({app:e=!1}){return Ct(R$i({app:e}),He.of(WjB))}function XjB({app:e=!1}){return Ct(FJa({app:e}),He.of(HjB))}function ZjB({app:e=!1}){return Ct(FJa({app:e}),He.of(JjB))}function kjB({app:e=!1}){return Ct(FJa({app:e}),He.of(KjB))}function e0B({app:e=!1}){return Ct(FJa({app:e}),He.of(xjB))}function Qvn(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function t0B({app:e=!1}){return Ct(Osa({app:e}),He.of(NjB))}var r0B=`module.exports = {
1838
1838
  hooks: {
@@ -1923,7 +1923,7 @@ Found ${d.length} preview deployment(s):
1923
1923
  `));for(let s of d){let u=new Date(s.updatedAt).toLocaleString();n.logger.info(` ${qt.cyan(s.url)}`),n.logger.info(` Organization: ${s.organizationId}`),n.logger.info(` Updated: ${u}
1924
1924
  `)}})}var d8h=require("fs/promises");var o8h=Symbol.for("immer-nothing"),t8h=Symbol.for("immer-draftable"),kve=Symbol.for("immer-state"),CSB=process.env.NODE_ENV!=="production"?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function uY(e,...t){if(process.env.NODE_ENV!=="production"){let r=CSB[e],i=typeof r=="function"?r.apply(null,t):r;throw new Error(`[Immer] ${i}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var qsa=Object.getPrototypeOf;function Tsa(e){return!!e&&!!e[kve]}function xvn(e){return e?u8h(e)||Array.isArray(e)||!!e[t8h]||!!e.constructor?.[t8h]||ZJa(e)||bju(e):!1}var qSB=Object.prototype.constructor.toString();function u8h(e){if(!e||typeof e!="object")return!1;let t=qsa(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===qSB}function pju(e,t){yju(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,i)=>t(i,r,e))}function yju(e){let t=e[kve];return t?t.type_:Array.isArray(e)?1:ZJa(e)?2:bju(e)?3:0}function RXc(e,t){return yju(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function s8h(e,t,r){let i=yju(e);i===2?e.set(t,r):i===3?e.add(r):e[t]=r}function TSB(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function ZJa(e){return e instanceof Map}function bju(e){return e instanceof Set}function Hvn(e){return e.copy_||e.base_}function zXc(e,t){if(ZJa(e))return new Map(e);if(bju(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=u8h(e);if(t===!0||t==="class_only"&&!r){let i=Object.getOwnPropertyDescriptors(e);delete i[kve];let n=Reflect.ownKeys(i);for(let a=0;a<n.length;a++){let o=n[a],c=i[o];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(i[o]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[o]})}return Object.create(qsa(e),i)}else{let i=qsa(e);if(i!==null&&r)return{...e};let n=Object.create(i);return Object.assign(n,e)}}function LXc(e,t=!1){return vju(e)||Tsa(e)||!xvn(e)||(yju(e)>1&&Object.defineProperties(e,{set:{value:dju},add:{value:dju},clear:{value:dju},delete:{value:dju}}),Object.freeze(e),t&&Object.values(e).forEach(r=>LXc(r,!0))),e}function dju(){uY(2)}function vju(e){return Object.isFrozen(e)}var RSB={};function Kvn(e){let t=RSB[e];return t||uY(0,e),t}var YJa;function c8h(){return YJa}function zSB(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function r8h(e,t){t&&(Kvn("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function NXc(e){FXc(e),e.drafts_.forEach(NSB),e.drafts_=null}function FXc(e){e===YJa&&(YJa=e.parent_)}function i8h(e){return YJa=zSB(YJa,e)}function NSB(e){let t=e[kve];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function n8h(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[kve].modified_&&(NXc(t),uY(4)),xvn(e)&&(e=_ju(t,e),t.parent_||hju(t,e)),t.patches_&&Kvn("Patches").generateReplacementPatches_(r[kve].base_,e,t.patches_,t.inversePatches_)):e=_ju(t,r,[]),NXc(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==o8h?e:void 0}function _ju(e,t,r){if(vju(t))return t;let i=t[kve];if(!i)return pju(t,(n,a)=>a8h(e,i,t,n,a,r)),t;if(i.scope_!==e)return t;if(!i.modified_)return hju(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;let n=i.copy_,a=n,o=!1;i.type_===3&&(a=new Set(n),n.clear(),o=!0),pju(a,(c,d)=>a8h(e,i,n,c,d,r,o)),hju(e,n,!1),r&&e.patches_&&Kvn("Patches").generatePatches_(i,r,e.patches_,e.inversePatches_)}return i.copy_}function a8h(e,t,r,i,n,a,o){if(process.env.NODE_ENV!=="production"&&n===r&&uY(5),Tsa(n)){let c=a&&t&&t.type_!==3&&!RXc(t.assigned_,i)?a.concat(i):void 0,d=_ju(e,n,c);if(s8h(r,i,d),Tsa(d))e.canAutoFreeze_=!1;else return}else o&&r.add(n);if(xvn(n)&&!vju(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;_ju(e,n),(!t||!t.scope_.parent_)&&typeof i!="symbol"&&(ZJa(r)?r.has(i):Object.prototype.propertyIsEnumerable.call(r,i))&&hju(e,n)}}function hju(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&LXc(t,r)}function FSB(e,t){let r=Array.isArray(e),i={type_:r?1:0,scope_:t?t.scope_:c8h(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=i,a=VXc;r&&(n=[i],a=XJa);let{revoke:o,proxy:c}=Proxy.revocable(n,a);return i.draft_=c,i.revoke_=o,c}var VXc={get(e,t){if(t===kve)return e;let r=Hvn(e);if(!RXc(r,t))return QSB(e,r,t);let i=r[t];return e.finalized_||!xvn(i)?i:i===qXc(e.base_,t)?(TXc(e),e.copy_[t]=UXc(i,e)):i},has(e,t){return t in Hvn(e)},ownKeys(e){return Reflect.ownKeys(Hvn(e))},set(e,t,r){let i=l8h(Hvn(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){let n=qXc(Hvn(e),t),a=n?.[kve];if(a&&a.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(TSB(r,n)&&(r!==void 0||RXc(e.base_,t)))return!0;TXc(e),QXc(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return qXc(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,TXc(e),QXc(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Hvn(e),i=Reflect.getOwnPropertyDescriptor(r,t);return i&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:i.enumerable,value:r[t]}},defineProperty(){uY(11)},getPrototypeOf(e){return qsa(e.base_)},setPrototypeOf(){uY(12)}},XJa={};pju(VXc,(e,t)=>{XJa[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});XJa.deleteProperty=function(e,t){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(t))&&uY(13),XJa.set.call(this,e,t,void 0)};XJa.set=function(e,t,r){return process.env.NODE_ENV!=="production"&&t!=="length"&&isNaN(parseInt(t))&&uY(14),VXc.set.call(this,e[0],t,r,e[0])};function qXc(e,t){let r=e[kve];return(r?Hvn(r):e)[t]}function QSB(e,t,r){let i=l8h(t,r);return i?"value"in i?i.value:i.get?.call(e.draft_):void 0}function l8h(e,t){if(!(t in e))return;let r=qsa(e);for(;r;){let i=Object.getOwnPropertyDescriptor(r,t);if(i)return i;r=qsa(r)}}function QXc(e){e.modified_||(e.modified_=!0,e.parent_&&QXc(e.parent_))}function TXc(e){e.copy_||(e.copy_=zXc(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var USB=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,i)=>{if(typeof t=="function"&&typeof r!="function"){let a=r;r=t;let o=this;return function(d=a,...s){return o.produce(d,u=>r.call(this,u,...s))}}typeof r!="function"&&uY(6),i!==void 0&&typeof i!="function"&&uY(7);let n;if(xvn(t)){let a=i8h(this),o=UXc(t,void 0),c=!0;try{n=r(o),c=!1}finally{c?NXc(a):FXc(a)}return r8h(a,i),n8h(n,a)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===o8h&&(n=void 0),this.autoFreeze_&&LXc(n,!0),i){let a=[],o=[];Kvn("Patches").generateReplacementPatches_(t,n,a,o),i(a,o)}return n}else uY(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(o,...c)=>this.produceWithPatches(o,d=>t(d,...c));let i,n;return[this.produce(t,r,(o,c)=>{i=o,n=c}),i,n]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){xvn(e)||uY(8),Tsa(e)&&(e=LSB(e));let t=i8h(this),r=UXc(e,void 0);return r[kve].isManual_=!0,FXc(t),r}finishDraft(e,t){let r=e&&e[kve];(!r||!r.isManual_)&&uY(9);let{scope_:i}=r;return r8h(i,t),n8h(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let n=t[r];if(n.path.length===0&&n.op==="replace"){e=n.value;break}}r>-1&&(t=t.slice(r+1));let i=Kvn("Patches").applyPatches_;return Tsa(e)?i(e,t):this.produce(e,n=>i(n,t))}};function UXc(e,t){let r=ZJa(e)?Kvn("MapSet").proxyMap_(e,t):bju(e)?Kvn("MapSet").proxySet_(e,t):FSB(e,t);return(t?t.scope_:c8h()).drafts_.push(r),r}function LSB(e){return Tsa(e)||uY(10,e),f8h(e)}function f8h(e){if(!xvn(e)||vju(e))return e;let t=e[kve],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=zXc(e,t.scope_.immer_.useStrictShallowCopy_)}else r=zXc(e,!0);return pju(r,(i,n)=>{s8h(r,i,f8h(n))}),t&&(t.finalized_=!1),r}var VSB=new USB,gju=VSB.produce;function WSB(e){return e.endsWith(`
1925
1925
  `)?e:e+`
1926
- `}async function p8h({cliContext:e,targetVersion:t}){if(!t)return e.failAndThrow("Please specify a version to downgrade to using --version");let r=await $E();if(r==null)return e.failAndThrow(`Directory "${CT}" not found.`);let i=await e.runTask(a=>Nbe({directory:r,context:a})),n=gju(i.rawConfig,a=>{a.version=t});await(0,d8h.writeFile)(i._absolutePath,WSB(JSON.stringify(n,void 0,2))),e.logger.info(`Updated ${JU} to version ${t}`)}var jju=require("fs/promises");var Jvn=ce(svu(),1),y8h=ce(ng(),1);function _8h(e,t){let r=e.shape,i=e.docs??void 0;return{openApiSchema:fl._visit(r,{alias:a=>GSB({aliasTypeDeclaration:a,docs:i}),enum:a=>HSB({enumTypeDeclaration:a,docs:i}),object:a=>{let o=e.userProvidedExamples[0],c=o==null?YSB(t,e.name):void 0,d=o==null&&c==null?XSB(t,e.name):void 0;return Aju({properties:a.properties.map(s=>{let u;return o!=null&&o.shape.type==="object"?u=o.shape.properties.find(f=>f.name.wireValue===s.name.wireValue):c!=null?c.type==="reference"&&c.shape.type==="named"&&c.shape.shape.type==="object"&&(u=c.shape.shape.properties.find(f=>f.name.wireValue===s.name.wireValue)):d!=null&&d.type==="body"&&d.value?.shape.type==="named"&&d.value.shape.shape.type==="object"&&(u=d.value.shape.shape.properties.find(f=>f.name.wireValue===s.name.wireValue)),{docs:s.docs??void 0,name:s.name,valueType:s.valueType,example:u}}),extensions:a.extends,docs:i})},union:a=>xSB({unionTypeDeclaration:a,docs:i}),undiscriminatedUnion:a=>KSB({undiscriminatedUnionDeclaration:a,docs:i}),_other:()=>{throw new Error("Encountered unknown type: "+r.type)}}),schemaName:h8h(e.name)}}function GSB({aliasTypeDeclaration:e,docs:t}){return{...lC(e.aliasOf),description:t}}function HSB({enumTypeDeclaration:e,docs:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue),description:t}}function xSB({unionTypeDeclaration:e,docs:t}){let i={oneOf:e.types.map(n=>{let a={[e.discriminant.wireValue]:{type:"string",enum:[n.discriminantValue.wireValue]}};return zN._visit(n.shape,{noProperties:()=>({type:"object",properties:a,required:[e.discriminant.wireValue]}),singleProperty:o=>({type:"object",properties:{...a,[o.name.wireValue]:lC(o.type)},required:[e.discriminant.wireValue]}),samePropertiesAsObject:o=>({type:"object",allOf:[{type:"object",properties:a},{$ref:Oju(o)}],required:[e.discriminant.wireValue]}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+n.shape.propertiesType)}})}),description:t};return e.baseProperties.length>0&&(i.properties=e.baseProperties.reduce((n,a)=>(n[a.name.wireValue]={description:a.docs??void 0,...lC(a.valueType)},a.valueType.type==="container"&&a.valueType.container.type==="optional"||(i.required=[...i.required??[],a.name.wireValue]),n),{})),i}function KSB({undiscriminatedUnionDeclaration:e,docs:t}){return{oneOf:e.members.map(r=>({description:r.docs??void 0,...lC(r.type)})),description:t}}function lC(e){return kr._visit(e,{container:t=>$SB(t),named:t=>({$ref:Oju(t)}),primitive:t=>JSB(t),unknown:()=>({}),_other:()=>{throw new Error("Encountered unknown typeReference: "+e.type)}})}function JSB(e){return e.v2==null?Vu._visit(e.v1,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:()=>({type:"string"}),uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),_other:()=>{throw new Error("Encountered unknown primitiveType: "+e.v1)}})??{}:pn._visit(e.v2,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:t=>{let r={type:"string"};return t.validation?.format!=null&&(r.format=t.validation.format),t.validation?.pattern!=null&&(r.pattern=t.validation.pattern),r},uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),_other:()=>{throw new Error("Encountered unknown primitiveType: "+e.v2)}})}function $SB(e){return hs._visit(e,{list:t=>({type:"array",items:lC(t)}),set:t=>({type:"array",items:lC(t)}),map:t=>t.keyType.type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType.type==="unknown"?{type:"object",additionalProperties:!0}:{type:"object",additionalProperties:lC(t.valueType)},optional:t=>({...lC(t),nullable:!0}),nullable:t=>({...lC(t),nullable:!0}),literal:t=>t._visit({boolean:r=>({type:"boolean",const:r}),string:r=>({type:"string",const:r}),_other:()=>({})}),_other:()=>{throw new Error("Encountered unknown containerType: "+e.type)}})}function Oju(e){return`#/components/schemas/${h8h(e)}`}function h8h(e){return[...e.fernFilepath.packagePath.map(t=>t.originalName),e.name.originalName].join("")}function YSB(e,t){for(let r of Object.values(e.services))for(let i of r.endpoints)if(!(i.userSpecifiedExamples.length<=0)&&i.requestBody?.type==="reference"&&i.requestBody.requestBodyType.type==="named"&&ZSB(i.requestBody.requestBodyType,t))return i.userSpecifiedExamples[0]?.example?.request??void 0}function XSB(e,t){for(let r of Object.values(e.services))for(let i of r.endpoints)if(!(i.userSpecifiedExamples.length<=0||i.response?.body?.type!=="json")&&i.response.body.value.responseBodyType.type==="named"&&i.response.body.value.responseBodyType.typeId===t.typeId){let n=i.userSpecifiedExamples.find(a=>a.example?.response.type==="ok");if(n!=null&&n.example?.response.type==="ok")return n.example.response.value}}function ZSB(e,t){return BT(e.fernFilepath,t.fernFilepath)&&BT(e.name,t.name)}function Aju({docs:e,properties:t,extensions:r}){let i={},n=[];t.forEach(o=>{let c=lC(o.valueType),d;(o.example!=null&&o.valueType.type==="primitive"||o.example!=null&&o.valueType.type==="container"&&o.valueType.container.type==="list"&&o.valueType.container.list.type==="primitive")&&(d=o.example.value.jsonExample),i[o.name.wireValue]={...c,description:o.docs??void 0,example:d},o.valueType.type==="container"&&o.valueType.container.type==="optional"||n.push(o.name.wireValue)});let a={type:"object",description:e,properties:i};return n.length>0&&(a.required=n),r.length>0&&(a.allOf=r.map(o=>({$ref:Oju(o)}))),a}function b8h({ir:e,httpServices:t,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c}){let d={};return t.forEach(s=>{s.endpoints.forEach(u=>{let{fullPath:f,convertedHttpMethod:p,operationObject:_}=kSB({ir:e,httpEndpoint:u,httpService:s,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c}),h=d[f]??={};if(h[p]!=null)throw new Error(`Duplicate ${p} endpoint at ${f}`);h[p]=_})}),d}function kSB({httpEndpoint:e,httpService:t,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c,ir:d}){let s=(0,y8h.default)(d.basePath!=null?GXc(d.basePath):"",GXc(t.basePath),GXc(e.path));s=s.startsWith("/")?s:`/${s}`;let u=eMB(e.method),f=d.pathParameters.map(A=>WXc({pathParameter:A,examples:e.userSpecifiedExamples.map(g=>g.example).filter(ds)??[]})),p=t.pathParameters.map(A=>WXc({pathParameter:A,examples:e.userSpecifiedExamples.map(g=>g.example).filter(ds)??[]})),_=e.pathParameters.map(A=>WXc({pathParameter:A,examples:e.userSpecifiedExamples.map(g=>g.example).filter(ds)??[]})),h=e.queryParameters.map(A=>aMB({queryParameter:A,typesByName:r,examples:e.userSpecifiedExamples.map(g=>g.example).filter(ds)??[]})),y=e.headers.map(A=>oMB({httpHeader:A,typesByName:r,examples:e.userSpecifiedExamples.map(g=>g.example).filter(ds)??[]})),b=[...f,...p,..._,...h,...y],v=c==="stoplight"?t.displayName??t.name.fernFilepath.allParts.map(A=>A.originalName).join(" "):t.name.fernFilepath.allParts.map(A=>A.pascalCase.unsafeName).join(""),O={description:e.docs??void 0,operationId:[...t.name.fernFilepath.allParts.map(A=>A.camelCase.unsafeName),e.name.originalName].join("_"),tags:[v],parameters:b,responses:rMB({httpResponse:e.response,responseErrors:e.errors,errorsByName:i,errorDiscriminationStrategy:n,examples:e.userSpecifiedExamples.map(A=>A.example).filter(ds)??[]}),summary:e.displayName??void 0};if(e.baseUrl!=null){let A=e.baseUrl;if(o?.environments.type!=="multipleBaseUrls")throw new Error("baseUrl is defined environments are not multipleBaseUrls");O.servers=o.environments.environments.map(g=>{let m=g.urls[A];if(m==null)throw new Error("No URL defined for "+A);let j={url:m};return g.docs!=null&&(j.description=g.docs),j})}return e.auth&&(O.security=a),e.requestBody!=null&&(O.requestBody=tMB({httpRequest:e.requestBody,typesByName:r,examples:e.userSpecifiedExamples.map(A=>A.example).filter(ds)??[]})),{fullPath:s,convertedHttpMethod:u,operationObject:O}}function eMB(e){return U0._visit(e,{get:()=>Jvn.OpenAPIV3.HttpMethods.GET,post:()=>Jvn.OpenAPIV3.HttpMethods.POST,put:()=>Jvn.OpenAPIV3.HttpMethods.PUT,patch:()=>Jvn.OpenAPIV3.HttpMethods.PATCH,delete:()=>Jvn.OpenAPIV3.HttpMethods.DELETE,head:()=>Jvn.OpenAPIV3.HttpMethods.HEAD,_other:()=>{throw new Error("Encountered unknown http method: "+e)}})}function tMB({httpRequest:e,typesByName:t,examples:r}){let i={};for(let n of r)n.request!=null&&(n.name&&n.name.originalName!==""?i[n.name.originalName]={value:n.request.jsonExample}:i[`Example${Am(i)+1}`]={value:n.request.jsonExample});return vA._visit(e,{inlinedRequestBody:n=>{let a={schema:Aju({docs:void 0,properties:n.properties.map(o=>{let c;return r.length>0&&r[0]?.request?.type==="inlinedRequestBody"&&(c=r[0]?.request.properties.find(d=>d.name.wireValue===o.name.wireValue)),{docs:o.docs??void 0,name:o.name,valueType:o.valueType,example:c}}),extensions:n.extends})};return Am(i)>0&&(a.examples=i),{required:!0,content:{"application/json":a}}},reference:n=>{let a={schema:lC(n.requestBodyType)};return Am(i)>0&&(a.examples=i),{description:n.docs??void 0,required:mju({typeReference:n.requestBodyType,typesByName:t}),content:{"application/json":a}}},fileUpload:n=>({required:!0,content:{"multipart/form-data":{schema:{type:"object",properties:n.properties.reduce((a,o)=>(r1._visit(o,{file:c=>{a[c.key.wireValue]={type:"string",format:"binary"}},bodyProperty:c=>{a[c.name.wireValue]={description:c.docs??void 0,...lC(c.valueType)}},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}}),{...a}),{})}}}}),bytes:()=>{throw new Error("bytes is not supported")},_other:()=>{throw new Error("Unknown HttpRequestBody type: "+e.type)}})}function rMB({httpResponse:e,responseErrors:t,errorsByName:r,errorDiscriminationStrategy:i,examples:n}){let a={};if(e?.body?.type==="json"){let o={schema:lC(e.body.value.responseBodyType)},c={};for(let d of n)d.response.type==="ok"&&d.response.value.type==="body"&&d.response.value.value!=null&&(d.name&&d.name.originalName!==""?c[d.name.originalName]={value:d.response.value.value.jsonExample}:c[`Example${Am(c)+1}`]={value:d.response.value.value.jsonExample});Am(c)>0&&(o.examples=c),a[String(e.statusCode??200)]={description:e.body.value.docs??"",content:{"application/json":o}}}else a[204]={description:""};return pve._visit(i,{statusCode:()=>{for(let o of t){let c=r[Pju(o.error)];if(c==null)throw new Error("Encountered undefined error declaration: "+o.error.name.originalName);let d={description:o.docs??""};if(c.type!=null){let s={schema:lC(c.type)},u={};for(let f of n)f.response.type==="error"&&f.response.body!=null&&BT(o.error,f.response.error)&&(f.name&&f.name.originalName!==""?u[f.name.originalName]={value:f.response.body.jsonExample}:u[`Example${Am(u)+1}`]={value:f.response.body.jsonExample});Am(u)>0&&(s.examples=u),d.content={"application/json":s}}a[c.statusCode]=d}},property:o=>{let c=nMB({responseErrors:t,errorsByName:r});for(let d of Object.keys(c)){let s=c[d];if(s==null||s.length===0)continue;let u={schema:{oneOf:s.map(p=>iMB({errorInfo:p,property:o}))}},f={};for(let p of n)if(p.response.type==="error"&&p.response.body!=null){let _=p.response.error;s.some(h=>BT(h.errorDeclaration.name,_))&&(p.name&&p.name.originalName!==""?f[p.name.originalName]={value:p.response.body.jsonExample}:f[`Example${Am(f)+1}`]={value:p.response.body.jsonExample})}Am(f)>0&&(u.examples=f),a[d]={description:"",content:{"application/json":u}}}},_other:()=>{throw new Error("Unknown error discrimination strategy: "+i.type)}}),a}function iMB({errorInfo:e,property:t}){let r=e.errorDeclaration.discriminantValue.wireValue,i=e.responseError.docs??void 0,n={[t.discriminant.wireValue]:{type:"string",enum:[r]}};return e.errorDeclaration.type!=null&&(n[t.contentProperty.wireValue]=lC(e.errorDeclaration.type)),{type:"object",description:i,properties:n}}function nMB({responseErrors:e,errorsByName:t}){let r={};for(let i of e){let n=t[Pju(i.error)];if(n==null)throw new Error("Encountered undefined error declaration: "+i.error.name.originalName);let a=n.statusCode,o=r[a];o==null?r[a]=[{responseError:i,errorDeclaration:n}]:o.push({responseError:i,errorDeclaration:n})}return r}function WXc({pathParameter:e,examples:t}){let r={name:e.name.originalName,in:"path",description:e.docs??void 0,required:!0,schema:lC(e.valueType)},i={};for(let n of t){let a=[...n.rootPathParameters,...n.servicePathParameters,...n.endpointPathParameters].find(o=>o.name.originalName===e.name.originalName);a!=null&&(n.name&&n.name.originalName!==""?i[n.name.originalName]={value:a.value.jsonExample}:i[`Example${Am(i)+1}`]={value:a.value.jsonExample},r.example==null&&(r.example=a.value.jsonExample))}return Am(i)>0&&(r.examples=i),r}function aMB({queryParameter:e,typesByName:t,examples:r}){let i={name:e.name.wireValue,in:"query",description:e.docs??void 0,required:mju({typeReference:e.valueType,typesByName:t}),schema:e.allowMultiple?lC(kr.container(hs.list(e.valueType))):lC(e.valueType)},n={};for(let a of r){let o=a.queryParameters.find(c=>c.name.wireValue===e.name.wireValue);o!=null&&(a.name&&a.name.originalName!==""?n[a.name.originalName]={value:o.value.jsonExample}:n[`Example${Am(n)+1}`]={value:o.value.jsonExample},i.example==null&&(i.example=o.value.jsonExample))}return Am(n)>0&&(i.examples=n),i}function oMB({httpHeader:e,typesByName:t,examples:r}){let i={name:e.name.wireValue,in:"header",description:e.docs??void 0,required:mju({typeReference:e.valueType,typesByName:t}),schema:lC(e.valueType)},n={};for(let a of r){let o=[...a.serviceHeaders,...a.endpointHeaders].find(c=>c.name.wireValue===e.name.wireValue);o!=null&&(a.name&&a.name.originalName!==""?n[a.name.originalName]={value:o.value.jsonExample}:n[`Example${Am(n)+1}`]={value:o.value.jsonExample},i.example==null&&(i.example=o.value.jsonExample))}return Am(n)>0&&(i.examples=n),i}function GXc(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return t}function mju({typeReference:e,typesByName:t}){if(e.type==="container"&&e.container.type==="optional")return!1;if(e.type==="named"){let r=HXc(e),i=t[r];if(i==null)throw new Error("Encountered non-existent type: "+e.name.originalName);if(i.shape.type==="alias")return mju({typeReference:i.shape.aliasOf,typesByName:t})}return!0}function v8h(e){return nR._visit(e.requirement,{all:()=>[e.schemes.reduce((t,r)=>({...t,[xXc(r)]:[]}),{})],any:()=>e.schemes.map(t=>({[xXc(t)]:[]})),endpointSecurity:()=>[],_other:()=>{throw new Error("Unknown auth scheme requirement: "+e.requirement)}})}function g8h(e){let t={};for(let r of e.schemes){let i=im._visit(r,{bearer:()=>({type:"http",scheme:"bearer"}),basic:()=>({type:"http",scheme:"basic"}),header:n=>({type:"apiKey",in:"header",name:n.name.wireValue}),oauth:()=>({type:"http",scheme:"bearer"}),inferred:()=>{},_other:()=>{throw new Error("Unknown auth scheme: "+r.type)}});i&&(t[xXc(r)]=i)}return t}function xXc(e){return im._visit(e,{bearer:()=>"BearerAuth",inferred:()=>"InferredAuth",basic:()=>"BasicAuth",oauth:()=>"BearerAuth",header:t=>`${t.name.name.pascalCase.unsafeName}Auth`,_other:()=>{throw new Error("Unknown auth scheme: "+e.type)}})}function O8h({apiName:e,ir:t,mode:r}){let i={},n={};Object.values(t.types).forEach(u=>{let f=_8h(u,t);i[f.schemaName]={title:f.schemaName,...f.openApiSchema},n[HXc(u.name)]=u});let a={};Object.values(t.errors).forEach(u=>{a[Pju(u.name)]=u});let o=v8h(t.auth),c=b8h({ir:t,httpServices:Object.values(t.services),typesByName:n,errorsByName:a,errorDiscriminationStrategy:t.errorDiscriminationStrategy,security:o,environments:t.environments??void 0,mode:r}),d={title:t.apiDisplayName??e,version:""};t.apiDocs!=null&&(d.description=t.apiDocs);let s={openapi:"3.0.1",info:d,paths:c,components:{schemas:i,securitySchemes:g8h(t.auth)}};return t.environments!=null&&t.environments.environments.type==="singleBaseUrl"&&(s.servers=t.environments.environments.environments.map(u=>({url:u.url,description:u.docs!=null?`${u.name.originalName} (${u.docs})`:u.name.originalName}))),s}function HXc(e){return[...e.fernFilepath.allParts.map(t=>t.originalName),e.name.originalName].join("-")}function Pju(e){return[...e.fernFilepath.allParts.map(t=>t.originalName),e.name.originalName].join("-")}async function A8h({project:e,cliContext:t,outputPath:r}){await Promise.all(e.apiWorkspaces.map(async i=>{await t.runTaskForWorkspace(i,async n=>{let a=await i.toFernWorkspace({context:n}),o=iS({workspace:a,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!0},readme:void 0,version:void 0,packageName:void 0,context:n,sourceResolver:new rS(n,a)}),c=O8h({apiName:i.workspaceName??"api",ir:o,mode:"openapi"});await(0,jju.mkdir)(tn(r),{recursive:!0}),await(0,jju.writeFile)(r,r.endsWith(".json")?JSON.stringify(c,void 0,2):Di.dump(c))})}))}async function m8h({project:e,cliContext:t,shouldFix:r}){await Promise.all(e.apiWorkspaces.map(async i=>{i instanceof tS||await t.runTaskForWorkspace(i,async n=>{await gMc({workspace:await i.toFernWorkspace({context:n}),context:n,shouldFix:r})})}))}var P8h="group";var j8h=".preview",w8h="approved-output-directories",E8h=".fern";var C8h=require("fs/promises");var M8h=require("fs/promises");var S8h=require("os");function kJa(){return Ct(Sr.of((0,S8h.homedir)()),He.of(E8h),He.of(w8h))}async function D8h(){let e=kJa();if(!await mi(e))return[];let r=await(0,M8h.readFile)(e,{encoding:"utf-8"});return JSON.parse(r)}var wju=require("fs/promises"),B8h=ce(require("path"),1);async function I8h(e){await(0,wju.mkdir)(B8h.default.dirname(kJa()),{recursive:!0}),await(0,wju.writeFile)(kJa(),JSON.stringify(e,null,2))}async function q8h(e,t,r){if(!e||qrc()||r)return{shouldProceed:!0};let i=await D8h();return i?.includes(e)?{shouldProceed:!0}:await mi(e)?(await(0,C8h.readdir)(e)).length===0?{shouldProceed:!0}:await t.confirmPrompt(`Directory ${e} contains existing files that may be overwritten. Continue?`,!1)?(await I8h([...i??[],e]),{shouldProceed:!0}):{shouldProceed:!1}:{shouldProceed:!0}}var $vn=class extends Error{constructor(t,r){super(t),this.name="AutoVersioningException",r&&(this.cause=r)}},e$a=class{logger;constructor({logger:t}){this.logger=t}extractPreviousVersion(t,r){let i=t.split(`
1926
+ `}async function p8h({cliContext:e,targetVersion:t}){if(!t)return e.failAndThrow("Please specify a version to downgrade to using --version");let r=await $E();if(r==null)return e.failAndThrow(`Directory "${CT}" not found.`);let i=await e.runTask(a=>Nbe({directory:r,context:a})),n=gju(i.rawConfig,a=>{a.version=t});await(0,d8h.writeFile)(i._absolutePath,WSB(JSON.stringify(n,void 0,2))),e.logger.info(`Updated ${JU} to version ${t}`)}var jju=require("fs/promises");var Jvn=ce(svu(),1),y8h=ce(ng(),1);function _8h(e,t){let r=e.shape,i=e.docs??void 0;return{openApiSchema:fl._visit(r,{alias:a=>GSB({aliasTypeDeclaration:a,docs:i}),enum:a=>HSB({enumTypeDeclaration:a,docs:i}),object:a=>{let o=e.userProvidedExamples[0],c=o==null?YSB(t,e.name):void 0,d=o==null&&c==null?XSB(t,e.name):void 0;return Aju({properties:a.properties.map(s=>{let u;return o!=null&&o.shape.type==="object"?u=o.shape.properties.find(f=>f.name.wireValue===s.name.wireValue):c!=null?c.type==="reference"&&c.shape.type==="named"&&c.shape.shape.type==="object"&&(u=c.shape.shape.properties.find(f=>f.name.wireValue===s.name.wireValue)):d!=null&&d.type==="body"&&d.value?.shape.type==="named"&&d.value.shape.shape.type==="object"&&(u=d.value.shape.shape.properties.find(f=>f.name.wireValue===s.name.wireValue)),{docs:s.docs??void 0,name:s.name,valueType:s.valueType,example:u}}),extensions:a.extends,docs:i})},union:a=>xSB({unionTypeDeclaration:a,docs:i}),undiscriminatedUnion:a=>KSB({undiscriminatedUnionDeclaration:a,docs:i}),_other:()=>{throw new Error("Encountered unknown type: "+r.type)}}),schemaName:h8h(e.name)}}function GSB({aliasTypeDeclaration:e,docs:t}){return{...lC(e.aliasOf),description:t}}function HSB({enumTypeDeclaration:e,docs:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue),description:t}}function xSB({unionTypeDeclaration:e,docs:t}){let i={oneOf:e.types.map(n=>{let a={[e.discriminant.wireValue]:{type:"string",enum:[n.discriminantValue.wireValue]}};return zN._visit(n.shape,{noProperties:()=>({type:"object",properties:a,required:[e.discriminant.wireValue]}),singleProperty:o=>({type:"object",properties:{...a,[o.name.wireValue]:lC(o.type)},required:[e.discriminant.wireValue]}),samePropertiesAsObject:o=>({type:"object",allOf:[{type:"object",properties:a},{$ref:Oju(o)}],required:[e.discriminant.wireValue]}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+n.shape.propertiesType)}})}),description:t};return e.baseProperties.length>0&&(i.properties=e.baseProperties.reduce((n,a)=>(n[a.name.wireValue]={description:a.docs??void 0,...lC(a.valueType)},a.valueType.type==="container"&&a.valueType.container.type==="optional"||(i.required=[...i.required??[],a.name.wireValue]),n),{})),i}function KSB({undiscriminatedUnionDeclaration:e,docs:t}){return{oneOf:e.members.map(r=>({description:r.docs??void 0,...lC(r.type)})),description:t}}function lC(e){return kr._visit(e,{container:t=>$SB(t),named:t=>({$ref:Oju(t)}),primitive:t=>JSB(t),unknown:()=>({}),_other:()=>{throw new Error("Encountered unknown typeReference: "+e.type)}})}function JSB(e){return e.v2==null?Vu._visit(e.v1,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:()=>({type:"string"}),uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),_other:()=>{throw new Error("Encountered unknown primitiveType: "+e.v1)}})??{}:pn._visit(e.v2,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:t=>{let r={type:"string"};return t.validation?.format!=null&&(r.format=t.validation.format),t.validation?.pattern!=null&&(r.pattern=t.validation.pattern),r},uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),_other:()=>{throw new Error("Encountered unknown primitiveType: "+e.v2)}})}function $SB(e){return hs._visit(e,{list:t=>({type:"array",items:lC(t)}),set:t=>({type:"array",items:lC(t)}),map:t=>t.keyType.type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType.type==="unknown"?{type:"object",additionalProperties:!0}:{type:"object",additionalProperties:lC(t.valueType)},optional:t=>({...lC(t),nullable:!0}),nullable:t=>({...lC(t),nullable:!0}),literal:t=>t._visit({boolean:r=>({type:"boolean",const:r}),string:r=>({type:"string",const:r}),_other:()=>({})}),_other:()=>{throw new Error("Encountered unknown containerType: "+e.type)}})}function Oju(e){return`#/components/schemas/${h8h(e)}`}function h8h(e){return[...e.fernFilepath.packagePath.map(t=>t.originalName),e.name.originalName].join("")}function YSB(e,t){for(let r of Object.values(e.services))for(let i of r.endpoints)if(!(i.userSpecifiedExamples.length<=0)&&i.requestBody?.type==="reference"&&i.requestBody.requestBodyType.type==="named"&&ZSB(i.requestBody.requestBodyType,t))return i.userSpecifiedExamples[0]?.example?.request??void 0}function XSB(e,t){for(let r of Object.values(e.services))for(let i of r.endpoints)if(!(i.userSpecifiedExamples.length<=0||i.response?.body?.type!=="json")&&i.response.body.value.responseBodyType.type==="named"&&i.response.body.value.responseBodyType.typeId===t.typeId){let n=i.userSpecifiedExamples.find(a=>a.example?.response.type==="ok");if(n!=null&&n.example?.response.type==="ok")return n.example.response.value}}function ZSB(e,t){return BT(e.fernFilepath,t.fernFilepath)&&BT(e.name,t.name)}function Aju({docs:e,properties:t,extensions:r}){let i={},n=[];t.forEach(o=>{let c=lC(o.valueType),d;(o.example!=null&&o.valueType.type==="primitive"||o.example!=null&&o.valueType.type==="container"&&o.valueType.container.type==="list"&&o.valueType.container.list.type==="primitive")&&(d=o.example.value.jsonExample),i[o.name.wireValue]={...c,description:o.docs??void 0,example:d},o.valueType.type==="container"&&o.valueType.container.type==="optional"||n.push(o.name.wireValue)});let a={type:"object",description:e,properties:i};return n.length>0&&(a.required=n),r.length>0&&(a.allOf=r.map(o=>({$ref:Oju(o)}))),a}function b8h({ir:e,httpServices:t,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c}){let d={};return t.forEach(s=>{s.endpoints.forEach(u=>{let{fullPath:f,convertedHttpMethod:p,operationObject:_}=kSB({ir:e,httpEndpoint:u,httpService:s,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c}),h=d[f]??={};if(h[p]!=null)throw new Error(`Duplicate ${p} endpoint at ${f}`);h[p]=_})}),d}function kSB({httpEndpoint:e,httpService:t,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c,ir:d}){let s=(0,y8h.default)(d.basePath!=null?GXc(d.basePath):"",GXc(t.basePath),GXc(e.path));s=s.startsWith("/")?s:`/${s}`;let u=eMB(e.method),f=d.pathParameters.map(A=>WXc({pathParameter:A,examples:e.userSpecifiedExamples.map(g=>g.example).filter(ds)??[]})),p=t.pathParameters.map(A=>WXc({pathParameter:A,examples:e.userSpecifiedExamples.map(g=>g.example).filter(ds)??[]})),_=e.pathParameters.map(A=>WXc({pathParameter:A,examples:e.userSpecifiedExamples.map(g=>g.example).filter(ds)??[]})),h=e.queryParameters.map(A=>aMB({queryParameter:A,typesByName:r,examples:e.userSpecifiedExamples.map(g=>g.example).filter(ds)??[]})),y=e.headers.map(A=>oMB({httpHeader:A,typesByName:r,examples:e.userSpecifiedExamples.map(g=>g.example).filter(ds)??[]})),b=[...f,...p,..._,...h,...y],v=c==="stoplight"?t.displayName??t.name.fernFilepath.allParts.map(A=>A.originalName).join(" "):t.name.fernFilepath.allParts.map(A=>A.pascalCase.unsafeName).join(""),O={description:e.docs??void 0,operationId:[...t.name.fernFilepath.allParts.map(A=>A.camelCase.unsafeName),e.name.originalName].join("_"),tags:[v],parameters:b,responses:rMB({httpResponse:e.response,responseErrors:e.errors,errorsByName:i,errorDiscriminationStrategy:n,examples:e.userSpecifiedExamples.map(A=>A.example).filter(ds)??[]}),summary:e.displayName??void 0};if(e.baseUrl!=null){let A=e.baseUrl;if(o?.environments.type!=="multipleBaseUrls")throw new Error("baseUrl is defined environments are not multipleBaseUrls");O.servers=o.environments.environments.map(g=>{let m=g.urls[A];if(m==null)throw new Error("No URL defined for "+A);let j={url:m};return g.docs!=null&&(j.description=g.docs),j})}return e.auth&&(O.security=a),e.requestBody!=null&&(O.requestBody=tMB({httpRequest:e.requestBody,typesByName:r,examples:e.userSpecifiedExamples.map(A=>A.example).filter(ds)??[]})),{fullPath:s,convertedHttpMethod:u,operationObject:O}}function eMB(e){return U0._visit(e,{get:()=>Jvn.OpenAPIV3.HttpMethods.GET,post:()=>Jvn.OpenAPIV3.HttpMethods.POST,put:()=>Jvn.OpenAPIV3.HttpMethods.PUT,patch:()=>Jvn.OpenAPIV3.HttpMethods.PATCH,delete:()=>Jvn.OpenAPIV3.HttpMethods.DELETE,head:()=>Jvn.OpenAPIV3.HttpMethods.HEAD,_other:()=>{throw new Error("Encountered unknown http method: "+e)}})}function tMB({httpRequest:e,typesByName:t,examples:r}){let i={};for(let n of r)n.request!=null&&(n.name&&n.name.originalName!==""?i[n.name.originalName]={value:n.request.jsonExample}:i[`Example${Am(i)+1}`]={value:n.request.jsonExample});return vA._visit(e,{inlinedRequestBody:n=>{let a={schema:Aju({docs:void 0,properties:n.properties.map(o=>{let c;return r.length>0&&r[0]?.request?.type==="inlinedRequestBody"&&(c=r[0]?.request.properties.find(d=>d.name.wireValue===o.name.wireValue)),{docs:o.docs??void 0,name:o.name,valueType:o.valueType,example:c}}),extensions:n.extends})};return Am(i)>0&&(a.examples=i),{required:!0,content:{"application/json":a}}},reference:n=>{let a={schema:lC(n.requestBodyType)};return Am(i)>0&&(a.examples=i),{description:n.docs??void 0,required:mju({typeReference:n.requestBodyType,typesByName:t}),content:{"application/json":a}}},fileUpload:n=>({required:!0,content:{"multipart/form-data":{schema:{type:"object",properties:n.properties.reduce((a,o)=>(r1._visit(o,{file:c=>{a[c.key.wireValue]={type:"string",format:"binary"}},bodyProperty:c=>{a[c.name.wireValue]={description:c.docs??void 0,...lC(c.valueType)}},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}}),{...a}),{})}}}}),bytes:()=>{throw new Error("bytes is not supported")},_other:()=>{throw new Error("Unknown HttpRequestBody type: "+e.type)}})}function rMB({httpResponse:e,responseErrors:t,errorsByName:r,errorDiscriminationStrategy:i,examples:n}){let a={};if(e?.body?.type==="json"){let o={schema:lC(e.body.value.responseBodyType)},c={};for(let d of n)d.response.type==="ok"&&d.response.value.type==="body"&&d.response.value.value!=null&&(d.name&&d.name.originalName!==""?c[d.name.originalName]={value:d.response.value.value.jsonExample}:c[`Example${Am(c)+1}`]={value:d.response.value.value.jsonExample});Am(c)>0&&(o.examples=c),a[String(e.statusCode??200)]={description:e.body.value.docs??"",content:{"application/json":o}}}else a[204]={description:""};return pve._visit(i,{statusCode:()=>{for(let o of t){let c=r[Pju(o.error)];if(c==null)throw new Error("Encountered undefined error declaration: "+o.error.name.originalName);let d={description:o.docs??""};if(c.type!=null){let s={schema:lC(c.type)},u={};for(let f of n)f.response.type==="error"&&f.response.body!=null&&BT(o.error,f.response.error)&&(f.name&&f.name.originalName!==""?u[f.name.originalName]={value:f.response.body.jsonExample}:u[`Example${Am(u)+1}`]={value:f.response.body.jsonExample});Am(u)>0&&(s.examples=u),d.content={"application/json":s}}a[c.statusCode]=d}},property:o=>{let c=nMB({responseErrors:t,errorsByName:r});for(let d of Object.keys(c)){let s=c[d];if(s==null||s.length===0)continue;let u={schema:{oneOf:s.map(p=>iMB({errorInfo:p,property:o}))}},f={};for(let p of n)if(p.response.type==="error"&&p.response.body!=null){let _=p.response.error;s.some(h=>BT(h.errorDeclaration.name,_))&&(p.name&&p.name.originalName!==""?f[p.name.originalName]={value:p.response.body.jsonExample}:f[`Example${Am(f)+1}`]={value:p.response.body.jsonExample})}Am(f)>0&&(u.examples=f),a[d]={description:"",content:{"application/json":u}}}},_other:()=>{throw new Error("Unknown error discrimination strategy: "+i.type)}}),a}function iMB({errorInfo:e,property:t}){let r=e.errorDeclaration.discriminantValue.wireValue,i=e.responseError.docs??void 0,n={[t.discriminant.wireValue]:{type:"string",enum:[r]}};return e.errorDeclaration.type!=null&&(n[t.contentProperty.wireValue]=lC(e.errorDeclaration.type)),{type:"object",description:i,properties:n}}function nMB({responseErrors:e,errorsByName:t}){let r={};for(let i of e){let n=t[Pju(i.error)];if(n==null)throw new Error("Encountered undefined error declaration: "+i.error.name.originalName);let a=n.statusCode,o=r[a];o==null?r[a]=[{responseError:i,errorDeclaration:n}]:o.push({responseError:i,errorDeclaration:n})}return r}function WXc({pathParameter:e,examples:t}){let r={name:e.name.originalName,in:"path",description:e.docs??void 0,required:!0,schema:lC(e.valueType)},i={};for(let n of t){let a=[...n.rootPathParameters,...n.servicePathParameters,...n.endpointPathParameters].find(o=>o.name.originalName===e.name.originalName);a!=null&&(n.name&&n.name.originalName!==""?i[n.name.originalName]={value:a.value.jsonExample}:i[`Example${Am(i)+1}`]={value:a.value.jsonExample},r.example==null&&(r.example=a.value.jsonExample))}return Am(i)>0&&(r.examples=i),r}function aMB({queryParameter:e,typesByName:t,examples:r}){let i={name:e.name.wireValue,in:"query",description:e.docs??void 0,required:mju({typeReference:e.valueType,typesByName:t}),schema:e.allowMultiple?lC(kr.container(hs.list(e.valueType))):lC(e.valueType)},n={};for(let a of r){let o=a.queryParameters.find(c=>c.name.wireValue===e.name.wireValue);o!=null&&(a.name&&a.name.originalName!==""?n[a.name.originalName]={value:o.value.jsonExample}:n[`Example${Am(n)+1}`]={value:o.value.jsonExample},i.example==null&&(i.example=o.value.jsonExample))}return Am(n)>0&&(i.examples=n),i}function oMB({httpHeader:e,typesByName:t,examples:r}){let i={name:e.name.wireValue,in:"header",description:e.docs??void 0,required:mju({typeReference:e.valueType,typesByName:t}),schema:lC(e.valueType)},n={};for(let a of r){let o=[...a.serviceHeaders,...a.endpointHeaders].find(c=>c.name.wireValue===e.name.wireValue);o!=null&&(a.name&&a.name.originalName!==""?n[a.name.originalName]={value:o.value.jsonExample}:n[`Example${Am(n)+1}`]={value:o.value.jsonExample},i.example==null&&(i.example=o.value.jsonExample))}return Am(n)>0&&(i.examples=n),i}function GXc(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return t}function mju({typeReference:e,typesByName:t}){if(e.type==="container"&&e.container.type==="optional")return!1;if(e.type==="named"){let r=HXc(e),i=t[r];if(i==null)throw new Error("Encountered non-existent type: "+e.name.originalName);if(i.shape.type==="alias")return mju({typeReference:i.shape.aliasOf,typesByName:t})}return!0}function v8h(e){return nR._visit(e.requirement,{all:()=>[e.schemes.reduce((t,r)=>({...t,[xXc(r)]:[]}),{})],any:()=>e.schemes.map(t=>({[xXc(t)]:[]})),endpointSecurity:()=>[],_other:()=>{throw new Error("Unknown auth scheme requirement: "+e.requirement)}})}function g8h(e){let t={};for(let r of e.schemes){let i=im._visit(r,{bearer:()=>({type:"http",scheme:"bearer"}),basic:()=>({type:"http",scheme:"basic"}),header:n=>({type:"apiKey",in:"header",name:n.name.wireValue}),oauth:()=>({type:"http",scheme:"bearer"}),inferred:()=>{},_other:()=>{throw new Error("Unknown auth scheme: "+r.type)}});i&&(t[xXc(r)]=i)}return t}function xXc(e){return im._visit(e,{bearer:()=>"BearerAuth",inferred:()=>"InferredAuth",basic:()=>"BasicAuth",oauth:()=>"BearerAuth",header:t=>`${t.name.name.pascalCase.unsafeName}Auth`,_other:()=>{throw new Error("Unknown auth scheme: "+e.type)}})}function O8h({apiName:e,ir:t,mode:r}){let i={},n={};Object.values(t.types).forEach(u=>{let f=_8h(u,t);i[f.schemaName]={title:f.schemaName,...f.openApiSchema},n[HXc(u.name)]=u});let a={};Object.values(t.errors).forEach(u=>{a[Pju(u.name)]=u});let o=v8h(t.auth),c=b8h({ir:t,httpServices:Object.values(t.services),typesByName:n,errorsByName:a,errorDiscriminationStrategy:t.errorDiscriminationStrategy,security:o,environments:t.environments??void 0,mode:r}),d={title:t.apiDisplayName??e,version:""};t.apiDocs!=null&&(d.description=t.apiDocs);let s={openapi:"3.0.1",info:d,paths:c,components:{schemas:i,securitySchemes:g8h(t.auth)}};return t.environments!=null&&t.environments.environments.type==="singleBaseUrl"&&(s.servers=t.environments.environments.environments.map(u=>({url:u.url,description:u.docs!=null?`${u.name.originalName} (${u.docs})`:u.name.originalName}))),s}function HXc(e){return[...e.fernFilepath.allParts.map(t=>t.originalName),e.name.originalName].join("-")}function Pju(e){return[...e.fernFilepath.allParts.map(t=>t.originalName),e.name.originalName].join("-")}async function A8h({project:e,cliContext:t,outputPath:r,indent:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await t.runTaskForWorkspace(n,async a=>{let o=await n.toFernWorkspace({context:a}),c=iS({workspace:o,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!0},readme:void 0,version:void 0,packageName:void 0,context:a,sourceResolver:new rS(a,o)}),d=O8h({apiName:n.workspaceName??"api",ir:c,mode:"openapi"});await(0,jju.mkdir)(tn(r),{recursive:!0}),await(0,jju.writeFile)(r,r.endsWith(".json")?JSON.stringify(d,void 0,i):Di.dump(d,{indent:i}))})}))}async function m8h({project:e,cliContext:t,shouldFix:r}){await Promise.all(e.apiWorkspaces.map(async i=>{i instanceof tS||await t.runTaskForWorkspace(i,async n=>{await gMc({workspace:await i.toFernWorkspace({context:n}),context:n,shouldFix:r})})}))}var P8h="group";var j8h=".preview",w8h="approved-output-directories",E8h=".fern";var C8h=require("fs/promises");var M8h=require("fs/promises");var S8h=require("os");function kJa(){return Ct(Sr.of((0,S8h.homedir)()),He.of(E8h),He.of(w8h))}async function D8h(){let e=kJa();if(!await mi(e))return[];let r=await(0,M8h.readFile)(e,{encoding:"utf-8"});return JSON.parse(r)}var wju=require("fs/promises"),B8h=ce(require("path"),1);async function I8h(e){await(0,wju.mkdir)(B8h.default.dirname(kJa()),{recursive:!0}),await(0,wju.writeFile)(kJa(),JSON.stringify(e,null,2))}async function q8h(e,t,r){if(!e||qrc()||r)return{shouldProceed:!0};let i=await D8h();return i?.includes(e)?{shouldProceed:!0}:await mi(e)?(await(0,C8h.readdir)(e)).length===0?{shouldProceed:!0}:await t.confirmPrompt(`Directory ${e} contains existing files that may be overwritten. Continue?`,!1)?(await I8h([...i??[],e]),{shouldProceed:!0}):{shouldProceed:!1}:{shouldProceed:!0}}var $vn=class extends Error{constructor(t,r){super(t),this.name="AutoVersioningException",r&&(this.cause=r)}},e$a=class{logger;constructor({logger:t}){this.logger=t}extractPreviousVersion(t,r){let i=t.split(`
1927
1927
  `),n="unknown",a=0;for(let o=0;o<i.length;o++){let c=i[o];if(c&&(c.startsWith("+++ b/")&&(n=c.substring(6)),c.startsWith("+")&&!c.startsWith("+++")&&c.includes(r))){a++;let d=c.replace(r,"<MAGIC>");this.logger.debug(`Found placeholder version in added line (file: ${n}): ${d}`);let s=this.findMatchingMinusLine(i,o,r);if(s==null){this.logger.debug(`No matching minus line in hunk; continuing search. file=${n}, plusLine=${d}`);continue}let u=this.extractPreviousVersionFromDiffLine(s);return this.logger.debug(`Extracted previous version from diff (file: ${n}): ${u}`),u}}throw a>0?new $vn(`Found placeholder version in the diff but no matching previous version lines were found in any hunk. This may indicate new files or a format change. occurrences=${a}, pairsFound=0`):new $vn("Failed to extract version from diff. This may indicate the version file format is not supported for auto-versioning, or the placeholder version was not found in any added lines.")}findMatchingMinusLine(t,r,i){let n=t[r];if(!n)return;let a=0;for(let o=r-1;o>=0;o--){let c=t[o];if(c){if(a++,this.shouldStopSearching(c)){this.logger.debug(`Stopped backward scan at hunk boundary after ${a} lines`);break}if(this.isDeletionLine(c)&&this.isVersionChangePair(c,n,i))return this.logger.debug(`Found matching minus line after scanning ${a} lines backwards`),c}}this.logger.warn(`No matching minus line found after scanning ${a} lines backwards`)}cleanDiffForAI(t,r){let i=t.split(`
1928
1928
  `),n=this.parseFileSections(i),a=[];for(let c of n){let d=this.cleanFileSection(c,r);d!=null&&a.push(d)}let o=[];for(let c of a)for(let d of c.lines)o.push(d);return this.logger.debug(`Cleaned diff: removed ${t.length-o.join(`
1929
1929
  `).length} bytes containing version changes`),o.join(`
@@ -2095,7 +2095,7 @@ Found fern at: ${i.detectedPath}`,i.resolvedPath!=null&&i.resolvedPath!==i.detec
2095
2095
  Resolved to: ${i.resolvedPath}`)),u+=`
2096
2096
 
2097
2097
  Please manually update using your package manager (npm, pnpm, yarn, bun, or brew).`,u+=`
2098
- For more diagnostic information, run with: FERN_LOG_LEVEL=debug fern self-update`,e.failAndThrow(u)}e.logger.info(`Detected installation method: ${qt.cyan(i.type)}`),i.detectedPath!=null&&e.logger.debug(`Found fern at: ${i.detectedPath}`),i.resolvedPath!=null&&i.resolvedPath!==i.detectedPath&&e.logger.debug(`Resolved to: ${i.resolvedPath}`);let n=TI5(i,t);if(n.length===0)return e.failAndThrow(`Unable to construct update command for installation method: ${i.type}`);i.type==="brew"&&t!=null&&e.logger.warn(qt.yellow("Warning: Homebrew does not support versioned upgrades. Upgrading to the latest version instead."));let a=n.join(" ");if(r===!0){e.logger.info(qt.yellow("Dry run mode - no changes will be made")),e.logger.info(`Would run: ${qt.cyan(a)}`);return}e.logger.info(`Running: ${qt.dim(a)}`);let[o,...c]=n;if(o==null)return e.failAndThrow("Invalid update command");let{failed:d,stderr:s}=await kh(e.logger,o,c,{doNotPipeOutput:!1,reject:!1});if(d)return e.logger.error(`Failed to update Fern CLI: ${s}`),e.failAndThrow("Update failed. Please try updating manually.");e.logger.info(qt.green("\u2713 Fern CLI updated successfully!"))}async function UgE({cliContext:e,project:t,testCommand:r,generationLanguage:i}){if(await e.instrumentPostHogEvent({orgId:t.config.organization,command:"fern test"}),r==null)return e.failAndThrow("No test command specified. Use the --command option.");if(t.apiWorkspaces.length!==1||t.apiWorkspaces[0]==null)return e.failAndThrow(`No API specified. Use the --${"api"} option.`);let n=t.apiWorkspaces[0];await e.runTaskForWorkspace(n,async a=>{let o=await n.toFernWorkspace({context:a});await Tcn({context:a,logWarnings:!1,workspace:o});let c=iS({workspace:o,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:a,sourceResolver:new rS(a,o)}),d=new yxn({context:a,ir:c,port:void 0}),u=`http://localhost:${await d.start()}`;a.logger.info("Running tests..."),a.logger.info(`>> ${r}`),a.logger.debug(`envvar set: TESTS_BASE_URL=${u}`);let f=r.split(" && ").map(p=>p.split(" "));for(let p of f){let{failed:_}=await kh(e.logger,p[0]??"",p.slice(1),{reject:!1,env:{TESTS_BASE_URL:u}});_&&(d.stop(),a.logger.error("Tests failed, Fern mock server stopping."),a.logger.error("View test output above."),e.failAndThrow())}d.stop(),a.logger.info("Fern mock server stopped.")})}async function LgE({orgId:e,taskContext:t}){let r=await j8(t);r.type==="user"&&await LVt({organization:e,token:r,context:t});let n=await w4({token:r.value}).registry.generateRegistryTokens({organizationId:Jh.OrganizationId(e)});if(n.ok){t.logger.info(qt.green(`Generated a FERN_TOKEN for ${e}: ${n.body.npm.token}`));return}n.error._visit({organizationNotFoundError:()=>t.failAndThrow(`Failed to create token because the organization ${e} was not found. Please reach out to support@buildwithfern.com`),unauthorizedError:()=>t.failAndThrow(`Failed to create token because you are not in the ${e} organization. Please reach out to support@buildwithfern.com`),_other:()=>t.failAndThrow("Failed to create token. Please reach out to support@buildwithfern.com")})}var VgE=ce(require("fs"),1),bBo=require("fs/promises");var WgE=require("stream"),GgE=require("stream/promises");async function RI5(e,t,r){let i=await fetch(e);if(i.ok&&i.body){r.debug("Origin successfully fetched, writing to file");let n=VgE.createWriteStream(t);await(0,GgE.finished)(WgE.Readable.fromWeb(i.body).pipe(n));let a=await(0,bBo.readFile)(t,"utf8");try{await(0,bBo.writeFile)(t,JSON.stringify(JSON.parse(a),void 0,2),"utf8")}catch{await(0,bBo.writeFile)(t,Di.dump(Di.load(a)),"utf8")}r.debug("File written successfully")}}async function HgE({cliContext:e,project:{apiWorkspaces:t}}){for(let r of t)r.type!=="fern"&&await e.runTaskForWorkspace(r,async i=>{let n=await xbe({absolutePathToWorkspace:r.absoluteFilePath,context:i});if(n==null){e.logger.info("No API configuration was found, skipping API update.");return}if(n.api!=null){if(n.api.type==="conjure"){e.logger.info("Encountered conjure API definition, skipping API update.");return}if(n.api.type==="singleNamespace"){await Bcp({cliContext:e,workspacePath:r.absoluteFilePath,apiLocations:n.api.definitions});return}else if(n.api.type==="multiNamespace"){n.api.rootDefinitions!=null&&await Bcp({cliContext:e,workspacePath:r.absoluteFilePath,apiLocations:n.api.rootDefinitions});for(let[a,o]of Object.entries(n.api.definitions))await Bcp({cliContext:e,workspacePath:r.absoluteFilePath,apiLocations:o})}}})}async function zI5({cliContext:e,workspacePath:t,apiLocation:r}){if(r.schema.type==="protobuf"){e.logger.info("Encountered conjure API definition, skipping API update.");return}r.origin!=null&&(e.logger.info(`Origin found, fetching spec from ${r.origin}`),await RI5(r.origin,Ct(t,He.of(r.schema.path)),e.logger))}async function Bcp({cliContext:e,workspacePath:t,apiLocations:r}){for(let i of r)await zI5({cliContext:e,workspacePath:t,apiLocation:i})}var ZJs=require("fs/promises");var xgE="fern";async function KgE(e){let t=await NI5(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${xgE}" not found.`),(await GA("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function NI5(){let e=await JA(xgE,{type:"directory"});if(e!=null)return Sr.of(e)}var Icp={name:"discriminant",summary:`Adds 'discriminant: "_type"' to all discriminated types.`,run:async({context:e})=>{let t=await KgE(e);for(let r of t)try{let i=await FI5(r),n=QI5(i);await(0,ZJs.writeFile)(r,n)}catch(i){e.failAndThrow("Failed to migrate "+r,i)}}};async function FI5(e){return(await(0,ZJs.readFile)(e)).toString()}var JgE=/^(\s{2,})union:\s*$/gm;function QI5(e){return e.replaceAll(JgE,t=>{let i=[...t.matchAll(JgE)][0]?.[1];if(i==null)return t;let n=" ".repeat(i.length*1.5);return[`${i}discriminant:`,`${n}value: _type`,`${n}name: type`,t].join(`
2098
+ For more diagnostic information, run with: FERN_LOG_LEVEL=debug fern self-update`,e.failAndThrow(u)}e.logger.info(`Detected installation method: ${qt.cyan(i.type)}`),i.detectedPath!=null&&e.logger.debug(`Found fern at: ${i.detectedPath}`),i.resolvedPath!=null&&i.resolvedPath!==i.detectedPath&&e.logger.debug(`Resolved to: ${i.resolvedPath}`);let n=TI5(i,t);if(n.length===0)return e.failAndThrow(`Unable to construct update command for installation method: ${i.type}`);i.type==="brew"&&t!=null&&e.logger.warn(qt.yellow("Warning: Homebrew does not support versioned upgrades. Upgrading to the latest version instead."));let a=n.join(" ");if(r===!0){e.logger.info(qt.yellow("Dry run mode - no changes will be made")),e.logger.info(`Would run: ${qt.cyan(a)}`);return}e.logger.info(`Running: ${qt.dim(a)}`);let[o,...c]=n;if(o==null)return e.failAndThrow("Invalid update command");let{failed:d,stderr:s}=await kh(e.logger,o,c,{doNotPipeOutput:!1,reject:!1});if(d)return e.logger.error(`Failed to update Fern CLI: ${s}`),e.failAndThrow("Update failed. Please try updating manually.");e.logger.info(qt.green("\u2713 Fern CLI updated successfully!"))}async function UgE({cliContext:e,project:t,testCommand:r,generationLanguage:i}){if(await e.instrumentPostHogEvent({orgId:t.config.organization,command:"fern test"}),r==null)return e.failAndThrow("No test command specified. Use the --command option.");if(t.apiWorkspaces.length!==1||t.apiWorkspaces[0]==null)return e.failAndThrow(`No API specified. Use the --${"api"} option.`);let n=t.apiWorkspaces[0];await e.runTaskForWorkspace(n,async a=>{let o=await n.toFernWorkspace({context:a});await Tcn({context:a,logWarnings:!1,workspace:o});let c=iS({workspace:o,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:a,sourceResolver:new rS(a,o)}),d=new yxn({context:a,ir:c,port:void 0}),u=`http://localhost:${await d.start()}`;a.logger.info("Running tests..."),a.logger.info(`>> ${r}`),a.logger.debug(`envvar set: TESTS_BASE_URL=${u}`);let f=r.split(" && ").map(p=>p.split(" "));for(let p of f){let{failed:_}=await kh(e.logger,p[0]??"",p.slice(1),{reject:!1,env:{TESTS_BASE_URL:u}});_&&(d.stop(),a.logger.error("Tests failed, Fern mock server stopping."),a.logger.error("View test output above."),e.failAndThrow())}d.stop(),a.logger.info("Fern mock server stopped.")})}async function LgE({orgId:e,taskContext:t}){let r=await j8(t);r.type==="user"&&await LVt({organization:e,token:r,context:t});let n=await w4({token:r.value}).registry.generateRegistryTokens({organizationId:Jh.OrganizationId(e)});if(n.ok){t.logger.info(qt.green(`Generated a FERN_TOKEN for ${e}: ${n.body.npm.token}`));return}n.error._visit({organizationNotFoundError:()=>t.failAndThrow(`Failed to create token because the organization ${e} was not found. Please reach out to support@buildwithfern.com`),unauthorizedError:()=>t.failAndThrow(`Failed to create token because you are not in the ${e} organization. Please reach out to support@buildwithfern.com`),_other:()=>t.failAndThrow("Failed to create token. Please reach out to support@buildwithfern.com")})}var VgE=ce(require("fs"),1),bBo=require("fs/promises");var WgE=require("stream"),GgE=require("stream/promises");async function RI5(e,t,r,i){let n=await fetch(e);if(n.ok&&n.body){r.debug("Origin successfully fetched, writing to file");let a=VgE.createWriteStream(t);await(0,GgE.finished)(WgE.Readable.fromWeb(n.body).pipe(a));let o=await(0,bBo.readFile)(t,"utf8");try{await(0,bBo.writeFile)(t,JSON.stringify(JSON.parse(o),void 0,i),"utf8")}catch{await(0,bBo.writeFile)(t,Di.dump(Di.load(o),{indent:i}),"utf8")}r.debug("File written successfully")}}async function HgE({cliContext:e,project:{apiWorkspaces:t},indent:r}){for(let i of t)i.type!=="fern"&&await e.runTaskForWorkspace(i,async n=>{let a=await xbe({absolutePathToWorkspace:i.absoluteFilePath,context:n});if(a==null){e.logger.info("No API configuration was found, skipping API update.");return}if(a.api!=null){if(a.api.type==="conjure"){e.logger.info("Encountered conjure API definition, skipping API update.");return}if(a.api.type==="singleNamespace"){await Bcp({cliContext:e,workspacePath:i.absoluteFilePath,apiLocations:a.api.definitions,indent:r});return}else if(a.api.type==="multiNamespace"){a.api.rootDefinitions!=null&&await Bcp({cliContext:e,workspacePath:i.absoluteFilePath,apiLocations:a.api.rootDefinitions,indent:r});for(let[o,c]of Object.entries(a.api.definitions))await Bcp({cliContext:e,workspacePath:i.absoluteFilePath,apiLocations:c,indent:r})}}})}async function zI5({cliContext:e,workspacePath:t,apiLocation:r,indent:i}){if(r.schema.type==="protobuf"){e.logger.info("Encountered conjure API definition, skipping API update.");return}r.origin!=null&&(e.logger.info(`Origin found, fetching spec from ${r.origin}`),await RI5(r.origin,Ct(t,He.of(r.schema.path)),e.logger,i))}async function Bcp({cliContext:e,workspacePath:t,apiLocations:r,indent:i}){for(let n of r)await zI5({cliContext:e,workspacePath:t,apiLocation:n,indent:i})}var ZJs=require("fs/promises");var xgE="fern";async function KgE(e){let t=await NI5(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${xgE}" not found.`),(await GA("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function NI5(){let e=await JA(xgE,{type:"directory"});if(e!=null)return Sr.of(e)}var Icp={name:"discriminant",summary:`Adds 'discriminant: "_type"' to all discriminated types.`,run:async({context:e})=>{let t=await KgE(e);for(let r of t)try{let i=await FI5(r),n=QI5(i);await(0,ZJs.writeFile)(r,n)}catch(i){e.failAndThrow("Failed to migrate "+r,i)}}};async function FI5(e){return(await(0,ZJs.readFile)(e)).toString()}var JgE=/^(\s{2,})union:\s*$/gm;function QI5(e){return e.replaceAll(JgE,t=>{let i=[...t.matchAll(JgE)][0]?.[1];if(i==null)return t;let n=" ".repeat(i.length*1.5);return[`${i}discriminant:`,`${n}value: _type`,`${n}name: type`,t].join(`
2099
2099
  `)})}var UI5={version:"0.0.191",migrations:[Icp]},$gE=UI5;var kJs=require("fs/promises"),Rcn=ce(N4(),1);var YgE="fern";async function XgE(e){let t=await LI5(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${YgE}" not found.`),(await GA("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function LI5(){let e=await JA(YgE,{type:"directory"});if(e!=null)return Sr.of(e)}var Ccp={name:"union-single-property-migration",summary:"migrates union types to set the `key` property on non-object subtypes to the discriminant value.",run:async({context:e})=>{let t=await XgE(e);for(let r of t)try{await VI5(r,e)}catch(i){e.failWithoutThrowing(`Failed to add 'key' property to union in ${r}`,i)}}};async function VI5(e,t){let r=await(0,kJs.readFile)(e),i=Rcn.default.parseDocument(r.toString()),n=i.get("types");if(n!=null){if(!Rcn.default.isMap(n)){t.failWithoutThrowing(`"types" is not a map in ${e}`);return}for(let a of n.items)if(Rcn.default.isMap(a.value)){let o=a.value.get("union");if(o==null)continue;if(!Rcn.default.isMap(o)){t.failWithoutThrowing(`"union" is not a map in ${e}`);continue}for(let c of o.items)Rcn.default.isScalar(c.value)?c.value={type:c.value,key:c.key}:Rcn.default.isMap(c.value)&&c.value.add(new Rcn.default.Pair("key",c.key))}await(0,kJs.writeFile)(e,i.toString())}}var WI5={version:"0.0.203",migrations:[Ccp]},ZgE=WI5;var t$s=require("fs/promises"),e$s=ce(N4(),1);var kgE="fern";async function eOE(e){let t=await GI5(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${kgE}" not found.`),(await GA("*/generators.yml",{cwd:t,absolute:!0})).map(Sr.of)}async function GI5(){let e=await JA(kgE,{type:"directory"});if(e!=null)return Sr.of(e)}var qcp={name:"add-mode-to-draft-generators",summary:"Adds 'mode' to draft generators in generators.yml, which can either be 'download-files' or 'publish'.",run:async({context:e})=>{let t=await eOE(e);for(let r of t)try{await HI5(r,e)}catch(i){e.failWithoutThrowing(`Failed to migrate ${r}`,i)}}};async function HI5(e,t){let r=await(0,t$s.readFile)(e),i=e$s.default.parseDocument(r.toString()),n=i.get("draft");if(n!=null){if(!e$s.default.isSeq(n)){t.failWithoutThrowing(`draft generators are not a list in ${e}`);return}n.items.forEach(a=>{if(!e$s.default.isMap(a)){t.failWithoutThrowing(`draft generator is not an object in ${e}`);return}let o=a.get("name",!0);if(typeof o?.value!="string"){t.failWithoutThrowing(`draft generator didn't have name in ${e}`);return}let c=a.get("local-output");a.delete("local-output"),a.set("mode",c==null?"publish":"download-files"),c!=null&&a.set("output-path",o.value.includes("openapi")?"./generated-openapi":o.value.includes("postman")?"./generated-postman":c)}),await(0,t$s.writeFile)(e,i.toString())}}var xI5={version:"0.0.207",migrations:[qcp]},tOE=xI5;var r$s=require("fs/promises"),oNa=ce(N4(),1);var rOE="fern";async function iOE(e){let t=await KI5(),r=(n,a)=>n.localeCompare(a,"en");return t==null?e.failAndThrow(`Directory "${rOE}" not found.`):(await GA("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function KI5(){let e=await JA(rOE,{type:"directory"});if(e!=null)return Sr.of(e)}var Tcp={name:"remove-inline-error-declarations",summary:"moves inlined error declarations to be types.",run:async({context:e})=>{let t=await iOE(e);for(let r of t)try{await JI5(r,e)}catch(i){e.failWithoutThrowing(`Failed to add 'key' property to union in ${r}`,i)}}};async function JI5(e,t){let r=await(0,r$s.readFile)(e),i=oNa.default.parseDocument(r.toString()),n=(o,c)=>{let d=i.get("types");d==null?i.set("types",{[o]:c}):oNa.default.isMap(d)?d.set(o,c):t.failWithoutThrowing(`"types" is not a map in ${e}`)},a=i.get("errors");if(a!=null){if(!oNa.default.isMap(a)){t.failWithoutThrowing(`"errors" is not a map in ${e}`);return}for(let o of a.items){if(!oNa.default.isMap(o.value)){t.failWithoutThrowing(`Error "${o.key}" is not a map in ${e}`);continue}let c=o.value.get("type",!0);if(c!=null&&typeof c.value!="string"){let s=`${o.key}Body`;n(s,c),o.value.set("type",s)}let d=o.value.get("http");if(d!=null)if(!oNa.default.isMap(d))t.failWithoutThrowing(`http in "${o.key}" is not a map in ${e}`);else{let s=d.get("statusCode",!0);o.value.delete("http"),o.value.set("status-code",s)}}await(0,r$s.writeFile)(e,i.toString())}}var $I5={version:"0.0.210",migrations:[Tcp]},nOE=$I5;var i$s=require("fs/promises"),zcn=ce(N4(),1);var aOE="fern";async function oOE(e){let t=await YI5(),r=(n,a)=>n.localeCompare(a,"en");return t==null?e.failAndThrow(`Directory "${aOE}" not found.`):(await GA("*/generators.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function YI5(){let e=await JA(aOE,{type:"directory"});if(e!=null)return Sr.of(e)}var Rcp={name:"add-publishing-to-release-generators",summary:"Adds publishing and github keys to release generators configuration",run:async({context:e})=>{let t=await oOE(e);for(let r of t)try{await XI5(r,e)}catch(i){e.failWithoutThrowing(`Failed to migrate ${r}`,i)}}};async function XI5(e,t){let r=await(0,i$s.readFile)(e),i=zcn.default.parseDocument(r.toString()),n=i.get("release");if(n!=null){if(!zcn.default.isSeq(n)){t.failWithoutThrowing(`release generators are not a list in ${e}`);return}n.items.forEach(a=>{if(!zcn.default.isMap(a)){t.failWithoutThrowing(`release generator is not an object in ${e}`);return}let o=a.get("outputs");if(!zcn.default.isMap(o)){t.failWithoutThrowing(`outputs is not an object in ${e}`);return}let c=o.get("github");zcn.default.isMap(c)&&c.has("repository")&&a.set("github",c);let d={},s=o.get("npm");zcn.default.isMap(s)&&(d.npm=s);let u=o.get("maven");zcn.default.isMap(u)&&(d.maven=u),Object.keys(d).length>0&&a.set("publishing",d),a.delete("outputs")}),await(0,i$s.writeFile)(e,i.toString())}}var ZI5={version:"0.0.212",migrations:[Rcp]},uOE=ZI5;var n$s=require("fs/promises");var sOE="fern";async function cOE(e){let t=await kI5(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${sOE}" not found.`),(await GA("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function kI5(){let e=await JA(sOE,{type:"directory"});if(e!=null)return Sr.of(e)}var zcp={name:"rename-alias-key-to-type",summary:"Renames the 'alias' key to 'type'",run:async({context:e})=>{let t=await cOE(e);for(let r of t){let n=(await(0,n$s.readFile)(r)).toString().replaceAll(" alias:"," type:");await(0,n$s.writeFile)(r,n)}}};var eC5={version:"0.0.220",migrations:[zcp]},lOE=eC5;var a$s=require("fs/promises");var fOE="fern";async function dOE(e){let t=await tC5(),r=(n,a)=>n.localeCompare(a,"en");return t==null?e.failAndThrow(`Directory "${fOE}" not found.`):(await GA("*/definition/api.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function tC5(){let e=await JA(fOE,{type:"directory"});if(e!=null)return Sr.of(e)}var Ncp={name:"add-error-discriminant",summary:"Add error-discriminant to api.yml",run:async({context:e})=>{let t=await dOE(e);for(let r of t){let n=(await(0,a$s.readFile)(r)).toString()+`
2100
2100
  error-discriminant: error`;await(0,a$s.writeFile)(r,n)}}};var rC5={version:"0.0.221",migrations:[Ncp]},pOE=rC5;var u$s=require("fs/promises");var _OE="fern";async function hOE(e){let t=await iC5(),r=(n,a)=>n.localeCompare(a,"en");return t==null?e.failAndThrow(`Directory "${_OE}" not found.`):(await GA("*/generators.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function iC5(){let e=await JA(_OE,{type:"directory"});if(e!=null)return Sr.of(e)}var o$s=Ft.strictObject({name:Ft.string(),version:Ft.string(),config:Ft.unknown(),audiences:Ft.optional(Ft.array(Ft.string()))});var yOE=o$s.extend({mode:Ft.union([Ft.literal("publish"),Ft.literal("download-files")]),"output-path":Ft.optional(Ft.string())});var bOE=Ft.strictObject({url:Ft.optional(Ft.string()),coordinate:Ft.string(),username:Ft.optional(Ft.string()),password:Ft.optional(Ft.string())});var vOE=Ft.strictObject({maven:bOE});var gOE=Ft.strictObject({url:Ft.optional(Ft.string()),"package-name":Ft.string(),token:Ft.optional(Ft.string())});var OOE=Ft.strictObject({npm:gOE});var AOE=Ft.strictObject({postman:Ft.strictObject({"api-key":Ft.string(),"workspace-id":Ft.string()})});var mOE=Ft.union([OOE,vOE,AOE]);var POE=Ft.strictObject({repository:Ft.string()});var jOE=o$s.extend({publishing:Ft.optional(mOE),github:Ft.optional(POE)});var Fcp=Ft.strictObject({draft:Ft.optional(Ft.array(yOE)),release:Ft.optional(Ft.array(jOE))});var Qcp={name:"add-generator-groups",summary:"Adds groups to generators configuration",run:async({context:e})=>{let t=await hOE(e);for(let r of t)try{await aC5(r)}catch(i){e.failWithoutThrowing(`Failed to migrate ${r}`,i)}}};async function aC5(e){let t=await(0,u$s.readFile)(e),r=Di.load(t.toString()),i=Fcp.parse(r),n={};i.draft!=null&&i.draft.length>0&&((n.groups??={}).server={generators:i.draft.map(a=>oC5(a))},n={"default-group":"server",...n}),i.release!=null&&i.release.length>0&&((n.groups??={}).external={generators:i.release.map(a=>uC5(a))}),await(0,u$s.writeFile)(e,Di.dump(n))}function oC5(e){let t={name:e.name,version:e.version};return e["output-path"]!=null&&(t.output={location:"local-file-system",path:e["output-path"]}),e.config!=null&&(t.config=e.config),t}function uC5(e){let t={name:e.name,version:e.version};return e.publishing!=null&&(t.output=sC5(e.publishing)),e.github!=null&&(t.github={repository:e.github.repository}),e.config!=null&&(t.config=e.config),t}function sC5(e){if(cC5(e))return{location:"npm",...e.npm};if(lC5(e))return{location:"maven",...e.maven};if(fC5(e))return{location:"postman",...e.postman};vt(e)}function cC5(e){return e.npm!=null}function lC5(e){return e.maven!=null}function fC5(e){return e.postman!=null}var dC5={version:"0.0.241",migrations:[Qcp]},wOE=dC5;var s$s=require("fs/promises"),Ucp=ce(N4(),1);var EOE="fern";async function SOE(e){let t=await pC5(),r=(n,a)=>n.localeCompare(a,"en");return t==null?e.failAndThrow(`Directory "${EOE}" not found.`):(await GA("*/definition/api.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function pC5(){let e=await JA(EOE,{type:"directory"});if(e!=null)return Sr.of(e)}var Lcp={name:"add-error-discrimination-config",summary:"Adds error discrimination configuration",run:async({context:e})=>{let t=await SOE(e);for(let r of t)try{await _C5(r)}catch(i){e.failWithoutThrowing(`Failed to migrate ${r}`,i)}}};async function _C5(e){let t=await(0,s$s.readFile)(e),r=Ucp.default.parseDocument(t.toString()),i=r.get("error-discriminant",!0);i==null||!Ucp.default.isScalar(i)||typeof i.value!="string"||(r.set("error-discrimination",{strategy:"property","property-name":i.value}),r.delete("error-discriminant"),await(0,s$s.writeFile)(e,r.toString()))}var hC5={version:"0.0.248",migrations:[Lcp]},MOE=hC5;var c$s=require("fs/promises"),eLt=ce(N4(),1);var DOE="fern";async function BOE(e){let t=await yC5(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${DOE}" not found.`),(await GA("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function yC5(){let e=await JA(DOE,{type:"directory"});if(e!=null)return Sr.of(e)}var Vcp={name:"add-inline-requests",summary:"Replace endpoint requests with inline definitions",run:async({context:e})=>{let t=await BOE(e);for(let r of t)try{await bC5(r,e)}catch(i){e.failWithoutThrowing(`Failed to migrate ${r}`,i)}}};async function bC5(e,t){let r=await(0,c$s.readFile)(e),i=eLt.default.parseDocument(r.toString()),n=i.get("services");if(n==null)return;if(!eLt.default.isMap(n))throw new Error("'services' is not a map");let a=n.get("http");if(a!=null){if(!eLt.default.isMap(a))throw new Error("'http' is not a map");for(let o of a.items){if(!eLt.default.isMap(o.value)){t.failWithoutThrowing(`Service '${o.key}' is not a map`);continue}let c=o.value.get("endpoints");if(c!=null){if(!eLt.default.isMap(c)){t.failWithoutThrowing(`Endpoints are not a map in service '${o.key}'`);continue}for(let d of c.items){if(!eLt.default.isMap(d.value)){t.failWithoutThrowing(`Endpoint ${d.key} is not a map in service '${o.key}'`);continue}try{vC5({document:i,endpoint:d.value})}catch(s){t.failWithoutThrowing("Failed to convert endpoint",s)}}await(0,c$s.writeFile)(e,i.toString())}}}}function vC5({document:e,endpoint:t}){let r=new eLt.default.YAMLMap,i=gC5(t);if(i!=null){let o=new eLt.default.YAMLMap,{requestBodyType:c,docs:d}=i;d!=null&&o.set("docs",d),o.set("type",c);let s=e.get("types");if(s!=null){if(!eLt.default.isMap(s))throw new Error("types are not a map");let u=s.get(c);if(u!=null&&eLt.default.isMap(u)){let f=u.get("extends"),p=u.get("properties");(f!=null||p!=null)&&(o=u,o.delete("docs"),r.set("name",c),s.delete(c))}}r.set("body",o)}let n=t.get("query-parameters");n!=null&&(r.set("query-parameters",n),t.delete("query-parameters"));let a=t.get("headers");a!=null&&(r.set("headers",a),t.delete("headers")),r.items.length>0&&t.set("request",r)}function gC5(e){let t=e.get("request");if(t!=null){if(typeof t=="string")return{requestBodyType:t,docs:void 0};if(eLt.default.isMap(t)){let r=t.get("type");if(r==null)throw new Error("request type does not exist");if(typeof r!="string")throw new Error("request type is not a string");let i=t.get("docs",!0);return{requestBodyType:r,docs:i}}throw new Error("request is not a string or a map")}}var OC5={version:"0.1.3-rc3",migrations:[Vcp]},IOE=OC5;var l$s=require("fs/promises"),vBo=ce(N4(),1);var COE="fern";async function qOE(e){let t=await AC5(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${COE}" not found.`),(await GA("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function AC5(){let e=await JA(COE,{type:"directory"});if(e!=null)return Sr.of(e)}var Wcp={name:"add-value-key-to-type-examples",summary:"Add the 'value' key to type examples, so they can be named and documented",run:async({context:e})=>{let t=await qOE(e);for(let r of t)try{await mC5(r,e)}catch(i){e.failWithoutThrowing(`Failed to migrate ${r}`,i)}}};async function mC5(e,t){let r=await(0,l$s.readFile)(e),i=vBo.default.parseDocument(r.toString()),n=i.get("types");if(n!=null){if(!vBo.default.isMap(n))throw new Error("'types' is not a map");for(let a of n.items){if(!vBo.default.isMap(a.value))continue;let o=a.value.get("examples");if(o!=null){if(!vBo.default.isSeq(o)){t.failWithoutThrowing("'examples' are not a list");continue}for(let c=0;c<o.items.length;c++){let d=o.get(c,!0);o.set(c,{value:d})}}}await(0,l$s.writeFile)(e,i.toString())}}var PC5={version:"0.3.0-rc12",migrations:[Wcp]},TOE=PC5;var f$s=require("fs/promises"),uNa=ce(N4(),1);var ROE="fern";async function zOE(e){let t=await jC5(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${ROE}" not found.`),(await GA("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function jC5(){let e=await JA(ROE,{type:"directory"});if(e!=null)return Sr.of(e)}var Gcp={name:"change-services-key-to-service",summary:'Rename the "services" key to "service". Only one service is allowed per file.',run:async({context:e})=>{let t=await zOE(e);for(let r of t)try{await wC5(r,e)}catch(i){e.failWithoutThrowing(`Failed to migrate ${r}`,i)}}};async function wC5(e,t){let r=await(0,f$s.readFile)(e),i=uNa.default.parseDocument(r.toString());if(!uNa.default.isMap(i.contents))return t.failAndThrow("File is not a map");for(let n of i.contents.items)if(uNa.default.isScalar(n.key)&&n.key.value==="services"){if(!uNa.default.isMap(n.value))return t.failAndThrow("Services are not a map");let a=n.value.get("http");if(a==null){i.contents.delete("services");return}if(!uNa.default.isMap(a))return t.failAndThrow("http is not a map");let[o,...c]=a.items;if(o==null){i.contents.delete("services");return}if(c.length>0)return t.failAndThrow("There are multiple services defined");n.key.value="service",n.value=o.value}await(0,f$s.writeFile)(e,i.toString())}var EC5={version:"0.3.23",migrations:[Gcp]},NOE=EC5;var d$s=require("fs/promises"),gBo=ce(N4(),1);var FOE="fern";async function QOE(e){let t=await SC5(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${FOE}" not found.`),(await GA("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function SC5(){let e=await JA(FOE,{type:"directory"});if(e!=null)return Sr.of(e)}var Hcp={name:"move-service-docs-to-top-level",summary:"Move service-level docs to the top-level of the file.",run:async({context:e})=>{let t=await QOE(e);for(let r of t)try{await MC5(r,e)}catch(i){e.failWithoutThrowing(`Failed to migrate ${r}`,i)}}};async function MC5(e,t){let r=await(0,d$s.readFile)(e),i=gBo.default.parseDocument(r.toString());if(!gBo.default.isMap(i.contents))return t.failAndThrow("File is not a map");let n=i.contents.get("service");if(n==null)return;if(!gBo.default.isMap(n))return t.failAndThrow("service is not a map");let a=n.items.findIndex(c=>gBo.default.isScalar(c.key)&&c.key.value==="docs"),o=n.items[a];o!=null&&(n.items.splice(a,1),i.contents.items.unshift(o),await(0,d$s.writeFile)(e,i.toString()))}var DC5={version:"0.5.4",migrations:[Hcp]},UOE=DC5;var p$s=require("fs/promises");var LOE="fern";async function VOE(e){let t=await BC5(),r=(n,a)=>n.localeCompare(a,"en");return t==null?e.failAndThrow(`Directory "${LOE}" not found.`):(await GA("*/generators.yml",{cwd:t,absolute:!0})).sort(r).map(Sr.of)}async function BC5(){let e=await JA(LOE,{type:"directory"});if(e!=null)return Sr.of(e)}var xcp={name:"add-suffix-to-docs-domain",summary:"Adds a docs.buildwithfern.com suffix to the docs domain",run:async({context:e})=>{let t=await VOE(e);for(let r of t)try{await IC5(r)}catch(i){e.failWithoutThrowing(`Failed to migrate ${r}`,i)}}};async function IC5(e){let t=await(0,p$s.readFile)(e),r=process.env.DOMAIN_SUFFIX??"docs.buildwithfern.com",i=/(docs:\s*domain:\s*)"([^"]*)"/g,n=t.toString().replace(i,(a,o,c)=>`docs:
2101
2101
  domain: "${c}.${r}"`);await(0,p$s.writeFile)(e,n.toString())}var CC5={version:"0.9.10",migrations:[xcp]},WOE=CC5;var IT5=ce(SmE(),1),CT5=ce(sPE(),1),MjE=ce(L3(),1);var SjE=require("fs/promises");async function wBo({absolutePathToWorkspace:e}){let t=k6i({absolutePathToWorkspace:e}),r=await(0,SjE.readFile)(t),i=Di.load(r.toString()),n=await MjE.DocsConfiguration.parse(i);if(n.ok)return n.value}var DT5="docs",BT5="docs.yml";function k6i({absolutePathToWorkspace:e}){return Ct(vNa({absolutePathToWorkspace:e}),He.of(BT5))}function vNa({absolutePathToWorkspace:e}){return Ct(e,He.of(DT5))}var Ucn=require("fs/promises");function lYs({docsConfiguration:e,docsURLs:t,apiName:r}){return{...e,navbarLinks:e.navbarLinks?.map(i=>({...i,href:i.url})),instances:t,logo:typeof e.logo=="string"?{dark:e.logo}:e.logo,navigation:r!=null?qT5({navigation:e.navigation,apiName:r}):e.navigation}}function qT5({navigation:e,apiName:t}){return e.map(r=>TT5(r)?{...r,apiName:t}:r)}function TT5(e){return e.api!=null}var DjE=Ft.strictObject({domain:Ft.string(),"custom-domains":Ft.optional(Ft.string().or(Ft.array(Ft.string())))});var BjE=Ft.strictObject({location:Ft.literal("local-file-system"),path:Ft.string()});var IjE=Ft.strictObject({location:Ft.literal("maven"),url:Ft.optional(Ft.string()),coordinate:Ft.string(),username:Ft.optional(Ft.string()),password:Ft.optional(Ft.string())});var CjE=Ft.strictObject({location:Ft.literal("npm"),url:Ft.optional(Ft.string()),"package-name":Ft.string(),token:Ft.optional(Ft.string())});var qjE=Ft.strictObject({location:Ft.literal("postman"),"api-key":Ft.string(),"workspace-id":Ft.string()});var TjE=Ft.strictObject({location:Ft.literal("pypi"),url:Ft.optional(Ft.string()),"package-name":Ft.string(),token:Ft.optional(Ft.string()),username:Ft.optional(Ft.string()),password:Ft.optional(Ft.string())});var RjE=Ft.discriminatedUnion("location",[CjE,IjE,TjE,qjE,BjE]);var zjE=Ft.strictObject({custom:Ft.string()});var NjE=Ft.union([Ft.enum(["MIT","Apache-2.0"]),zjE]);var FjE=Ft.strictObject({repository:Ft.string(),license:Ft.optional(NjE),mode:Ft.optional(Ft.enum(["pull-request","commit"]))});var fYs=Ft.strictObject({name:Ft.string(),version:Ft.string(),output:Ft.optional(RjE),github:Ft.optional(FjE),config:Ft.unknown()});var QjE=Ft.strictObject({audiences:Ft.optional(Ft.array(Ft.string())),docs:Ft.optional(DjE),generators:Ft.array(fYs)});var jlp="default-group",UjE=Ft.strictObject({[jlp]:Ft.optional(Ft.string()),groups:Ft.optional(Ft.record(QjE))});var dYs={Nest:"Nest",MoveUp:"MoveUp"};function e9i({generatorsConfiguration:e,pathModificationStrategy:t}){let r=[];return{value:{"default-group":e[jlp],groups:Object.fromEntries(Object.entries(e.groups??{}).map(([n,a])=>(a.docs!=null&&r.push({url:a.docs.domain,customDomain:a.docs["custom-domains"]?.[0]}),[n,{audiences:a.audiences,generators:a.generators.map(o=>RT5({generatorInvocation:o,pathModificationStrategy:t}))}])))},docsURLs:r}}function RT5({generatorInvocation:e,pathModificationStrategy:t}){return{...e,output:e.output?.location==="local-file-system"?{location:"local-file-system",path:zT5({path:e.output.path,pathModificationStrategy:t})}:e.output}}function zT5({path:e,pathModificationStrategy:t}){switch(t){case"Nest":return Ct(He.of("../"),He.of(e));case"MoveUp":return e.startsWith("../")?e.substring(3):e;default:vt(t)}}var pYs={};Zt(pYs,{GeneratorInvocationSchema:()=>fYs,GeneratorsConfigurationSchema:()=>UjE});var LjE=require("fs/promises");async function t9i({absolutePathToWorkspace:e}){let t=IRi({absolutePathToWorkspace:e}),r=await(0,LjE.readFile)(t),i=Di.load(r.toString()),n=await pYs.GeneratorsConfigurationSchema.safeParseAsync(i);if(n.success)return n.data}var NT5="generators.yml";function IRi({absolutePathToWorkspace:e}){return Ct(e,He.of(NT5))}function _Ys(e){return e.map(t=>{if(Array.isArray(t.customDomain))throw new Error("Expected custom-domain to be a string, but it was an array.");return{...t,customDomain:t.customDomain}})}var FT5="apis";async function VjE({absolutePathToFernDirectory:e,workspaces:t,workspaceContainingDocs:r}){let i=Ct(e,He.of(FT5));await(0,Ucn.mkdir)(i);for(let n of t){let a=Ct(e,He.of(n)),o=await QT5({absolutePathToWorkspace:a});if(n===r){await UT5({absolutePathToWorkspace:a,docsURLs:o,apiName:r});let d=vNa({absolutePathToWorkspace:a});await CLt({src:d,dest:e}),await(0,Ucn.rm)(d,{recursive:!0})}let c=Ct(i,He.of(n));await CLt({src:a,dest:c}),await(0,Ucn.rm)(a,{recursive:!0})}}async function QT5({absolutePathToWorkspace:e}){let t=await t9i({absolutePathToWorkspace:e});if(t==null)return[];let r=IRi({absolutePathToWorkspace:e}),i=e9i({generatorsConfiguration:t,pathModificationStrategy:dYs.Nest});return await(0,Ucn.writeFile)(r,Di.dump(i.value)),i.docsURLs}async function UT5({absolutePathToWorkspace:e,docsURLs:t,apiName:r}){let i=await wBo({absolutePathToWorkspace:e});if(i==null)return;let n=lYs({docsConfiguration:i,docsURLs:_Ys(t),apiName:r}),a=k6i({absolutePathToWorkspace:e});await(0,Ucn.writeFile)(a,Di.dump(n))}var gNa=require("fs/promises");async function WjE({absolutePathToFernDirectory:e,absolutePathToWorkspace:t}){let r=await VT5({absolutePathToWorkspace:t});await LT5({absolutePathToWorkspace:t,docsURLs:r});let i=vNa({absolutePathToWorkspace:t});await CLt({src:i,dest:e}),await CLt({src:t,dest:e}),await(0,gNa.rm)(i,{recursive:!0}),await(0,gNa.rm)(t,{recursive:!0})}async function LT5({absolutePathToWorkspace:e,docsURLs:t}){let r=await wBo({absolutePathToWorkspace:e});if(r==null)return;let i=lYs({docsConfiguration:r,docsURLs:_Ys(t),apiName:void 0}),n=k6i({absolutePathToWorkspace:e});await(0,gNa.writeFile)(n,Di.dump(i))}async function VT5({absolutePathToWorkspace:e}){let t=await t9i({absolutePathToWorkspace:e});if(t==null)return[];let r=IRi({absolutePathToWorkspace:e}),i=e9i({generatorsConfiguration:t,pathModificationStrategy:"MoveUp"});return await(0,gNa.writeFile)(r,Di.dump(i.value)),i.docsURLs}var ONa=require("fs/promises");var WT5="apis";async function GjE({absolutePathToFernDirectory:e,workspaces:t}){let r=Ct(e,He.of(WT5));await(0,ONa.mkdir)(r);for(let i of t){let n=Ct(e,He.of(i));await GT5({absolutePathToWorkspace:n});let a=Ct(r,He.of(i));await CLt({src:n,dest:a}),await(0,ONa.rm)(n,{recursive:!0})}}async function GT5({absolutePathToWorkspace:e}){let t=await t9i({absolutePathToWorkspace:e});if(t==null)return;let r=IRi({absolutePathToWorkspace:e}),i=e9i({generatorsConfiguration:t,pathModificationStrategy:dYs.Nest});await(0,ONa.writeFile)(r,Di.dump(i.value))}var hYs=require("fs/promises");async function HjE({absolutePathToFernDirectory:e,absolutePathToWorkspace:t}){await HT5({absolutePathToWorkspace:t}),await CLt({src:t,dest:e}),await(0,hYs.rm)(t,{recursive:!0})}async function HT5({absolutePathToWorkspace:e}){let t=await t9i({absolutePathToWorkspace:e});if(t==null)return;let r=IRi({absolutePathToWorkspace:e}),i=e9i({generatorsConfiguration:t,pathModificationStrategy:"MoveUp"});await(0,hYs.writeFile)(r,Di.dump(i.value))}var wlp={name:"flatten-fern-directory-structure",summary:"Flattens your fern directory structure. If you have one API, you no longer need an API folder.",run:async({context:e})=>{let t=await KT5();if(t==null){e.failAndThrow("Fern directory not found. Failed to run migration");return}let r=await gB(t),i=[];for(let a of r)a.type==="directory"&&i.push(a);if(i.length===0)return;if(i.length===1&&i[0]!=null){let a=Ct(t,He.of(i[0].name));await mi(k6i({absolutePathToWorkspace:a}))?await WjE({absolutePathToFernDirectory:t,absolutePathToWorkspace:a}):await HjE({absolutePathToFernDirectory:t,absolutePathToWorkspace:a});return}let n=[];for(let a of i){let o=k6i({absolutePathToWorkspace:Ct(t,He.of(a.name))});await mi(o)&&n.push(a)}if(n.length===0||n[0]==null){await GjE({absolutePathToFernDirectory:t,workspaces:i.map(a=>a.name)});return}if(n.length>1){e.failAndThrow("Detected multiple docs websites being published. This is unsupported in the latest upgrade. File an issue (https://github.com/fern-api/fern) if this is important!");return}await VjE({absolutePathToFernDirectory:t,workspaces:i.map(a=>a.name),workspaceContainingDocs:n[0].name})}},xT5="fern";async function KT5(){let e=await JA(xT5,{type:"directory"});if(e!=null)return Sr.of(e)}var JT5={version:"0.15.0-rc0",migrations:[wlp]},xjE=JT5;var Elp=require("fs/promises");var $jE=ce(N4(),1),Slp={name:"require-generators-yml",summary:"A generators.yml file is now required if you are using OpenAPI, AsyncAPI, or gRPC.",run:async({context:e})=>{let t=await $E();if(t==null){e.failAndThrow("Fern directory not found. Failed to run migration");return}let{files:r,directories:i}=await JjE(t),n=i.find(a=>a.name==="apis");if(n==null)await KjE({context:e,files:r,directories:i,absolutePathToFernDirectory:t,absoluteFilepathToWorkspace:t});else for(let a of n.contents){if(a.type!=="directory")continue;let o=Ct(t,He.of("apis"),He.of(a.name));await KjE({context:e,...await JjE(Ct(o)),absolutePathToFernDirectory:t,absoluteFilepathToWorkspace:o})}}};async function KjE({absolutePathToFernDirectory:e,absoluteFilepathToWorkspace:t,context:r,files:i,directories:n}){let a=i.find(c=>c.name==="generators.yml"||c.name==="generators.yaml"),o=n.find(c=>c.name==="openapi");if(a==null){if(o!=null&&o.contents[0]!=null){let c=Ct(t,He.of("generators.yml"));await(0,Elp.writeFile)(c,Di.dump({api:{path:Ct(oJ(e,t),He.of(o.name),He.of(o.contents[0]?.name))}})),r.logger.info(qt.green(`Wrote ${c}`))}}else if(Di.load(a.contents)?.api==null){if(o!=null&&o.contents[0]!=null){let d=$jE.default.parseDocument(a.contents);d.set("api",{path:Ct(oJ(e,t),He.of(o.name),He.of(o.contents[0]?.name))}),await(0,Elp.writeFile)(a.absolutePath,d.toString()),r.logger.info(qt.green(`Updated ${a.absolutePath}`))}}}async function JjE(e){let t=await gB(e),r=[],i=[];for(let n of t)n.type==="directory"?i.push(n):r.push(n);return{files:r,directories:i}}var $T5={version:"0.41.0-rc0",migrations:[Slp]},YjE=$T5;var bYs=require("fs/promises");var kjE=ce(N4(),1),e0E={name:"generators-yml-use-api-specs",summary:"API specification must use the api.specs[] array syntax.",run:async({context:e})=>{let t=await $E();if(t==null){e.failAndThrow("Fern directory not found. Failed to run migration");return}let{files:r,directories:i}=await ZjE(t),n=i.find(a=>a.name==="apis");if(n==null)await XjE({context:e,files:r,directories:i,absoluteFilepathToWorkspace:t});else for(let a of n.contents){if(a.type!=="directory")continue;let o=Ct(t,He.of("apis"),He.of(a.name));await XjE({context:e,...await ZjE(Ct(o)),absoluteFilepathToWorkspace:o})}}};async function XjE({absoluteFilepathToWorkspace:e,context:t,files:r,directories:i}){let n=[],a=r.find(p=>p.name==="generators.yml"||p.name==="generators.yaml");if(a==null){t.failAndThrow("generators.yml not found");return}let o=Di.load(a.contents);if(o==null){t.failAndThrow("generators.yml is null or undefined");return}if(typeof o!="object"){t.failAndThrow("generators.yml is not a valid YAML object");return}if("api"in o){if(o.api==null)return;if(Array.isArray(o.api)){let p=o.api;for(let _ of p){let h=await yYs({oldSpec:_,absoluteFilepathToWorkspace:e,files:r,directories:i,context:t});h&&n.push(h)}}else if(typeof o.api=="object")if("namespaces"in o.api){let p=o.api.namespaces;for(let[_,h]of Object.entries(p))if(Array.isArray(h))for(let y of h){let b=await yYs({oldSpec:y,absoluteFilepathToWorkspace:e,files:r,directories:i,context:t,namespace:_});b&&n.push(b)}else if(typeof h=="string"||typeof h=="object"){let y=await yYs({oldSpec:h,absoluteFilepathToWorkspace:e,files:r,directories:i,context:t,namespace:_});y&&n.push(y)}else{t.logger.warn(`Namespace ${_} is not a valid type. Skipping...`);continue}}else{let p=await yYs({oldSpec:o.api,absoluteFilepathToWorkspace:e,files:r,directories:i,context:t});p&&n.push(p)}else{t.failAndThrow("API spec is not a valid YAML object or array");return}}let c=XT5(o);if("openapi"in o){let p=o.openapi;if(typeof p=="string")n.push({openapi:p,overrides:"openapi-overrides"in o?o["openapi-overrides"]:void 0,origin:"spec-origin"in o?o["spec-origin"]:void 0,settings:Mlp(c)});else if(typeof p=="object"){let _=p;if(_.path==null){t.failAndThrow("openapi path is not defined");return}n.push({openapi:_.path,overrides:_.overrides,origin:_.origin,settings:Mlp(_.settings??{})})}else{t.failAndThrow("openapi is not a string or object");return}}if("async-api"in o){let p=o["async-api"];if(typeof p=="string")n.push({asyncapi:p,settings:t0E(c)});else{t.failAndThrow("async-api is not a string");return}}if(n.length===0){t.logger.debug("No API specs found. Leaving generators.yml unchanged.");return}let d=a.contents.split(`
@@ -2128,7 +2128,7 @@ ${qt.dim(a.summary)}`}));r.push("Do you wish to continue?");let{[t]:i}=await p7o
2128
2128
  `)[0];if(!o)return{version:null,failureReason:"config-not-tracked"};let{stdout:c,failed:d}=await kh(t,"git",["show",`HEAD:${o}`],{cwd:n,doNotPipeOutput:!0,reject:!1});if(d||!c.trim())return{version:null,failureReason:"no-git-history"};let u=JSON.parse(c).version??null;return u==null?{version:null,failureReason:"no-version-field"}:{version:u}}catch(r){return t.debug(`Failed to retrieve version from git: ${r}`),{version:null,failureReason:"parse-error"}}}async function C0E({fromVersion:e,fromGit:t,cliContext:r,fernDirectory:i,projectConfig:n,isLocalDev:a}){let o=e?.trim(),c=process.env[vYs]?.trim(),d=T0E({cliVersion:r.environment.packageVersion,fromVersion:e,isLocalDev:a});if(!o&&c&&c!=="0.0.0"&&!d&&!t&&(o=c),!o||d||t){let s=await hR5(i,r.logger);if(s.version!=null)d&&r.logger.debug(`Detected faulty upgrade (FERN_PRE_UPGRADE_VERSION=${process.env[vYs]}). Using version from git history: ${s.version}`),o=s.version;else if(d){let u=I0E(s.failureReason);r.logger.warn(`Detected potential faulty upgrade but could not retrieve version from git history${u}. Using current config version: ${n.version}`),o=n.version}else if(t){let u=I0E(s.failureReason);r.logger.debug(`Could not retrieve version from git${u}. Falling back to config.`),o=o||n.version}else o=o||n.version}return o}function yR5({cliContext:e,targetVersion:t,currentVersion:r}){T$(t,r)||e.failAndThrow(`Cannot upgrade because target version (${t}) is not ahead of existing version ${r}`)}function bR5(e){let t=new Set(["--version","--to","--from","--from-git"]),r=[],i=0;for(;i<e.length;){let n=e[i];if(i===0&&n==="upgrade"){i++;continue}let a=t.has(n??""),o=Array.from(t).some(c=>n?.startsWith(`${c}=`));a?(i++,i<e.length&&!e[i]?.startsWith("-")&&i++):(o||n!=null&&r.push(n),i++)}return r}async function R0E({cliContext:e,includePreReleases:t,targetVersion:r,fromVersion:i,fromGit:n,yes:a}){let o=e.environment.packageVersion==="0.0.0",c=r?.trim();if(!c){let h=(await e.isUpgradeAvailable({includePreReleases:t})).cliUpgradeInfo;if(h!=null&&h.isUpgradeAvailable)c=h.latestVersion;else{if(o){e.logger.info("No upgrade available.");return}let b=await $E();if(b==null)return e.failAndThrow(`Directory "${CT}" not found.`);let v=await e.runTask(A=>Nbe({directory:b,context:A})),O=T0E({cliVersion:e.environment.packageVersion,fromVersion:i,isLocalDev:o});if(v.version!==e.environment.packageVersion||O)c=e.environment.packageVersion,O?e.logger.info(`Detected faulty upgrade. Config version is ${v.version}, CLI version is ${e.environment.packageVersion}`):e.logger.info(`No newer version available, but config version (${v.version}) differs from CLI version (${e.environment.packageVersion})`);else{e.logger.info("No upgrade available.");return}}}if(e.environment.packageVersion===c||o){let _=await $E();if(_==null)return e.failAndThrow(`Directory "${CT}" not found.`);let h=await e.runTask(v=>Nbe({directory:_,context:v})),y=await C0E({fromVersion:i,fromGit:n,cliContext:e,fernDirectory:_,projectConfig:h,isLocalDev:o});e.logger.info(`Running migrations from ${qt.dim(y)} \u2192 ${qt.green(c)}`),await e.runTask(async v=>{await Clp({fromVersion:y,toVersion:c,context:v,yes:a??!1})}),await e.exitIfFailed();let b=gju(h.rawConfig,v=>{v.version=c});await(0,q0E.writeFile)(h._absolutePath,_R5(JSON.stringify(b,void 0,2))),e.logger.info(`Updated fern.config.json to version ${qt.green(c)}`);return}yR5({cliContext:e,targetVersion:c,currentVersion:e.environment.packageVersion});let d=await $E();if(d==null)return e.failAndThrow(`Directory "${CT}" not found.`);let s=await e.runTask(_=>Nbe({directory:d,context:_})),u=await C0E({fromVersion:i,fromGit:n,cliContext:e,fernDirectory:d,projectConfig:s,isLocalDev:o});e.logger.info(`Upgrading from ${qt.dim(e.environment.packageVersion)} \u2192 ${qt.green(c)}`);let f=bR5(process.argv.slice(2)),p=["upgrade","--from",u,"--to",c,...f];a&&!f.some(_=>_==="--yes"||_==="-y")&&p.push("--yes");try{await DBo({version:c,cliContext:e,env:{[vYs]:u},args:p,throwOnError:!0})}catch(_){if(_ instanceof MBo){e.logger.debug(`Rerun CLI failed with stdout: ${_.stdout}`),e.logger.debug(`Rerun CLI failed with stderr: ${_.stderr}`);let h=(_.stderr??"")+(_.stdout??"");if(h.includes("ETARGET")||h.includes("E404")||h.includes("404 Not Found")||h.includes("No matching version found")||h.includes("version not found"))return e.failAndThrow(`Failed to upgrade to ${c} because it does not exist. See https://www.npmjs.com/package/${e.environment.packageName}?activeTab=versions.`)}throw _}}async function z0E({project:e,cliContext:t,errorOnBrokenLinks:r}){let i=e.docsWorkspaces;if(i==null){t.failAndThrow("No docs workspace found");return}await t.runTaskForWorkspace(i,async n=>{let a=performance.now(),o=await Promise.all(e.apiWorkspaces.map(async u=>u.toFernWorkspace({context:n}))),c=await uL(e),d=await Bsa(i,n,o,c,!0),s=performance.now()-a;Isa({violations:d,context:n,logWarnings:!0,logSummary:!0,logBreadcrumbs:!1,elapsedMillis:s}),d.length>0&&r&&n.failAndThrow()})}function Q0E({apiResults:e,docsResult:t,logWarnings:r,context:i}){let n=performance.now(),a=!1;if(e.filter(u=>{let f=BBo(u.violations);return f.numErrors>0||r&&f.numWarnings>0}).length>0){let u=PR5(e.map(p=>p.violations).flat());if(e.length>1){i.logger.info(qt.cyan(qt.bold("[sdk]")));for(let p of e){let _=BBo(p.violations);(_.numErrors>0||r&&_.numWarnings>0)&&(a=a||_.numErrors>0,gR5({apiName:p.apiName,violations:p.violations,stats:_,logWarnings:r,context:i,indent:" "}))}}else a=a||u.numErrors>0,vR5({violations:e[0]?.violations??[],stats:u,logWarnings:r,context:i})}if(t!=null){let u=BBo(t.violations);(u.numErrors>0||r&&u.numWarnings>0)&&(a=a||u.numErrors>0,OR5({violations:t.violations,stats:u,logWarnings:r,context:i}))}let c=performance.now()-n,d=[...e.map(u=>u.violations).flat(),...t?.violations??[]],s=BBo(d);return jR5({stats:s,logWarnings:r,elapsedMillis:c,context:i}),{hasErrors:a}}function vR5({violations:e,stats:t,logWarnings:r,context:i}){let n=Tlp(t,r);i.logger.info(qt.cyan(qt.bold("[sdk]"))+` ${n}`),qlp({violations:e,logWarnings:r,context:i,indent:" "})}function gR5({apiName:e,violations:t,stats:r,logWarnings:i,context:n,indent:a}){let o=Tlp(r,i);n.logger.info(`${a}${qt.bold(`[${e}]`)} ${o}`),qlp({violations:t,logWarnings:i,context:n,indent:a+" "})}function OR5({violations:e,stats:t,logWarnings:r,context:i}){let n=Tlp(t,r);i.logger.info(qt.magenta(qt.bold("[docs]"))+` ${n}`),qlp({violations:e,logWarnings:r,context:i,indent:" "})}function qlp({violations:e,logWarnings:t,context:r,indent:i}){let n=e.filter(o=>o.severity==="fatal"||o.severity==="error"),a=e.filter(o=>o.severity==="warning");if(t)for(let o of a.sort(F0E))N0E({violation:o,context:r,indent:i});for(let o of n.sort(F0E))N0E({violation:o,context:r,indent:i})}function N0E({violation:e,context:t,indent:r}){let i=mR5(e.severity),n=AR5(e);n===""?t.logger.info(`${r}${i} ${e.message}`):(t.logger.info(`${r}${i}`),t.logger.info(`${r} path: ${qt.blue(n)}`),t.logger.info(`${r} issue: ${e.message}`)),t.logger.info("")}function AR5(e){let t=[];e.relativeFilepath!==""&&t.push(e.relativeFilepath);for(let r of e.nodePath){let i=typeof r=="string"?r:r.key;typeof r!="string"&&r.arrayIndex!=null&&(i+=`[${r.arrayIndex}]`),t.push(i)}return t.join(" -> ")}function mR5(e){switch(e){case"fatal":return qt.red("[error]");case"error":return qt.red("[error]");case"warning":return qt.yellow("[warning]");default:vt(e)}}function Tlp(e,t){let r=[];return e.numErrors>0&&r.push(`${e.numErrors} error${e.numErrors!==1?"s":""}`),t&&e.numWarnings>0&&r.push(`${e.numWarnings} warning${e.numWarnings!==1?"s":""}`),r.join(", ")}function BBo(e){let t=0,r=0;for(let i of e)switch(i.severity){case"fatal":case"error":t+=1;break;case"warning":r+=1;break;default:vt(i.severity)}return{numErrors:t,numWarnings:r}}function PR5(e){return BBo(e)}function F0E(e,t){let r=e.relativeFilepath.localeCompare(t.relativeFilepath);return r!==0?r:JSON.stringify(e.nodePath).localeCompare(JSON.stringify(t.nodePath))}function jR5({stats:e,logWarnings:t,elapsedMillis:r,context:i}){let n=r>0?` in ${(r/1e3).toFixed(3)} seconds.`:".",a=`Found ${e.numErrors} error${e.numErrors!==1?"s":""} and ${e.numWarnings} warning${e.numWarnings!==1?"s":""}`+n;!t&&e.numWarnings>0&&(a+=" Run fern check --warnings to print out the warnings not shown."),e.numErrors>0?i.logger.error(a):e.numWarnings>0?i.logger.warn(a):i.logger.info(qt.green("All checks passed"))}async function U0E({project:e,cliContext:t,logWarnings:r,brokenLinks:i,errorOnBrokenLinks:n,isLocal:a,directFromOpenapi:o}){let c=[],d,s=!1,u=e.docsWorkspaces;if(u!=null){let p=i||n?[]:["valid-markdown-links"],_=await uL(e),h;await t.runTaskForWorkspace(u,async y=>{h=await Y3h({workspace:u,context:y,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:_,errorOnBrokenLinks:n,excludeRules:p})}),h!=null&&(d={violations:h.violations,elapsedMillis:h.elapsedMillis},h.hasErrors&&(s=!0))}await Promise.all(e.apiWorkspaces.map(async p=>{if(p.generatorsConfiguration?.groups.length===0&&p.type!=="fern")return;if(p instanceof tS&&o){await t.runTaskForWorkspace(p,async h=>{await p.getIntermediateRepresentation({context:h,audiences:{type:"all"},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,logWarnings:r})});return}if(p instanceof CEe){let h=Ct(p.absoluteFilePath,He.of(Eq),He.of(yB));if(!await mi(h)){await t.runTask(async b=>(b.logger.error(`Missing file: ${yB}`),b.failAndThrow()));return}}let _;await t.runTaskForWorkspace(p,async h=>{let y=await p.toFernWorkspace({context:h});_=await YvE({workspace:y,context:h,ossWorkspace:p instanceof tS?p:void 0})}),_!=null&&(c.push({apiName:_.apiName,violations:_.violations,elapsedMillis:_.elapsedMillis}),_.hasErrors&&(s=!0))}));let{hasErrors:f}=await t.runTask(p=>Q0E({apiResults:c,docsResult:d,logWarnings:r,context:p}));(f||s)&&t.failAndThrow()}var CRi=require("fs/promises");var Rlp=ce(require("path"),1);async function L0E({project:e,cliContext:t,sdkLanguage:r,preserveSchemaIds:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await t.runTaskForWorkspace(n,async a=>{n instanceof N$?await wR5({workspace:n,context:a}):await ER5({workspace:await n.toFernWorkspace({context:a},{preserveSchemaIds:i}),context:a})})}))}async function wR5({workspace:e,context:t}){for(let[r,i]of Object.entries(e.definition.importedDefinitions)){let n=Ct(e.absoluteFilePath,He.of(Eq),He.of(r),He.of(`.${Eq}`));await V0E({definition:i.definition,absolutePathToOutputDirectory:n}),t.logger.info(qt.green(`Wrote imported definition at ${Rlp.default.relative(process.cwd(),n)}`))}}async function ER5({workspace:e,context:t}){let r=Ct(e.absoluteFilePath,He.of(`.${Eq}`));await V0E({definition:e.definition,absolutePathToOutputDirectory:r}),t.logger.info(qt.green(`Wrote definition to ${Rlp.default.relative(process.cwd(),r)}`))}async function V0E({definition:e,absolutePathToOutputDirectory:t}){let r=(i,n)=>{let a={imports:0,types:1,services:2},o=i in a?a[i]:Object.keys(a).length,c=n in a?a[n]:Object.keys(a).length;return o==null?-1:c==null?1:o!==c?o-c:i.localeCompare(n)};await mi(t)&&await(0,CRi.rm)(t,{recursive:!0}),await(0,CRi.mkdir)(t,{recursive:!0}),await(0,CRi.writeFile)(Ct(t,He.of(yB)),Di.dump(e.rootApiFile.contents,{sortKeys:r}));for(let[i,n]of Object.entries(e.packageMarkers)){let a=Ct(t,He.of(i));await(0,CRi.mkdir)(tn(a),{recursive:!0}),await(0,CRi.writeFile)(a,Di.dump(n.contents,{sortKeys:r}))}for(let[i,n]of Object.entries(e.namedDefinitionFiles)){let a=Ct(t,He.of(i));await(0,CRi.mkdir)(tn(a),{recursive:!0}),await(0,CRi.writeFile)(a,Di.dump(n.contents,{sortKeys:r}))}}var W0E=require("fs/promises");async function G0E({project:e,outputPath:t,cliContext:r}){let i=e.docsWorkspaces;i!=null&&await r.runTaskForWorkspace(i,async n=>{let a=await uL(e),o=await Promise.all(e.apiWorkspaces.map(async s=>s.toFernWorkspace({context:n},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),d=await new c8t({domain:i.config.instances[0]?.url??"http://localhost:8080",docsWorkspace:i,ossWorkspaces:a,apiWorkspaces:o,taskContext:n,editThisPage:void 0,uploadFiles:void 0,registerApi:void 0,targetAudiences:i.config.instances[0]?.audiences?Array.isArray(i.config.instances[0].audiences)?i.config.instances[0].audiences:[i.config.instances[0].audiences]:void 0}).resolve();await(0,W0E.writeFile)(Sr.of(t),JSON.stringify(d,null,2)),n.logger.info(qt.green(`Docs definition written to ${t}`))})}var uwE=ce(kJc(),1),ANa=require("fs"),iLt=require("fs/promises"),swE=ce(R4c(),1),Llp=ce(require("path"),1);var SR5="https://r88yjrnw5k.execute-api.us-east-1.amazonaws.com/dev2/translate",MR5=3,DR5=1e3,BR5=3e4,IR5=3e4;function H0E(e,t){if(e.name==="AbortError"||e.code==="ECONNRESET"||e.code==="ENOTFOUND"||e.code==="ECONNREFUSED"||e.code==="ETIMEDOUT")return!0;if(e.cause instanceof Error){let r=e.cause;if(r.code==="ECONNRESET"||r.code==="ENOTFOUND"||r.code==="ECONNREFUSED"||r.code==="ETIMEDOUT")return!0}if(t){let r=t.status;if(r>=500&&r<600||r===429||r===408)return!0}return!1}function x0E(e,t,r){let i=t*Math.pow(2,e-1),n=Math.random()*.1*i;return Math.min(i+n,r)}function CR5(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r);return fetch(e,{...t,signal:i.signal}).finally(()=>{clearTimeout(n)})}async function IBo({text:e,language:t,sourceLanguage:r,fileType:i,cliContext:n,retryConfig:a={}}){if(t===r)return e;let o=await qpn();if(o==null)throw n.logger.error("Authentication required. Please run 'fern login' or set the FERN_TOKEN environment variable."),new Error("Authentication required for translation service");let c={maxRetries:a.maxRetries??MR5,baseDelay:a.baseDelay??DR5,maxDelay:a.maxDelay??BR5,timeout:a.timeout??IR5},d;for(let u=1;u<=c.maxRetries+1;u++)try{let f=await CR5(SR5,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.value}`},body:JSON.stringify({text:e,source_language:r,target_language:t,...i!==void 0&&{file_type:i}})},c.timeout);if(!f.ok){let _="";try{let y=await f.json();_=y.detail||JSON.stringify(y)}catch{_=await f.text()}if(f.status===403)throw new Error(`403: ${_}`);let h=new Error(`HTTP ${f.status}: ${_}`);if(!H0E(h,f))return n.logger.debug(`[TRANSLATE] Non-retriable error ${f.status}: ${_}`),e;if(d=h,u<=c.maxRetries){n.logger.debug(`[TRANSLATE] Attempt ${u} failed with status ${f.status}: ${_}. Retrying...`);let y=x0E(u,c.baseDelay,c.maxDelay);await new Promise(b=>setTimeout(b,y));continue}else return n.logger.debug(`[TRANSLATE] All ${c.maxRetries+1} attempts failed. Final error: ${_}`),e}let p=await f.json();return u>1&&n.logger.debug(`[TRANSLATE] Succeeded on attempt ${u} after ${u-1} retries`),await new Promise(_=>setTimeout(_,500)),p.translated_text??e}catch(f){if(d=f,f instanceof Error&&f.message.includes("403"))throw f;if(f instanceof Error&&!H0E(f)){let h=f instanceof Error?f.message:String(f);return n.logger.debug(`[TRANSLATE] Non-retriable error: ${h}`),e}if(u>c.maxRetries){let h=f instanceof Error?f.message:String(f);return n.logger.debug(`[TRANSLATE] All ${c.maxRetries+1} attempts failed. Final error: ${h}`),e}let p=f instanceof Error?f.message:String(f);n.logger.debug(`[TRANSLATE] Attempt ${u} failed: ${p}. Retrying...`);let _=x0E(u,c.baseDelay,c.maxDelay);await new Promise(h=>setTimeout(h,_))}let s=d instanceof Error?d.message:d?String(d):"Unknown error";return n.logger.debug(`[TRANSLATE] Unexpected end of retry loop. Last error: ${s}`),e}var qR5=new Set(["title","display-name","page","section","text","link","message","subtitle","search-text","system-prompt","summary","description","docs","tags","api"]);function K0E(e,t){return typeof t!="string"||t==="string"||t.startsWith("./")?!1:!!qR5.has(e)}function jxn({name:e}){let t=e.replace(/\.(md|mdx)$/i,"");return UE(t)}function TR5(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.page=="string"&&typeof t.path=="string"}function RR5(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.section=="string"&&Array.isArray(t.contents)}function zR5(e){return typeof e!="object"||e===null?!1:typeof e.api=="string"}function NR5(e){return typeof e!="object"||e===null?!1:typeof e.changelog=="string"}function FR5(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t["display-name"]=="string"||typeof t.displayName=="string"}function QR5(e){if(typeof e!="object"||e===null)return!1;let t=e;return(typeof t["display-name"]=="string"||typeof t.displayName=="string")&&typeof t.path=="string"}function UR5(e){if(typeof e!="object"||e===null)return;let t=e;if(typeof t.slug=="string")return t.slug;if(t["skip-slug"]!==!0){if(TR5(e))return jxn({name:e.page});if(RR5(e))return jxn({name:e.section});if(zR5(e)){let r=e["api-name"],i=e.api;return jxn({name:typeof r=="string"?r:i})}if(NR5(e)){let r=e.title;if(typeof r=="string")return jxn({name:r});let i=e.changelog;if(typeof i=="string"){let n=i.split("/").pop()||i;return jxn({name:n})}}if(FR5(e)){let r=e["display-name"]||e.displayName;if(typeof r=="string")return jxn({name:r})}if(QR5(e)){let r=e["display-name"]||e.displayName;if(typeof r=="string")return jxn({name:r})}}}async function zlp({obj:e,language:t,sourceLanguage:r,filePath:i,cliContext:n,stub:a,sourceObj:o}){if(e==null||typeof e=="string")return e;if(Array.isArray(e)){let c=Array.isArray(o)?o:void 0;return await Promise.all(e.map((d,s)=>zlp({obj:d,language:t,sourceLanguage:r,filePath:i,cliContext:n,stub:a,sourceObj:c?.[s]})))}if(typeof e=="object"){let c={},d=typeof o=="object"&&o!==null?o:void 0,s;s=UR5(e);for(let[u,f]of Object.entries(e))if(u!=="slug")if(K0E(u,f)){if(a){c[u]=f;continue}c[u]=await IBo({text:f,language:t,sourceLanguage:r,cliContext:n})}else c[u]=await zlp({obj:f,language:t,sourceLanguage:r,filePath:i,cliContext:n,stub:a,sourceObj:d?.[u]});return s!==void 0&&(c.slug=s),c}return e}async function J0E({yamlContent:e,language:t,sourceLanguage:r,filePath:i,cliContext:n,stub:a=!1}){if(t===r)return e;try{let o=r$n(e);if(!o)return e;let c=await zlp({obj:o,language:t,sourceLanguage:r,filePath:i,cliContext:n,stub:a,sourceObj:o});return ifn(c,{indent:2,lineWidth:-1,quotingType:'"',forceQuotes:!1})}catch(o){if(o instanceof Error&&o.message.includes("403"))throw o;return n.logger.error(` [ERROR] Failed to process YAML file ${i}: ${o}`),e}}async function gYs({transformation:e,cliContext:t,stub:r=!1}){let{filePath:i,language:n,sourceLanguage:a,originalContent:o}=e;if(r&&!i.endsWith(".yml")&&!i.endsWith(".yaml"))return t.logger.debug(`[STUB] Returning content as-is for ${i} (stub mode enabled)`),o;t.logger.debug(`[PROCESSING] ${i} for language: ${n} (source: ${a})`);try{return(i.endsWith(".yml")||i.endsWith(".yaml"))&&!i.includes("generators.yml")?await J0E({yamlContent:o,language:n,sourceLanguage:a,filePath:i,cliContext:t,stub:r}):i.endsWith(".md")||i.endsWith(".mdx")?IBo({text:o,language:n,sourceLanguage:a,fileType:"MDX",cliContext:t}):i.endsWith(".json")&&!i.includes("fern.config.json")?IBo({text:o,language:n,sourceLanguage:a,cliContext:t}):(t.logger.debug(`[SKIP] Skipping file "${i}" - unsupported file type for translation.`),o)}catch(c){if(c instanceof Error&&c.message.includes("403"))throw c;return o}}function $0E(e){let t=[".png",".jpg",".jpeg",".gif",".svg",".webp",".ico",".bmp",".tiff",".tif",".woff",".woff2",".ttf",".otf",".eot",".pdf",".doc",".docx",".mp4",".webm",".ogg",".mp3",".wav",".zip",".tar",".gz",".bin"],r=e.toLowerCase();return t.some(i=>r.endsWith(i))}function Y0E(e,t){return e.endsWith(".yaml")||e.endsWith(".yml")?!0:e.endsWith(".md")||e.endsWith(".mdx")||e.endsWith(".json")&&!e.includes("fern.config.json")?!t:!1}var AYs=require("fs/promises");function OYs(e,t){try{let r=new URL(e),i=r.hostname,n=e.endsWith("/");if(i.includes(".docs.buildwithfern.com")){let o=i.split(".")[0];r.hostname=`${o}-${t}.docs.buildwithfern.com`,r.pathname=`/${t}${r.pathname}`}else r.hostname=`${t}.${i}`,r.pathname=`/${t}${r.pathname}`;let a=r.toString();return!n&&a.endsWith("/")&&r.pathname===`/${t}/`&&(a=a.slice(0,-1)),a}catch{let r=e.endsWith("/");if(e.includes("://")){let[i,n]=e.split("://"),[a,...o]=n?.split("#")??[],[c,...d]=a?.split("?")??[],[s,...u]=c?.split("/")??[];if(!s)return e;let f;s.includes(".docs.buildwithfern.com")?f=`${s.split(".")[0]}-${t}.docs.buildwithfern.com/${t}`:f=`${t}.${s}/${t}`;let p=`${i}://${f}`;return u.length>0?p+="/"+u.join("/"):r&&(p+="/"),d.length>0&&(p+="?"+d.join("?")),o.length>0&&(p+="#"+o.join("#")),p}else if(e.includes("/")){let i=e.split("/"),n=i[0],a=i.slice(1),o;return n?.includes(".docs.buildwithfern.com")?o=`${n.split(".")[0]}-${t}.docs.buildwithfern.com/${t}`:o=`${t}.${n}/${t}`,a.length>0||a.some(c=>c!=="")?`${o}/${a.join("/")}`:r?`${o}/`:o}else return e.includes(".docs.buildwithfern.com")?`${e.split(".")[0]}-${t}.docs.buildwithfern.com/${t}`:`${t}.${e}/${t}`}}function LR5(e,t){let r=VR5({docsConfig:e,language:t});return WR5({docsConfig:r,language:t})}function VR5({docsConfig:e,language:t}){let r=structuredClone(e);return r.settings?(r.settings.language=t,r.settings["search-text"]=X0E[t]):r.settings={language:t,"search-text":X0E[t]},r}var X0E={en:"Search",es:"Buscar",fr:"Rechercher",de:"Suchen",it:"Cerca",pt:"Pesquisar",ja:"\u691C\u7D22",zh:"\u641C\u7D22",ko:"\uAC80\uC0C9",el:"\u0391\u03BD\u03B1\u03B6\u03AE\u03C4\u03B7\u03C3\u03B7",no:"S\xF8k",pl:"Szukaj",ru:"\u041F\u043E\u0438\u0441\u043A",sv:"S\xF6k",tr:"Ara"};function WR5({docsConfig:e,language:t}){let r=structuredClone(e);return r.instances&&Array.isArray(r.instances)&&(r.instances=r.instances.map(i=>{let n={...i};if(n.url&&(n.url=OYs(n.url,t)),n["custom-domain"]){let a=n["custom-domain"];typeof a=="string"?n["custom-domain"]=OYs(a,t):Array.isArray(a)&&(n["custom-domain"]=a.map(o=>OYs(o,t)))}return n})),r}async function Z0E({originalDocsConfigPath:e,targetDirectory:t,language:r,sourceLanguage:i,context:n,stub:a=!1}){try{let o=await(0,AYs.readFile)(e,"utf-8"),d=await gYs({transformation:{filePath:r0,language:r,sourceLanguage:i,originalContent:o},cliContext:n,stub:a}),s=Di.load(d),u=LR5(s,r),f=Ct(t,He.of(r0)),p=Di.dump(u,{sortKeys:!1});await(0,AYs.writeFile)(f,p,"utf-8"),n.logger.debug(`Created language-specific docs config: ${f}`)}catch(o){if(o instanceof Error&&o.message.includes("403"))throw o;n.logger.warn(`Failed to create language-specific docs config for ${r}: ${o}`)}}var k0E=require("fs"),ewE=require("fs/promises"),twE=ce(require("path"),1);async function Nlp(e,t){let r={},i=await(0,ewE.readdir)(e);for(let n of i){if(n==="translations")continue;let a=twE.default.join(e,n),o=t?Ct(t,He.of(n)):He.of(n),c=(0,k0E.statSync)(a);if(c.isDirectory()){let d=await Nlp(a,o);for(let[s,u]of Object.entries(d))r[s]=u}else c.isFile()&&(r[a]=o)}return r}var rwE=require("crypto"),iwE=require("fs"),CBo=require("fs/promises"),Flp=ce(require("path"),1);function nwE(e){return(0,rwE.createHash)("sha256").update(e,"utf-8").digest("hex")}async function awE(e){let t=Flp.default.join(e,"hashes");if(!(0,iwE.existsSync)(t))return{};try{let r=await(0,CBo.readFile)(t,"utf-8"),i=JSON.parse(r),{_comment:n,...a}=i;return a}catch{return{}}}async function Qlp(e,t){let r=Flp.default.join(e,"hashes"),i={};Object.keys(t).sort().forEach(a=>{let o=t[a];o!==void 0&&(i[a]=o)});let n={_comment:"This file is auto-generated by Fern to track source file changes for translation purposes. Do not edit manually - it will be overwritten on the next translation update.",...i};await(0,CBo.writeFile)(r,JSON.stringify(n,null,2),"utf-8")}async function mYs(e,t,r){try{let i=await(0,CBo.readFile)(e,"utf-8"),n=nwE(i),a=r[t];return n!==a}catch{return!0}}function GR5(e,t,r){let i=nwE(r);e[t]=i}async function Ulp(e,t,r,i){GR5(t,r,i),await Qlp(e,t)}function owE(e,t){let r={};for(let[i,n]of Object.entries(e))t.has(i)&&(r[i]=n);return r}async function cwE({project:e,cliContext:t,stub:r=!1}){let i=e.docsWorkspaces;if(i==null){t.logger.error("No docs workspace found. Please ensure you have a docs.yml file configured.");return}let n=i.config.languages;if(n==null||n.length===0){t.logger.error("No languages found in docs.yml configuration. Please add a 'languages' field with the desired languages.");return}await t.runTaskForWorkspace(i,async a=>{let o=i.absoluteFilePath,c=Ct(o,He.of("translations")),d=n[0];if(!d)throw new Error("Unexpected error - first element of languages array is invalid");(0,ANa.existsSync)(c)||(a.logger.debug(`Creating translations directory at: ${c}`),await(0,iLt.mkdir)(c,{recursive:!0}));let s={},u=n.filter(y=>y!==d),f=Ct(o,He.of(r0)),p=(0,ANa.existsSync)(f);for(let y of u){let b=Ct(c,He.of(y),He.of("fern"));(0,ANa.existsSync)(b)||await(0,iLt.mkdir)(b,{recursive:!0}),s[y]={filesProcessed:0,filesSkipped:0}}s[d]={filesProcessed:0,filesSkipped:0};let _={filesProcessed:0,filesSkipped:0};try{let y=await awE(c),b=await Nlp(o,""),v=Object.entries(b),O=new Set(Object.values(b)),A=owE(y,O);Object.keys(A).length!==Object.keys(y).length&&await Qlp(c,A),y=A;let g=[];for(let[q,N]of v)p&&N===r0||Y0E(q,r)&&await mYs(q,N,y)&&g.push([q,N]);let m=!1;p&&(m=await mYs(f,He.of(r0),y));let j=g.length+(m?1:0),M=j*u.length,w=process.stdout.isTTY&&!swE.default&&M>0,D;w&&(D=new uwE.default.SingleBar({format:"Processing files [{bar}] {percentage}% | {value}/{total} files",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,clearOnComplete:!1,stopOnComplete:!0}),D.start(M,0));let B=0,z=0;try{if(p)if(m){for(let Q of u){B++,z++,w||a.logger.info(qt.gray(`[${z}/${j+1}] Processing: ${r0} (docs config) for language: ${Q}`)),t.logger.debug(`[PROCESSING] ${r0} (docs config) for language: ${Q}`);let x=Ct(c,He.of(Q),He.of("fern"));await Z0E({originalDocsConfigPath:f,targetDirectory:x,language:Q,sourceLanguage:d,context:t,stub:r});let ee=s[Q];D&&D.update(B),ee&&ee.filesProcessed++,t.logger.debug(`[COMPLETED] ${r0} -> ${Q}/${r0}`)}let q=await(0,iLt.readFile)(f,"utf-8");await Ulp(c,y,He.of(r0),q);let N=s[d];N&&N.filesProcessed++,t.logger.debug(`[HASH UPDATED] ${r0} -> ${d} (source language - hash updated)`)}else{for(let q of n){let N=s[q];N&&N.filesSkipped++}t.logger.debug(`[SKIPPED] ${r0} (no changes since last translation)`)}for(let[q,N]of v){if(p&&N===r0){t.logger.debug(`[SKIPPED] ${N} (already handled by docs config processing)`);continue}if(!await mYs(q,N,y)){for(let ve of n){let be=s[ve];be&&be.filesSkipped++}t.logger.debug(`[SKIPPED] ${N} (no changes since last translation)`);continue}t.logger.debug(`[PROCESSING] ${N} (detected changes)`);let x=await(0,iLt.readFile)(q,"utf-8");await Ulp(c,y,N,x);let ee=s[d];ee&&ee.filesProcessed++,t.logger.debug(`[HASH UPDATED] ${N} -> ${d} (source language - hash only)`);for(let ve of u){z++,B++,w||a.logger.info(qt.gray(`[${z}/${j}] Processing: ${N}`));let be=Ct(c,He.of(ve),He.of("fern")),H=Ct(be,N),G=Llp.default.dirname(H);(0,ANa.existsSync)(G)||await(0,iLt.mkdir)(G,{recursive:!0});let se=await gYs({transformation:{filePath:N,language:ve,sourceLanguage:d,originalContent:x},cliContext:t,stub:r});await(0,iLt.writeFile)(H,se,"utf-8");let Ae=s[ve];Ae&&Ae.filesProcessed++,t.logger.debug(`[COMPLETED] ${N} -> ${ve}/${N}`),D&&D.update(B)}}}finally{D&&(D.update(M),D.stop(),t.logger.info())}a.logger.info(qt.cyan("Copying asset files..."));let F=0;for(let[q,N]of v)if($0E(q))for(let Q of u){let x=Ct(c,He.of(Q),He.of("fern")),ee=Ct(x,N),ve=Llp.default.dirname(ee);(0,ANa.existsSync)(ve)||await(0,iLt.mkdir)(ve,{recursive:!0}),await(0,iLt.copyFile)(q,ee),F++,t.logger.debug(`[ASSET COPIED] ${N} -> ${Q}/${N}`)}F>0&&a.logger.info(qt.green(`\u2713 Copied ${F} asset files to translation directories`));for(let q of n){let N=s[q];if(!N)continue;_.filesProcessed+=N.filesProcessed,_.filesSkipped+=N.filesSkipped;let Q=N.filesProcessed+N.filesSkipped;q===d?(a.logger.info(qt.blue(`${q} (source) hash tracking summary: ${N.filesProcessed} processed, ${N.filesSkipped} skipped (${Q} total)`)),a.logger.info(qt.green(`\u2713 Successfully tracked ${q} source language hashes (no directory created)`))):(a.logger.info(qt.blue(`${q} translation summary: ${N.filesProcessed} processed, ${N.filesSkipped} skipped (${Q} total)`)),a.logger.info(qt.green(`\u2713 Successfully created ${q} translation with content processing`)))}}catch(y){throw y instanceof Error&&y.message.includes("403")||a.logger.error(`Failed to create translations: ${y}`),y}let h=_.filesProcessed+_.filesSkipped;if(a.logger.info(qt.cyan(`Overall summary: ${_.filesProcessed} files processed, ${_.filesSkipped} files skipped across ${n.length} languages (${h} total operations)`)),a.logger.info(qt.green(`Translations created successfully in: ${c}`)),u.length>0){a.logger.info("You can now modify the content in each language directory:");for(let y of u)a.logger.info(qt.blue(` - ${y}: ${Ct(c,He.of(y))}`))}if(a.logger.info(`Source language (${d}) values are tracked as hashes in translations/hashes`),p&&u.length>0){a.logger.info("Language-specific docs configurations created with modified instance URLs:");for(let y of u)a.logger.info(` - ${y}/docs.yml: URLs modified to include ${y} prefix`)}})}var PYs=HR5();function HR5(){return typeof window<"u"&&typeof window.document<"u"?{type:"browser",version:window.navigator.userAgent}:typeof globalThis<"u"&&globalThis?.navigator?.userAgent==="Cloudflare-Workers"?{type:"workerd"}:typeof EdgeRuntime=="string"?{type:"edge-runtime"}:typeof self=="object"&&typeof self?.importScripts=="function"&&(self.constructor?.name==="DedicatedWorkerGlobalScope"||self.constructor?.name==="ServiceWorkerGlobalScope"||self.constructor?.name==="SharedWorkerGlobalScope")?{type:"web-worker"}:typeof Deno<"u"&&typeof Deno.version<"u"&&typeof Deno.version.deno<"u"?{type:"deno",version:Deno.version.deno}:typeof Bun<"u"&&typeof Bun.version<"u"?{type:"bun",version:Bun.version}:typeof process<"u"&&"version"in process&&!!process.version&&"versions"in process&&!!process.versions?.node?{type:"node",version:process.versions.node,parsedVersion:Number(process.versions.node.split(".")[0])}:typeof navigator<"u"&&navigator?.product==="ReactNative"?{type:"react-native"}:{type:"unknown"}}u95();var o95="The Fern CLI requires Node 18+ or above.";async function u95(){let e=process.argv.includes("--local"),t=new ucu(process.stdout,process.stderr,{isLocal:e}),r=async()=>{await t.exit()};if(PYs.type==="node"&&PYs.parsedVersion!=null&&PYs.parsedVersion>=18){let{setGlobalDispatcher:i,Agent:n}=await Promise.resolve().then(()=>ce(o_p(),1));i(new n({connect:{timeout:2147483647},bodyTimeout:0,headersTimeout:2147483647}))}if(process.env.HTTP_PROXY!=null){let{setGlobalDispatcher:i,ProxyAgent:n}=await Promise.resolve().then(()=>ce(o_p(),1)),a=new n(process.env.HTTP_PROXY);i(a)}process.on("SIGINT",async()=>{t.suppressUpgradeMessage(),await r()});try{let i=process.env[SBo];i!=null&&process.chdir(i);let n=await c95(t);t.environment.packageVersion===n?await s95(t):await DBo({version:n,cliContext:t})}catch(i){await t.instrumentPostHogEvent({command:process.argv.join(" "),properties:{failed:!0,error:i}}),i?.message.includes("globalThis")?(t.logger.error(o95),t.failWithoutThrowing()):i instanceof WS?t.failWithoutThrowing():i instanceof dzi?t.logger.error(`Failed. ${i.log}`):t.failWithoutThrowing("Failed.",i)}await r()}async function s95(e){let t=ath(vUc(process.argv)).scriptName(e.environment.cliName).version(!1).fail((r,i,n)=>{i==null&&(n.showHelp(),e.logger.error(r))}).strict().exitProcess(!1).command("$0",!1,r=>r.option("version",{describe:"Print current version",alias:"v"}).version(!1),r=>{r.version!=null?e.logger.info(e.environment.packageVersion):(t.showHelp(),e.failAndThrow())}).option("log-level",{default:oc.Info,choices:cGi}).demandCommand().recommendCommands();d95(t,e),p95(t,e),f95(t,e),_95(t,e),h95(t,e),y95(t,e),b95(t,e),O95(t,e),v95(t,e),g95(t,e),P95(t,e),A95(t,e),m95(t,e),M95(t,e),D95(t,e),B95(t,e),N95(t,e),F95(t,e),C95(t,e),q95(t,e),z95(t,e),I95(t,e),E95(t,e),S95(t,e),j95({cli:t,cliContext:e,onRun:()=>{e.suppressUpgradeMessage()}}),w95(t,e),G95(t,e),H95(t,e),x95(t,e),K95(t,e),j0h(t,e),w0h(t,e),J95(t,e),t.middleware(async r=>{e.setLogLevel(r["log-level"]),e.logFernVersionDebug()}),await t.parse()}async function c95(e){if(process.env.FERN_NO_VERSION_REDIRECTION==="true")return e.environment.packageVersion;let t=await $E();if(t!=null){let r=await e.runTask(i=>Nbe({directory:t,context:i}));return r.version==="*"?e.environment.packageVersion:r.version}return CKi({cliEnvironment:e.environment})}async function l95(e){let t=await $E();if(t!=null)return(await e.runTask(i=>Nbe({directory:t,context:i}))).organization}function f95(e,t){e.command("init","Initialize a Fern API",r=>r.option("api",{boolean:!0,description:"Initialize an api."}).option("docs",{boolean:!0,description:"Initialize a docs website."}).option("organization",{alias:"org",type:"string",description:"Organization name"}).option("openapi",{type:"string",description:"Filepath or url to an existing OpenAPI spec"}).option("mintlify",{type:"string",description:"Migrate docs from Mintlify provided a path to a mint.json file"}).option("readme",{type:"string",description:"Migrate docs from Readme provided a URL to a Readme generated docs site"}),async r=>{if(r.organization==null){let i=await l95(t);i!=null?r.organization=i:r.organization=await t.getInput({message:"Please enter your organization"})}if(r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.");if(r.readme!=null&&r.mintlify!=null)return t.failWithoutThrowing("Cannot specify both --readme and --mintlify. Please choose one.");if(r.readme!=null)await t.runTask(async i=>{await mFc({readmeUrl:r.readme,organization:r.organization??"fern",taskContext:i,versionOfCli:await CKi({cliEnvironment:t.environment})})});else if(r.docs!=null)await t.runTask(async i=>{await jMc({organization:r.organization,versionOfCli:await CKi({cliEnvironment:t.environment}),taskContext:i})});else if(r.mintlify!=null)await t.runTask(async i=>{await DMc({pathToMintJson:r.mintlify,organization:r.organization??"fern",taskContext:i,versionOfCli:await CKi({cliEnvironment:t.environment})})});else{let i;if(r.openapi!=null){if(Zln(r.openapi)){let a=await cth({url:r.openapi,logger:t.logger});a.status==="failure"&&t.failAndThrow(a.errorMessage);let o=a.filePath;i=Sr.of(o)}else i=Sr.of(Uu(WA(),r.openapi));await mi(i)||t.failAndThrow(`${i} does not exist`)}await t.runTask(async n=>{await mMc({organization:r.organization,versionOfCli:await CKi({cliEnvironment:t.environment}),context:n,openApiPath:i})})}})}function d95(e,t){e.command("diff","Diff two versions of an API",r=>r.option("from",{string:!0,demandOption:!0,description:"The previous version of the API"}).option("to",{string:!0,demandOption:!0,description:"The next version of the API"}).option("from-version",{string:!0,description:"The previous version of the API (e.g. 1.1.0)"}).option("from-generator-version",{string:!0,description:"The previous version of the generator (e.g. 1.1.0)"}).option("to-generator-version",{string:!0,description:"The next version of the generator (e.g. 1.1.0)"}).option("quiet",{boolean:!0,default:!1,alias:"q",description:"Whether to suppress output written to stderr"}).middleware(i=>{if(!T2s(i.fromGeneratorVersion,i.toGeneratorVersion))throw new Error("Both --from-generator-version and --to-generator-version must be provided together, or neither should be provided")}),async r=>{let i=C2s(r.fromVersion),n=q2s({from:r.fromGeneratorVersion,to:r.toGeneratorVersion}),a=await I0h({context:t,from:r.from,to:r.to,fromVersion:i,generatorVersions:n});if(i!=null){let{errors:c,...d}=a;t.logger.info(JSON.stringify(d))}!r.quiet&&a.errors.length>0&&t.stderr.info(a.errors.join(`
2129
2129
  `));let o=a.bump==="major"?1:0;await t.exit({code:o})})}function p95(e,t){e.command("sdk-diff <from-dir> <to-dir>",!1,r=>r.positional("from-dir",{type:"string",demandOption:!0,description:"Path to the directory containing the previous version of the SDK"}).positional("to-dir",{type:"string",demandOption:!0,description:"Path to the directory containing the next version of the SDK"}).option("json",{boolean:!0,default:!1,description:"Output result as JSON"}),async r=>{await t.instrumentPostHogEvent({command:"fern sdk-diff"});let i=await jO(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),n=await NgE({context:t,project:i,fromDir:r.fromDir,toDir:r.toDir});r.json?t.logger.info(JSON.stringify(n,null,2)):(t.logger.info(`
2130
2130
  `+n.message),t.logger.info(`
2131
- Version Bump: ${n.version_bump}`))})}function _95(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async i=>{await LgE({orgId:r.organization??(await jO(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:i})})})}function h95(e,t){e.command("add <generator>",`Add a code generator to ${GM}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{await S0h({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:r.generator,groupName:r.group,cliContext:t})})}function y95(e,t){e.command(["generate"],"Generate all generators in the specified group",r=>r.option("api",{string:!0,description:"If multiple APIs, specify the name with --api <name>. Otherwise, just --api."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("group",{type:"string",description:"The group to generate"}).option("mode",{choices:Object.values(egE),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally, using Docker"}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}).option("force",{boolean:!0,default:!1,description:"Ignore prompts to confirm generation, defaults to false"}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("disable-snippets",{boolean:!0,description:"Disable snippets in docs generation.",default:!1}).option("runner",{choices:["docker","podman"],description:"Choose the container runtime to use for local generation.",default:void 0}).option("lfs-override",{type:"string",hidden:!0,description:"Override output mode to local-file-system with the specified path"}).option("disable-dynamic-snippets",{boolean:!0,description:"Disable dynamic SDK snippets in docs generation",default:!1}).option("prompt",{boolean:!0,description:"Prompt for confirmation before generating (use --no-prompt to skip)",default:!0}).option("skip-upload",{boolean:!0,description:"Skip asset upload step and generate fake links for preview",default:!1}).option("fernignore",{type:"string",description:"Path to a custom .fernignore file to use instead of the one on the main branch (remote generation only)"}).option("dynamic-ir-only",{boolean:!0,description:"Only upload dynamic IR for specified version, skip SDK generation (remote generation only)",default:!1}),async r=>r.api!=null&&r.docs!=null?t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one."):r.skipUpload&&!r.preview?t.failWithoutThrowing("The --skip-upload flag can only be used with --preview."):r.skipUpload&&r.docs==null?t.failWithoutThrowing("The --skip-upload flag can only be used with --docs."):r.fernignore!=null&&(r.local||r.runner!=null)?t.failWithoutThrowing("The --fernignore flag is not supported with local generation (--local or --runner). It can only be used with remote generation."):r["dynamic-ir-only"]&&(r.local||r.runner!=null)?t.failWithoutThrowing("The --dynamic-ir-only flag is not supported with local generation (--local or --runner). It can only be used with remote generation."):r["dynamic-ir-only"]&&r.version==null?t.failWithoutThrowing("The --dynamic-ir-only flag requires a version to be specified with --version."):r["dynamic-ir-only"]&&r.docs!=null?t.failWithoutThrowing("The --dynamic-ir-only flag can only be used for API generation, not docs generation."):r.api!=null?await jcp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local||r.runner!=null,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,dynamicIrOnly:r["dynamic-ir-only"]}):r.docs!=null?(r.group!=null&&t.logger.warn("--group is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await rgE({project:await jO(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview,brokenLinks:r.brokenLinks,strictBrokenLinks:r.strictBrokenLinks,disableTemplates:r.disableSnippets,noPrompt:!r.prompt,skipUpload:r.skipUpload})):await jcp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,dynamicIrOnly:r["dynamic-ir-only"]}))}function b95(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(en.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}).option("disable-examples",{boolean:!0,description:"Whether to disable automatic example generation in the IR",default:!1}),async r=>{await sgE({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:Uu(WA(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,readme:void 0,directFromOpenapi:r.fromOpenapi,disableExamples:r.disableExamples})})}function v95(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(en.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await fgE({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:Uu(WA(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function g95(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(en.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("disable-examples",{boolean:!0,description:"Whether to suppress examples from being included in the IR"}),async r=>{await ngE({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:Uu(WA(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,disableDynamicExamples:r.disableExamples??!1})})}function O95(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the FDR API definition for certain audiences"}).option("v2",{boolean:!0,description:"Use v2 format"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{r.v2?await wcp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:Uu(WA(),r.pathToOutput),directFromOpenapi:!1,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):r.fromOpenapi?await wcp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:Uu(WA(),r.pathToOutput),directFromOpenapi:!0,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):await ogE({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:Uu(WA(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function A95(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>j8(a));await qgE({project:i,cliContext:t,token:n,version:r.version})})}function m95(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>j8(a));await TgE({project:i,cliContext:t,token:n})})}function P95(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("local",{boolean:!0,description:"Run validation locally without sending data to Fern API.",default:!1}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{await U0E({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,logWarnings:r.warnings,brokenLinks:r.brokenLinks,errorOnBrokenLinks:r.strictBrokenLinks,directFromOpenapi:r.fromOpenapi})})}function j95({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades Fern CLI version in ${JU}`,i=>i.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}).option("to",{string:!0,hidden:!0}).option("from",{string:!0,description:"The version to migrate from. Use this to manually run migrations when upgrading from an older CLI version."}).option("from-git",{boolean:!0,hidden:!0}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to migration prompts."}),async i=>{await R0E({cliContext:t,includePreReleases:i.rc,targetVersion:i.to??i.version,fromVersion:i.from,fromGit:i["from-git"],yes:i.yes}),r()})}function w95(e,t){e.command("downgrade <version>",`Downgrades Fern CLI version in ${JU}`,r=>r.positional("version",{type:"string",description:"The version to downgrade to",demandOption:!0}),async r=>{await p8h({cliContext:t,targetVersion:r.version})})}function E95(e,t){e.command("api update",`Pulls the latest OpenAPI spec from the specified origin in ${GM} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}),async r=>{await t.instrumentPostHogEvent({command:"fern api update"}),await HgE({cliContext:t,project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0})})})}function S95(e,t){e.command("self-update [version]","Updates the globally installed Fern CLI to the latest version or the specified version",r=>r.positional("version",{type:"string",description:"The version to update to (e.g., 0.85.0, 10). Defaults to latest."}).option("dry-run",{type:"boolean",description:"Show what would be executed without actually running the update",default:!1}),async r=>{await t.instrumentPostHogEvent({command:"fern self-update"}),await QgE({cliContext:t,version:r.version,dryRun:r.dryRun})})}function M95(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}),async r=>{await t.runTask(async i=>{await t.instrumentPostHogEvent({command:"fern login"}),await a5a(i,{useDeviceCodeFlow:r.deviceCode})})})}function D95(e,t){e.command("logout","Log out of Fern",r=>r,async()=>{await t.runTask(async r=>{await t.instrumentPostHogEvent({command:"fern logout"}),await zEc(r)})})}function B95(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern format"}),await m8h({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function I95(e,t){e.command("test",!1,r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(en.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{await t.instrumentPostHogEvent({command:"fern test"}),await UgE({cliContext:t,project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function C95(e,t){e.command("mock",!1,r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{await t.instrumentPostHogEvent({command:"fern mock"}),await SgE({cliContext:t,project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function q95(e,t){e.command("overrides","Commands for managing OpenAPI overrides",r=>(T95(r,t),R95(r,t),r))}function T95(e,t){e.command("compare <original> <modified>","Compare two OpenAPI specs and generate an overrides file from the differences.",r=>r.positional("original",{type:"string",description:"Path to the original OpenAPI spec",demandOption:!0}).positional("modified",{type:"string",description:"Path to the modified OpenAPI spec",demandOption:!0}).option("output",{type:"string",alias:"o",description:"Path to write the overrides file (defaults to <original>-overrides.yml)"}),async r=>{await t.instrumentPostHogEvent({command:"fern overrides compare"});let i=Uu(WA(),r.original),n=Uu(WA(),r.modified),a=r.output!=null?Uu(WA(),r.output):void 0;await pgE({originalPath:Sr.of(i),modifiedPath:Sr.of(n),outputPath:a!=null?Sr.of(a):void 0,cliContext:t})})}function R95(e,t){e.command("write","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{await t.instrumentPostHogEvent({command:"fern overrides write"}),await Scp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function z95(e,t){e.command("write-overrides",!1,r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{t.logger.warn("The 'write-overrides' command is deprecated. Use 'fern overrides write' instead."),await t.instrumentPostHogEvent({command:"fern write-overrides"}),await Scp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function N95(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(en.GenerationLanguage),description:"Write the definition for a particular SDK language"}).option("preserve-schemas",{string:!0,description:"Preserve potentially unsafe schema Ids in the generated fern definition"}),async r=>{let i=r.preserveSchemas!=null;await t.instrumentPostHogEvent({command:"fern write-definition"}),await L0E({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language,preserveSchemaIds:i}),cliContext:t,sdkLanguage:r.language,preserveSchemaIds:i})})}function F95(e,t){e.command("docs","Commands for managing your docs",r=>(V95(r,t),W95(r,t),Q95(r,t),r))}function Q95(e,t){e.command("preview","Commands for managing preview deployments",r=>(U95(r,t),L95(r,t),r))}function U95(e,t){e.command("list","List all preview deployments",r=>r.option("limit",{type:"number",description:"Maximum number of preview deployments to display"}).option("page",{type:"number",description:"Page number for pagination (starts at 1)"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview list"}),await e8h({cliContext:t,limit:r.limit,page:r.page})})}function L95(e,t){e.command("delete <url>","Delete a preview deployment",r=>r.positional("url",{type:"string",description:"The FQDN of the preview deployment to delete (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview delete"}),await k3h({cliContext:t,previewUrl:r.url})})}function V95(e,t){e.command("dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}).option("broken-links",{boolean:!0,default:!1,description:"Check for broken links in your docs"}).option("beta",{boolean:!0,default:!1,description:"Run the app router development server"}).option("legacy",{boolean:!0,default:!1,description:"Run the legacy development server"}).option("backend-port",{number:!0,description:"Run the development backend server on the following port"}).option("force-download",{boolean:!0,default:!1,description:"Force re-download of the docs preview bundle by deleting the cached bundle"}),async r=>{r.beta&&t.logger.warn("--beta flag now accesses the same functionality as default and will be deprecated in a future release");let i;r.port!=null?i=r.port:i=await rna({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]});let n;r.backendPort!=null?n=r.backendPort:n=await rna({port:[3001,3002,3003,3004,3005,3006,3007,3008,3009,3010,3011]});let a=r.bundlePath;await Z3h({loadProject:()=>jO(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:i,bundlePath:a,brokenLinks:r.brokenLinks,legacyPreview:r.legacy,backendPort:n,forceDownload:r.forceDownload})})}function W95(e,t){e.command("broken-links","Check for broken links in your docs",r=>r.option("strict",{boolean:!0,default:!1,description:"Fail with non-zero exit status"}),async r=>{let i=await jO(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await z0E({project:i,cliContext:t,errorOnBrokenLinks:r.strict})})}function G95(e,t){e.command("jsonschema <path-to-output>","Generate JSON Schema for a specific type",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).positional("path-to-output",{type:"string",description:"Path to write JSON Schema",demandOption:!0}).option("type",{string:!0,demandOption:!0,description:"The type to generate JSON Schema for (e.g. 'MySchema' or 'mypackage.MySchema')"}),async r=>{await t.instrumentPostHogEvent({command:"fern jsonschema",properties:{output:r.output}}),await AgE({typeLocator:r.type,project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),jsonschemaFilepath:Uu(WA(),r.pathToOutput),cliContext:t})})}function H95(e,t){e.command("write-docs-definition <output-path>",!1,r=>r.positional("output-path",{type:"string",description:"Path to write the docs definition",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern write-docs-definition",properties:{outputPath:r.outputPath}}),await G0E({project:await jO(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),outputPath:Uu(WA(),r.outputPath),cliContext:t})})}function x95(e,t){e.command("write-translation","Generate translation directories for each language defined in docs.yml",r=>r.option("stub",{alias:"s",type:"boolean",default:!1,description:"Return content as-is without calling the translation service"}),async r=>{await t.instrumentPostHogEvent({command:"fern write-translation"}),await cwE({project:await jO(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,stub:r.stub})})}function K95(e,t){e.command("export <output-path>","Export your API to an OpenAPI spec",r=>r.positional("output-path",{type:"string",description:"Path to write the OpenAPI spec",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern export",properties:{outputPath:r.outputPath}}),await A8h({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,outputPath:Uu(WA(),r.outputPath)})})}function J95(e,t){e.command("protoc-gen-fern",!1,r=>{},async()=>{let r=yUc,i=await $95(process.stdin),n=EFa(Rhp,i),a=r.run(n);await Y95(process.stdout,ZZs(aCo,a)),process.exit(0)})}function $95(e){return new Promise((t,r)=>{let i=[];e.on("data",n=>i.push(n)),e.on("end",()=>{t(new Uint8Array(Buffer.concat(i)))}),e.on("error",n=>{r(n)})})}function Y95(e,t){return new Promise((r,i)=>{e.write(t,n=>{n?i(n):r()})})}
2131
+ Version Bump: ${n.version_bump}`))})}function _95(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async i=>{await LgE({orgId:r.organization??(await jO(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:i})})})}function h95(e,t){e.command("add <generator>",`Add a code generator to ${GM}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{await S0h({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:r.generator,groupName:r.group,cliContext:t})})}function y95(e,t){e.command(["generate"],"Generate all generators in the specified group",r=>r.option("api",{string:!0,description:"If multiple APIs, specify the name with --api <name>. Otherwise, just --api."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("group",{type:"string",description:"The group to generate"}).option("mode",{choices:Object.values(egE),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally, using Docker"}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}).option("force",{boolean:!0,default:!1,description:"Ignore prompts to confirm generation, defaults to false"}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("disable-snippets",{boolean:!0,description:"Disable snippets in docs generation.",default:!1}).option("runner",{choices:["docker","podman"],description:"Choose the container runtime to use for local generation.",default:void 0}).option("lfs-override",{type:"string",hidden:!0,description:"Override output mode to local-file-system with the specified path"}).option("disable-dynamic-snippets",{boolean:!0,description:"Disable dynamic SDK snippets in docs generation",default:!1}).option("prompt",{boolean:!0,description:"Prompt for confirmation before generating (use --no-prompt to skip)",default:!0}).option("skip-upload",{boolean:!0,description:"Skip asset upload step and generate fake links for preview",default:!1}).option("fernignore",{type:"string",description:"Path to a custom .fernignore file to use instead of the one on the main branch (remote generation only)"}).option("dynamic-ir-only",{boolean:!0,description:"Only upload dynamic IR for specified version, skip SDK generation (remote generation only)",default:!1}),async r=>r.api!=null&&r.docs!=null?t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one."):r.skipUpload&&!r.preview?t.failWithoutThrowing("The --skip-upload flag can only be used with --preview."):r.skipUpload&&r.docs==null?t.failWithoutThrowing("The --skip-upload flag can only be used with --docs."):r.fernignore!=null&&(r.local||r.runner!=null)?t.failWithoutThrowing("The --fernignore flag is not supported with local generation (--local or --runner). It can only be used with remote generation."):r["dynamic-ir-only"]&&(r.local||r.runner!=null)?t.failWithoutThrowing("The --dynamic-ir-only flag is not supported with local generation (--local or --runner). It can only be used with remote generation."):r["dynamic-ir-only"]&&r.version==null?t.failWithoutThrowing("The --dynamic-ir-only flag requires a version to be specified with --version."):r["dynamic-ir-only"]&&r.docs!=null?t.failWithoutThrowing("The --dynamic-ir-only flag can only be used for API generation, not docs generation."):r.api!=null?await jcp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local||r.runner!=null,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,dynamicIrOnly:r["dynamic-ir-only"]}):r.docs!=null?(r.group!=null&&t.logger.warn("--group is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await rgE({project:await jO(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview,brokenLinks:r.brokenLinks,strictBrokenLinks:r.strictBrokenLinks,disableTemplates:r.disableSnippets,noPrompt:!r.prompt,skipUpload:r.skipUpload})):await jcp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,dynamicIrOnly:r["dynamic-ir-only"]}))}function b95(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(en.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}).option("disable-examples",{boolean:!0,description:"Whether to disable automatic example generation in the IR",default:!1}),async r=>{await sgE({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:Uu(WA(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,readme:void 0,directFromOpenapi:r.fromOpenapi,disableExamples:r.disableExamples})})}function v95(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(en.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await fgE({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:Uu(WA(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function g95(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(en.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("disable-examples",{boolean:!0,description:"Whether to suppress examples from being included in the IR"}),async r=>{await ngE({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:Uu(WA(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,disableDynamicExamples:r.disableExamples??!1})})}function O95(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the FDR API definition for certain audiences"}).option("v2",{boolean:!0,description:"Use v2 format"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{r.v2?await wcp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:Uu(WA(),r.pathToOutput),directFromOpenapi:!1,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):r.fromOpenapi?await wcp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:Uu(WA(),r.pathToOutput),directFromOpenapi:!0,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):await ogE({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:Uu(WA(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function A95(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>j8(a));await qgE({project:i,cliContext:t,token:n,version:r.version})})}function m95(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>j8(a));await TgE({project:i,cliContext:t,token:n})})}function P95(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("local",{boolean:!0,description:"Run validation locally without sending data to Fern API.",default:!1}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{await U0E({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,logWarnings:r.warnings,brokenLinks:r.brokenLinks,errorOnBrokenLinks:r.strictBrokenLinks,directFromOpenapi:r.fromOpenapi})})}function j95({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades Fern CLI version in ${JU}`,i=>i.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}).option("to",{string:!0,hidden:!0}).option("from",{string:!0,description:"The version to migrate from. Use this to manually run migrations when upgrading from an older CLI version."}).option("from-git",{boolean:!0,hidden:!0}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to migration prompts."}),async i=>{await R0E({cliContext:t,includePreReleases:i.rc,targetVersion:i.to??i.version,fromVersion:i.from,fromGit:i["from-git"],yes:i.yes}),r()})}function w95(e,t){e.command("downgrade <version>",`Downgrades Fern CLI version in ${JU}`,r=>r.positional("version",{type:"string",description:"The version to downgrade to",demandOption:!0}),async r=>{await p8h({cliContext:t,targetVersion:r.version})})}function E95(e,t){e.command("api update",`Pulls the latest OpenAPI spec from the specified origin in ${GM} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{await t.instrumentPostHogEvent({command:"fern api update"}),await HgE({cliContext:t,project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),indent:r.indent})})}function S95(e,t){e.command("self-update [version]","Updates the globally installed Fern CLI to the latest version or the specified version",r=>r.positional("version",{type:"string",description:"The version to update to (e.g., 0.85.0, 10). Defaults to latest."}).option("dry-run",{type:"boolean",description:"Show what would be executed without actually running the update",default:!1}),async r=>{await t.instrumentPostHogEvent({command:"fern self-update"}),await QgE({cliContext:t,version:r.version,dryRun:r.dryRun})})}function M95(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}),async r=>{await t.runTask(async i=>{await t.instrumentPostHogEvent({command:"fern login"}),await a5a(i,{useDeviceCodeFlow:r.deviceCode})})})}function D95(e,t){e.command("logout","Log out of Fern",r=>r,async()=>{await t.runTask(async r=>{await t.instrumentPostHogEvent({command:"fern logout"}),await zEc(r)})})}function B95(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern format"}),await m8h({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function I95(e,t){e.command("test",!1,r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(en.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{await t.instrumentPostHogEvent({command:"fern test"}),await UgE({cliContext:t,project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function C95(e,t){e.command("mock",!1,r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{await t.instrumentPostHogEvent({command:"fern mock"}),await SgE({cliContext:t,project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function q95(e,t){e.command("overrides","Commands for managing OpenAPI overrides",r=>(T95(r,t),R95(r,t),r))}function T95(e,t){e.command("compare <original> <modified>","Compare two OpenAPI specs and generate an overrides file from the differences.",r=>r.positional("original",{type:"string",description:"Path to the original OpenAPI spec",demandOption:!0}).positional("modified",{type:"string",description:"Path to the modified OpenAPI spec",demandOption:!0}).option("output",{type:"string",alias:"o",description:"Path to write the overrides file (defaults to <original>-overrides.yml)"}),async r=>{await t.instrumentPostHogEvent({command:"fern overrides compare"});let i=Uu(WA(),r.original),n=Uu(WA(),r.modified),a=r.output!=null?Uu(WA(),r.output):void 0;await pgE({originalPath:Sr.of(i),modifiedPath:Sr.of(n),outputPath:a!=null?Sr.of(a):void 0,cliContext:t})})}function R95(e,t){e.command("write","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{await t.instrumentPostHogEvent({command:"fern overrides write"}),await Scp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function z95(e,t){e.command("write-overrides",!1,r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{t.logger.warn("The 'write-overrides' command is deprecated. Use 'fern overrides write' instead."),await t.instrumentPostHogEvent({command:"fern write-overrides"}),await Scp({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function N95(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(en.GenerationLanguage),description:"Write the definition for a particular SDK language"}).option("preserve-schemas",{string:!0,description:"Preserve potentially unsafe schema Ids in the generated fern definition"}),async r=>{let i=r.preserveSchemas!=null;await t.instrumentPostHogEvent({command:"fern write-definition"}),await L0E({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language,preserveSchemaIds:i}),cliContext:t,sdkLanguage:r.language,preserveSchemaIds:i})})}function F95(e,t){e.command("docs","Commands for managing your docs",r=>(V95(r,t),W95(r,t),Q95(r,t),r))}function Q95(e,t){e.command("preview","Commands for managing preview deployments",r=>(U95(r,t),L95(r,t),r))}function U95(e,t){e.command("list","List all preview deployments",r=>r.option("limit",{type:"number",description:"Maximum number of preview deployments to display"}).option("page",{type:"number",description:"Page number for pagination (starts at 1)"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview list"}),await e8h({cliContext:t,limit:r.limit,page:r.page})})}function L95(e,t){e.command("delete <url>","Delete a preview deployment",r=>r.positional("url",{type:"string",description:"The FQDN of the preview deployment to delete (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview delete"}),await k3h({cliContext:t,previewUrl:r.url})})}function V95(e,t){e.command("dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}).option("broken-links",{boolean:!0,default:!1,description:"Check for broken links in your docs"}).option("beta",{boolean:!0,default:!1,description:"Run the app router development server"}).option("legacy",{boolean:!0,default:!1,description:"Run the legacy development server"}).option("backend-port",{number:!0,description:"Run the development backend server on the following port"}).option("force-download",{boolean:!0,default:!1,description:"Force re-download of the docs preview bundle by deleting the cached bundle"}),async r=>{r.beta&&t.logger.warn("--beta flag now accesses the same functionality as default and will be deprecated in a future release");let i;r.port!=null?i=r.port:i=await rna({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]});let n;r.backendPort!=null?n=r.backendPort:n=await rna({port:[3001,3002,3003,3004,3005,3006,3007,3008,3009,3010,3011]});let a=r.bundlePath;await Z3h({loadProject:()=>jO(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:i,bundlePath:a,brokenLinks:r.brokenLinks,legacyPreview:r.legacy,backendPort:n,forceDownload:r.forceDownload})})}function W95(e,t){e.command("broken-links","Check for broken links in your docs",r=>r.option("strict",{boolean:!0,default:!1,description:"Fail with non-zero exit status"}),async r=>{let i=await jO(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await z0E({project:i,cliContext:t,errorOnBrokenLinks:r.strict})})}function G95(e,t){e.command("jsonschema <path-to-output>","Generate JSON Schema for a specific type",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).positional("path-to-output",{type:"string",description:"Path to write JSON Schema",demandOption:!0}).option("type",{string:!0,demandOption:!0,description:"The type to generate JSON Schema for (e.g. 'MySchema' or 'mypackage.MySchema')"}),async r=>{await t.instrumentPostHogEvent({command:"fern jsonschema",properties:{output:r.output}}),await AgE({typeLocator:r.type,project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),jsonschemaFilepath:Uu(WA(),r.pathToOutput),cliContext:t})})}function H95(e,t){e.command("write-docs-definition <output-path>",!1,r=>r.positional("output-path",{type:"string",description:"Path to write the docs definition",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern write-docs-definition",properties:{outputPath:r.outputPath}}),await G0E({project:await jO(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),outputPath:Uu(WA(),r.outputPath),cliContext:t})})}function x95(e,t){e.command("write-translation","Generate translation directories for each language defined in docs.yml",r=>r.option("stub",{alias:"s",type:"boolean",default:!1,description:"Return content as-is without calling the translation service"}),async r=>{await t.instrumentPostHogEvent({command:"fern write-translation"}),await cwE({project:await jO(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,stub:r.stub})})}function K95(e,t){e.command("export <output-path>","Export your API to an OpenAPI spec",r=>r.positional("output-path",{type:"string",description:"Path to write the OpenAPI spec",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{await t.instrumentPostHogEvent({command:"fern export",properties:{outputPath:r.outputPath}}),await A8h({project:await jO(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,outputPath:Uu(WA(),r.outputPath),indent:r.indent})})}function J95(e,t){e.command("protoc-gen-fern",!1,r=>{},async()=>{let r=yUc,i=await $95(process.stdin),n=EFa(Rhp,i),a=r.run(n);await Y95(process.stdout,ZZs(aCo,a)),process.exit(0)})}function $95(e){return new Promise((t,r)=>{let i=[];e.on("data",n=>i.push(n)),e.on("end",()=>{t(new Uint8Array(Buffer.concat(i)))}),e.on("error",n=>{r(n)})})}function Y95(e,t){return new Promise((r,i)=>{e.write(t,n=>{n?i(n):r()})})}
2132
2132
  /*! Bundled license information:
2133
2133
 
2134
2134
  tmp/lib/tmp.js: