fern-api 0.94.0 → 0.94.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +3 -3
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -2163,7 +2163,7 @@ ${XOy.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&Fvf(th
2163
2163
  `+sca.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?sca.default.cyan(oAy(t,this.opt.mask)):sca.default.italic(sca.default.dim("[hidden]")):this.opt.mask?oAy(t,this.opt.mask):sca.default.italic(sca.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 nSs=fa(gse(),1);var oPy=fa(bbf(),1),tSs=require("child_process"),Bka=require("fs"),eSs=fa(require("path"),1),uPy=fa(require("os"),1),sPy=require("crypto"),rgf=fa(iPy(),1);var XEs=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var bKo=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var ZEs=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var kEs=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function rSs(e="",t,r){let n=new ngf(e,r);n.runAsync((i,a)=>{if(i)setImmediate(t,i,void 0);else try{n.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function aPy(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function daC(e){let t=[],r="";for(let n=0;n<e.length;n++){let i=e.charAt(n);n>0&&i===" "&&e[n-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${i}`}return r.length>0&&t.push(r),t}var ngf=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=daC(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??uPy.default.tmpdir(),r=(0,sPy.randomUUID)(),n=aPy(this.fileOptions.prefix),i=aPy(this.fileOptions.postfix),a=`${n}${r}${i}`,o=eSs.default.resolve(t,a),c=eSs.default.resolve(t)+eSs.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,Bka.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new XEs(t)}}readTemporaryFile(){try{let t=(0,Bka.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,oPy.detect)(t)??"utf8";rgf.default.encodingExists(r)||(r="utf8"),this.text=rgf.default.decode(t,r)}}catch(t){throw new ZEs(t)}}removeTemporaryFile(){try{(0,Bka.unlinkSync)(this.tempFile)}catch(t){throw new kEs(t)}}launchEditor(){try{let t=(0,tSs.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new bKo(t)}}launchEditorAsync(t){try{(0,tSs.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new bKo(r)}}};var cPy=fa(Gnt(),1);var gKo=class extends mse{_run(t){this.done=t,this.editorResult=new cPy.Subject;let r=Jbe(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let n=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,i=this.handleSubmitEvents(this.editorResult);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,n?this.render():this.startExternalEditor(),this}render(t){let r="",n=this.getQuestion();n+=this.status==="answered"?nSs.default.dim("Received"):nSs.default.dim("Press <enter> to launch your preferred editor."),t&&(r=nSs.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),rSs(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 _Py=require("stream");var dPy=fa(require("readline"),1),pPy=fa(fPy(),1),dca=class{constructor(t){this.rl||=dPy.default.createInterface(_aC(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 _aC(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let i=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw i.isTtyError=!0,i}let r=new pPy.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var mKo=class extends dca{constructor(t={}){super(t),this.log=new _Py.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return nKo(this.rl,this.bottomBar.split(`
2164
2164
  `).length),this}updateBottomBar(t){return nKo(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+`
2165
2165
  `}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&&jEs(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var e6=fa(Gnt(),1),vPy=fa(wJo(),1);var iSs=fa(Gnt(),1),hPy=fa(wJo(),1),aSs=function(e,t,r){return typeof e[t]!="function"?(0,iSs.of)(e):(0,iSs.from)((0,hPy.default)(e[t])(r).then(n=>(e[t]=n,e)))};var yPy={set:(e,t="",r)=>{let n=e;t.split(".").forEach((i,a,o)=>{i==="__proto__"||i==="constructor"||(a===o.length-1?n[i]=r:(!(i in n)||typeof n[i]!="object")&&(n[i]={}),n=n[i])})},get:(e,t="",r)=>{let n=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((o,c)=>o!=null?o[c]:o,e),i=n(/[,[\]]+?/)||n(/[,.[\]]+?/);return i===void 0||i===e?r:i}},Tka=class extends dca{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let n;return Array.isArray(t)?n=(0,e6.from)(t):(0,e6.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,e6.from)(Object.entries(t).map(([i,a])=>({name:i,...a}))):n=(0,e6.from)([t]),this.process=n.pipe((0,e6.concatMap)(this.processQuestion.bind(this)),(0,e6.publish)()),this.process.connect(),this.process.pipe((0,e6.reduce)((i,a)=>(yPy.set(i,a.name,a.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,e6.defer)(()=>(0,e6.of)(t).pipe((0,e6.concatMap)(this.setDefaultType.bind(this)),(0,e6.concatMap)(this.filterIfRunnable.bind(this)),(0,e6.concatMap)(()=>aSs(t,"message",this.answers)),(0,e6.concatMap)(()=>aSs(t,"default",this.answers)),(0,e6.concatMap)(()=>aSs(t,"choices",this.answers)),(0,e6.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,e6.defer)(()=>(0,e6.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,e6.defer)(()=>(0,e6.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&yPy.get(this.answers,t.name)!==void 0)return e6.EMPTY;if(t.when===!1)return e6.EMPTY;if(typeof t.when!="function")return(0,e6.of)(t);let{answers:r}=this;return(0,e6.defer)(()=>(0,e6.from)((0,vPy.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,e6.filter)(n=>n!=null)))}};function bPy(e){let t=function(r,n){let i;try{i=new Tka(t.prompts,e)}catch(o){return Promise.reject(o)}let a=i.run(r,n);return a.ui=i,a};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",aKo),this.registerPrompt("input",uca),this.registerPrompt("number",oKo),this.registerPrompt("confirm",uKo),this.registerPrompt("rawlist",sKo),this.registerPrompt("expand",cKo),this.registerPrompt("checkbox",lKo),this.registerPrompt("password",fKo),this.registerPrompt("editor",gKo)},t.restoreDefaultPrompts(),t}var agf=bPy();function yaC(e,t){agf.registerPrompt(e,t)}function vaC(){agf.restoreDefaultPrompts()}var baC={prompt:agf,ui:{BottomBar:mKo,Prompt:Tka},createPromptModule:bPy,registerPrompt:yaC,restoreDefaultPrompts:vaC,Separator:Yxe},oSs=baC;var Gka=require("path"),ijy=require("fs"),ajy=require("readline"),Cwy="posthog-node";function asC(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"]}={}){return a=>{if(!(i==="*"||i.includes(a.level)))return a;a.tags||(a.tags={});let c=a.tags[CSs.POSTHOG_ID_TAG];if(c===void 0)return a;let d=e.options.host??"https://us.i.posthog.com",s=new URL(`/project/${e.apiKey}/person/${c}`,d).toString();a.tags["PostHog Person URL"]=s;let u=a.exception?.values||[],l=u.map(A=>({...A,stacktrace:A.stacktrace?{...A.stacktrace,type:"raw",frames:(A.stacktrace.frames||[]).map(P=>({...P,platform:"node:javascript"}))}:void 0})),m={$exception_message:u[0]?.value||a.message,$exception_type:u[0]?.type,$exception_personURL:s,$exception_level:a.level,$exception_list:l,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:u[0]?.value||a.message,$sentry_exception_type:u[0]?.type,$sentry_tags:a.tags};return t&&r&&(m.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:c,properties:m}),a}}var CSs=class{constructor(t,r,n,i){this.name=Cwy,this.name=Cwy,this.setupOnce=function(a,o){let c=o()?.getClient()?.getDsn()?.projectId;a(asC(t,{organization:r,projectId:c,prefix:n,severityAllowList:i}))}}};CSs.POSTHOG_ID_TAG="posthog_distinct_id";var wSs="0123456789abcdef",ISs=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||t<0||r<0||n<0||i<0||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");let 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/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|n>>>24,a[9]=n>>>16,a[10]=n>>>8,a[11]=n,a[12]=i>>>24,a[13]=i>>>16,a[14]=i>>>8,a[15]=i,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}if(r){let n=new Uint8Array(16);for(let i=0;i<16;i+=4){let a=parseInt(r.substring(2*i,2*i+8),16);n[i+0]=a>>>24,n[i+1]=a>>>16,n[i+2]=a>>>8,n[i+3]=a}return new e(n)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=wSs.charAt(this.bytes[r]>>>4),t+=wSs.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=wSs.charAt(this.bytes[r]>>>4),t+=wSs.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},Jgf=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??osC()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let n=this.generateOrAbortCore(t,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(t,r)),n}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return ISs.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}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,ISs.ofInner(t)}},osC=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),Iwy,Kgf=()=>usC().toString(),usC=()=>(Iwy||(Iwy=new Jgf)).generate();function ssC(e,t){let r=!1;return Object.assign(n=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t())},{_posthogErrorHandler:!0})}function csC(e,t){global.process.on("uncaughtException",ssC(e,t))}function lsC(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var jSs,Mwy,ESs;function fsC(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return ESs&&r.length===Mwy||(Mwy=r.length,ESs=r.reduce((n,i)=>{jSs||(jSs={});let a=jSs[i];if(a)n[a[0]]=a[1];else{let o=e(i);for(let c=o.length-1;c>=0;c--){let s=o[c]?.filename,u=t[i];if(s&&u){n[s]=u,jSs[i]=[s,u];break}}}return n},{})),ESs}function dsC(e){return typeof Event<"u"&&ojy(e,Event)}function psC(e){return ujy(e,"Object")}function r0f(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return ojy(e,Error)}}function ojy(e,t){try{return e instanceof t}catch{return!1}}function _sC(e){return ujy(e,"ErrorEvent")}function ujy(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function hsC(e,t,r,n){let a=n&&n.mechanism||{handled:!0,type:"generic"},o=sjy(a,r,n);return{$exception_list:await Promise.all(o.map(async s=>{let u=await AsC(e,t,s);return u.value=u.value||"",u.type=u.type||"Error",u.mechanism=a,u}))}}function sjy(e,t,r){let n=ysC(e,t,r);return n.cause?[n,...sjy(e,n.cause,r)]:[n]}function ysC(e,t,r){if(r0f(t))return t;if(e.synthetic=!0,psC(t)){let i=vsC(t);if(i)return i;let a=bsC(t),o=r?.syntheticException||new Error(a);return o.message=a,o}let n=r?.syntheticException||new Error(t);return n.message=`${t}`,n}function vsC(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(r0f(r))return r}}function bsC(e){if("name"in e&&typeof e.name=="string"){let n=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(n+=` with message '${e.message}'`),n}else if("message"in e&&typeof e.message=="string")return e.message;let t=msC(e);if(_sC(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=gsC(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function gsC(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function msC(e,t=40){let r=Object.keys(OsC(e));r.sort();let n=r[0];if(!n)return"[object has no keys]";if(n.length>=t)return Bwy(n,t);for(let i=r.length;i>0;i--){let a=r.slice(0,i).join(", ");if(!(a.length>t))return i===r.length?a:Bwy(a,t)}return""}function Bwy(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function OsC(e){return r0f(e)?{message:e.message,name:e.name,stack:e.stack,...Twy(e)}:dsC(e)?{type:e.type,target:qwy(e.target),currentTarget:qwy(e.currentTarget),...Twy(e)}:e}function Twy(e){if(typeof e=="object"&&e!==null){let t={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}else return{}}function qwy(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function AsC(e,t,r){let n={type:r.name||r.constructor.name,value:r.message},i=PsC(e,r);for(let a of t)i=await a(i);return i.length&&(n.stacktrace={frames:i,type:"raw"}),n}function PsC(e,t){return wsC(e(t.stack||"",1),e)}function wsC(e,t){let r=fsC(t);return e.forEach(n=>{n.filename&&(n.chunk_id=r[n.filename])}),e}var jsC=2e3,Vka=class e{static async captureException(t,r,n,i,a){let o={...a};i||(o.$process_person_profile=!1);let c=await hsC(this.stackParser,this.frameModifiers,r,n);t.capture({event:"$exception",distinctId:i||Kgf(),properties:{...c,...o}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(csC(this.onException.bind(this),this.onFatalError.bind(this)),lsC(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(jsC)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function EsC(e=process.argv[1]?(0,Gka.dirname)(process.argv[1]):process.cwd(),t=Gka.sep==="\\"){let r=t?Rwy(e):e;return n=>{if(!n)return;let i=t?Rwy(n):n,{dir:a,base:o,ext:c}=Gka.posix.parse(i);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,c.length*-1));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 Rwy(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var MSs=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)}}},DSs=new MSs(25),cjy=new MSs(20),n0f=7,SsC=1e3,DsC=1e4;async function CsC(e){let t={};for(let i=e.length-1;i>=0;i--){let a=e[i],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||TsC(o)||qsC(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(cjy.get(i))continue;let a=t[i];if(!a)continue;a.sort((d,s)=>d-s);let o=NsC(a);if(o.every(d=>RsC(i,d)))continue;let c=FsC(DSs,i,{});n.push(IsC(i,o,c))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&MsC(e,DSs),DSs.reduce(),e}function IsC(e,t,r){return new Promise(n=>{let i=(0,ijy.createReadStream)(e),a=(0,ajy.createInterface)({input:i});function o(){i.destroy(),n()}let c=0,d=0,s=t[d];if(s===void 0){o();return}let u=s[0],l=s[1];function m(){cjy.set(e,1),a.close(),a.removeAllListeners(),o()}i.on("error",m),a.on("error",m),a.on("close",o),a.on("line",A=>{if(c++,!(c<u)&&(r[c]=xsC(A,0),c>=l)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let P=t[d];if(P===void 0){a.close(),a.removeAllListeners();return}u=P[0],l=P[1]}})})}function MsC(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;BsC(r.lineno,r,n)}}function BsC(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=ljy(e);i<e;i++){let a=r[i];if(a===void 0){Nwy(t);return}t.pre_context.push(a)}if(r[e]===void 0){Nwy(t);return}t.context_line=r[e];let n=fjy(e);t.post_context=[];for(let i=e+1;i<=n;i++){let a=r[i];if(a===void 0)break;t.post_context.push(a)}}function Nwy(e){delete e.pre_context,delete e.context_line,delete e.post_context}function TsC(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function qsC(e){return e.lineno!==void 0&&e.lineno>DsC||e.colno!==void 0&&e.colno>SsC}function RsC(e,t){let r=DSs.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function NsC(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=Fwy(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let a=e[t+1];if(typeof a!="number")break;a<=n[1]?n[1]=a+n0f:(i.push(n),n=Fwy(a)),t++}return i}function Fwy(e){return[ljy(e),fjy(e)]}function ljy(e){return Math.max(1,e-n0f)}function fjy(e){return e+n0f}function FsC(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function xsC(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let a=Math.min(i+140,n);return a>n-5&&(a=n),a===n&&(i=Math.max(a-140,0)),r=r.slice(i,a),i>0&&(r=`...${r}`),a<n&&(r+="..."),r}var zsC="4.18.0",t3e;(function(e){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.DecideEndpointWasHit="decide_endpoint_was_hit",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config"})(t3e||(t3e={}));var xwy;(function(e){e.Left="left",e.Right="right",e.Center="center"})(xwy||(xwy={}));var zwy;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(zwy||(zwy={}));var Qwy;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(Qwy||(Qwy={}));var Lwy;(function(e){e.Html="html",e.Text="text"})(Lwy||(Lwy={}));var Uwy;(function(e){e.Number="number",e.Emoji="emoji"})(Uwy||(Uwy={}));var Vwy;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(Vwy||(Vwy={}));var Wwy;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(Wwy||(Wwy={}));var Hwy;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(Hwy||(Hwy={}));var Gwy;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(Gwy||(Gwy={}));var QsC=e=>{if("flags"in e){let t=UsC(e.flags),r=VsC(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,a])=>[i,djy(a)])),n=Object.fromEntries(Object.entries(t).map(([i,a])=>[i,LsC(i,a,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function LsC(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 UsC=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,i0f(r)]).filter(([,t])=>t!==void 0)),VsC=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?djy(n):void 0]}))},i0f=e=>e===void 0?void 0:e.variant??e.enabled,djy=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},WsC=1,HsC=new Set(["61be3dd8","96f6df5f","8cfdba9b","bf027177","e59430a8","7fa5500b","569798e9","04809ff7","0ebc61a5","32de7f98","3beeb69a","12d34ad9","733853ec","0645bb64","5dcbee21","b1f95fa3","2189e408","82b460c2","3a8cc979","29ef8843","2cdbf767","38084b54","50f9f8de","41d0df91","5c236689","c11aedd3","ada46672","f4331ee1","42fed62a","c957462c","d62f705a","e0162666","01b3e5cf","441cef7f","bb9cafee","8f348eb0","b2553f3a","97469d7d","39f21a76","03706dcc","27d50569","307584a7","6433e92e","150c7fbb","49f57f22","3772f65b","01eb8256","3c9e9234","f853c7f7","c0ac4b67","cd609d40","10ca9b1a","8a87f11b","8e8e5216","1f6b63b3","db7943dd","79b7164c","07f78e33","2d21b6fd","952db5ee","a7d3b43f","1924dd9c","84e1b8f6","dff631b6","c5aa8a79","fa133a95","498a4508","24748755","98f3d658","21bbda67","7dbfed69","be3ec24c","fc80b8e2","75cc0998"]),GsC="utf8";function JsC(e,t){if(!e||typeof e!="string"||KsC(e))throw new Error(t)}function KsC(e){return e.trim().length===0}function $sC(e){return e?.replace(/\/+$/,"")}async function YsC(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){n>0&&await new Promise(i=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function Jwy(){return new Date().getTime()}function Hgf(){return new Date().toISOString()}function BSs(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function XsC(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function ZsC(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return(t>>>0).toString(16).padStart(8,"0")}function ksC(e,t=0,r){let n=ZsC(e);return r?.has(n)?!1:parseInt(n,16)/4294967295<t}function Kwy(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var IKo=String.fromCharCode,$wy="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",SSs={};function ecC(e,t){if(!SSs[e]){SSs[e]={};for(let r=0;r<e.length;r++)SSs[e][e.charAt(r)]=r}return SSs[e][t]}var Lka={compressToBase64:function(e){if(e==null)return"";let t=Lka._compress(e,6,function(r){return $wy.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:Lka._decompress(e.length,32,function(t){return ecC($wy,e.charAt(t))})},compress:function(e){return Lka._compress(e,16,function(t){return IKo(t)})},_compress:function(e,t,r){if(e==null)return"";let n={},i={},a=[],o,c,d="",s="",u="",l=2,m=3,A=2,P=0,C=0,M;for(M=0;M<e.length;M+=1)if(d=e.charAt(M),Object.prototype.hasOwnProperty.call(n,d)||(n[d]=m++,i[d]=!0),s=u+d,Object.prototype.hasOwnProperty.call(n,s))u=s;else{if(Object.prototype.hasOwnProperty.call(i,u)){if(u.charCodeAt(0)<256){for(o=0;o<A;o++)P=P<<1,C==t-1?(C=0,a.push(r(P)),P=0):C++;for(c=u.charCodeAt(0),o=0;o<8;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}else{for(c=1,o=0;o<A;o++)P=P<<1|c,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=0;for(c=u.charCodeAt(0),o=0;o<16;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}l--,l==0&&(l=Math.pow(2,A),A++),delete i[u]}else for(c=n[u],o=0;o<A;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1;l--,l==0&&(l=Math.pow(2,A),A++),n[s]=m++,u=String(d)}if(u!==""){if(Object.prototype.hasOwnProperty.call(i,u)){if(u.charCodeAt(0)<256){for(o=0;o<A;o++)P=P<<1,C==t-1?(C=0,a.push(r(P)),P=0):C++;for(c=u.charCodeAt(0),o=0;o<8;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}else{for(c=1,o=0;o<A;o++)P=P<<1|c,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=0;for(c=u.charCodeAt(0),o=0;o<16;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}l--,l==0&&(l=Math.pow(2,A),A++),delete i[u]}else for(c=n[u],o=0;o<A;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1;l--,l==0&&(l=Math.pow(2,A),A++)}for(c=2,o=0;o<A;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1;for(;;)if(P=P<<1,C==t-1){a.push(r(P));break}else C++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:Lka._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let n=[],i=[],a={val:r(0),position:t,index:1},o=4,c=4,d=3,s="",u,l,m,A,P,C,M;for(u=0;u<3;u+=1)n[u]=u;for(m=0,P=Math.pow(2,2),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;switch(m){case 0:for(m=0,P=Math.pow(2,8),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;M=IKo(m);break;case 1:for(m=0,P=Math.pow(2,16),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;M=IKo(m);break;case 2:return""}for(n[3]=M,l=M,i.push(M);;){if(a.index>e)return"";for(m=0,P=Math.pow(2,d),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;switch(M=m){case 0:for(m=0,P=Math.pow(2,8),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;n[c++]=IKo(m),M=c-1,o--;break;case 1:for(m=0,P=Math.pow(2,16),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;n[c++]=IKo(m),M=c-1,o--;break;case 2:return i.join("")}if(o==0&&(o=Math.pow(2,d),d++),n[M])s=n[M];else if(M===c)s=l+l.charAt(0);else return null;i.push(s),n[c++]=l+s.charAt(0),o--,l=s,o==0&&(o=Math.pow(2,d),d++)}}},$gf=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}},Wka=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()}},MKo=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function Ywy(e){if(e instanceof Wka){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 Ggf(e){return typeof e=="object"&&(e instanceof Wka||e instanceof MKo)}function Xwy(e){return typeof e=="object"&&e instanceof Wka&&e.status===413}var Ygf;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(Ygf||(Ygf={}));var Xgf=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new $gf,this._isInitialized=!1,JsC(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=$sC(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.captureMode=r?.captureMode||"json",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:Ggf},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._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(t3e.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(t3e.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(t3e.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>console.log("PostHog Debug",n,i));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){let r=Kgf();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",a,i)})}async captureStatelessImmediate(t,r,n,i){let a=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",a,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",a,i)})}async aliasStatelessImmediate(t,r,n,i){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,i)}groupIdentifyStateless(t,r,n,i,a,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...o||{}}});this.enqueue("capture",c,i)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).catch(i=>{this.logMsgIfDebug(()=>console.error("Remote config could not be loaded",i)),this._events.emit("error",i)})}async getDecide(t,r={},n={},i={},a={}){await this._initPromise;let c=ksC(this.apiKey,WsC,HsC)?`${this.host}/flags/?v=2`:`${this.host}/decide/?v=4`,d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...a})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Decide URL",c)),this.fetchWithRetry(c,d,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>QsC(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,n={},i={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,n,i,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let d=i0f(c.response);return d===void 0&&(d=!1),{response:d,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,n,i,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId}}async getFeatureFlagPayloadStateless(t,r,n={},i={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,n,i,a,o,[t]);if(!c)return;let d=c[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a,o)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,n,i,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={},n={},i={},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.getDecide(t,r,n,i,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(Ygf.FeatureFlags)?(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.logMsgIfDebug(()=>console.log("PostHog Debug","Loading surveys is disabled.")),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this.logMsgIfDebug(()=>console.error(c)),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",a)),this._events.emit("error",a)}))?.surveys;return i&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(i))),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(t3e.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(t3e.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(t3e.Props,this.props)})}enqueue(t,r,n){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let i=this.prepareMessage(t,r,n),a=this.getPersistedProperty(t3e.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),a.push({message:i}),this.setPersistedProperty(t3e.Queue,a),this._events.emit(t,i),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=BSs(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized||await this._initPromise,this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let i={api_key:this.apiKey,batch:[this.prepareMessage(t,r,n)],sent_at:Hgf()};this.historicalMigration&&(i.historical_migration=!0);let a=JSON.stringify(i),o=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${Jwy()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,c=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(Lka.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(o,c)}catch(d){this._events.emit("error",d)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:Hgf(),uuid:n?.uuid?n.uuid:Kgf()};return(n?.disableGeoip??this.disableGeoip)&&(i.properties||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await Ywy(t)})}async flush(){let t=Kwy([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),Kwy([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(t3e.Queue)||[];if(!t.length)return;let r=[],n=t.length;for(;t.length>0&&r.length<n;){let i=t.slice(0,this.maxBatchSize),a=i.map(m=>m.message),o=()=>{let A=(this.getPersistedProperty(t3e.Queue)||[]).slice(i.length);this.setPersistedProperty(t3e.Queue,A),t=A},c={api_key:this.apiKey,batch:a,sent_at:Hgf()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${Jwy()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,u=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(Lka.compressToBase64(d))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:d},l={retryCheck:m=>Xwy(m)?!1:Ggf(m)};try{await this.fetchWithRetry(s,u,l)}catch(m){if(Xwy(m)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`));continue}throw m instanceof MKo||o(),this._events.emit("error",m),m}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,n,i){var a;(a=AbortSignal).timeout??(a.timeout=function(s){let u=new AbortController;return setTimeout(()=>u.abort(),s),u.signal});let o=r.body?r.body:"",c=-1;try{c=Buffer.byteLength(o,GsC)}catch{c=new TextEncoder().encode(o).length}return await YsC(async()=>{let d=null;try{d=await this.fetch(t,{signal:AbortSignal.timeout(i??this.requestTimeout),...r})}catch(u){throw new MKo(u)}if(!(r.mode==="no-cors")&&(d.status<200||d.status>=400))throw new Wka(d,c);return d},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let n=async()=>{try{for(await Promise.all(Object.values(this.pendingPromises));!((this.getPersistedProperty(t3e.Queue)||[]).length===0||(await this.flush(),r)););}catch(i){if(!Ggf(i))throw i;await Ywy(i)}};return Promise.race([new Promise((i,a)=>{BSs(()=>{this.logMsgIfDebug(()=>console.error("Timed out while shutting down PostHog")),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),n()])}async shutdown(t=3e4){return this.shutdownPromise?this.logMsgIfDebug(()=>console.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}},Zgf=XsC();if(!Zgf){let e=Dwy();Zgf=async(t,r)=>{let n=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:n.status,text:async()=>n.data,json:async()=>n.data}}}var pjy=Zgf,TSs=class{constructor(t){this.factory=t}async getValue(){return this.value!==void 0?this.value:(this.initializationPromise===void 0&&(this.initializationPromise=(async()=>{try{let t=await this.factory();return this.value=t,t}finally{this.initializationPromise=void 0}})()),this.initializationPromise)}isInitialized(){return this.value!==void 0}async waitForInitialization(){this.isInitialized()||await this.getValue()}},_jy=new TSs(async()=>{try{return await import("crypto")}catch{return}});async function tcC(){return await _jy.getValue()}var rcC=new TSs(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await _jy.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function ncC(){return await rcC.getValue()}async function icC(e){let t=await tcC();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await ncC();if(r){let n=await r.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}throw new Error("No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API")}var acC=60*1e3,ocC=1152921504606847e3,ucC=["is_not"],Uka=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Ose=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},kgf=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,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=i,this.projectApiKey=n,this.host=a,this.poller=void 0,this.fetch=c.fetch||pjy,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,n={},i={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;for(let d of this.featureFlags)if(t===d.key){c=d;break}if(c!==void 0)try{o=await this.computeFlagLocally(c,r,n,i,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof Ose?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let n;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),n==null)return null;try{return JSON.parse(n)}catch{return n}}}async getAllFlagsAndPayloads(t,r={},n={},i={}){await this.loadFeatureFlags();let a={},o={},c=this.featureFlags.length==0;return await Promise.all(this.featureFlags.map(async d=>{try{let s=await this.computeFlagLocally(d,t,r,n,i);a[d.key]=s;let u=await this.computeFeatureFlagPayloadLocally(d.key,s);u&&(o[d.key]=u)}catch(s){s instanceof Ose||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),c=!0}})),{response:a,payloads:o,fallbackToDecide:c}}async computeFlagLocally(t,r,n={},i={},a={}){if(t.ensure_experience_continuity)throw new Ose("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let d=this.groupTypeMapping[String(c)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Ose("Flag has unknown group type index");if(!(d in n))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return await this.matchFeatureFlagProperties(t,n[d],s)}else return await this.matchFeatureFlagProperties(t,r,i)}async matchFeatureFlagProperties(t,r,n){let i=t.filters||{},a=i.groups||[],o=!1,c,d=[...a].sort((s,u)=>{let l=!!s.variant,m=!!u.variant;return l&&m?0:l?-1:m?1:0});for(let s of d)try{if(await this.isConditionMatch(t,r,s,n)){let u=s.variant,l=i.multivariate?.variants||[];u&&l.some(m=>m.key===u)?c=u:c=await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof Ose)o=!0;else throw u}if(c!==void 0)return c;if(o)throw new Ose("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i){let a=n.rollout_percentage,o=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let d=c.type,s=!1;if(d==="cohort"?s=yjy(c,i,this.cohorts,this.debugMode):s=hjy(c,i,o),!s)return!1}if(a==null)return!0}return!(a!=null&&await Zwy(t.key,r)>a/100)}async getMatchingVariant(t,r){let n=await Zwy(t.key,r,"variant"),i=this.variantLookupTable(t).find(a=>n>=a.valueMin&&n<a.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{i=n+c.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:c.key}),n=i}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(acC,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.getPollingInterval());try{let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new Uka(`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 Uka(`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 Uka(`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 r=await t.json()??{};if(!("flags"in r)){this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));return}this.featureFlags=r.flags??[],this.featureFlagsByKey=this.featureFlags.reduce((n,i)=>(n[i.key]=i,n),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||{},this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof Uka&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET"){return{method:t,headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions(),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=BSs(()=>{i.abort()},this.timeout),r.signal=i.signal}try{return await this.fetch(t,r)}finally{clearTimeout(n)}}stopPoller(){clearTimeout(this.poller)}_requestRemoteConfigPayload(t){let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config/`,n=this.getPersonalApiKeyRequestOptions(),i=null;if(this.timeout&&typeof this.timeout=="number"){let a=new AbortController;i=BSs(()=>{a.abort()},this.timeout),n.signal=a.signal}try{return this.fetch(r,n)}finally{clearTimeout(i)}}};async function Zwy(e,t,r=""){let n=await icC(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/ocC}function hjy(e,t,r){let n=e.key,i=e.value,a=e.operator||"exact";if(n in t){if(a==="is_not_set")throw new Ose("Operator is_not_set is not supported")}else throw new Ose(`Property ${n} not found in propertyValues`);let o=t[n];if(o==null&&!ucC.includes(a))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(l=>String(l).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,l){if(l==="gt")return s>u;if(l==="gte")return s>=u;if(l==="lt")return s<u;if(l==="lte")return s<=u;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return c(i,o);case"is_not":return!c(i,o);case"is_set":return n in t;case"icontains":return String(o).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(i).toLowerCase());case"regex":return kwy(String(i))&&String(o).match(String(i))!==null;case"not_regex":return kwy(String(i))&&String(o).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof i=="number"?i:null;if(typeof i=="string")try{s=parseFloat(i)}catch{}return s!=null&&o!=null?typeof o=="string"?d(o,String(i),a):d(o,s,a):d(String(o),String(i),a)}case"is_date_after":case"is_date_before":{let s=scC(String(i));if(s==null&&(s=ejy(i)),s==null)throw new Ose(`Invalid date: ${i}`);let u=ejy(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new Ose(`Unknown operator: ${a}`)}}function yjy(e,t,r,n=!1){let i=String(e.value);if(!(i in r))throw new Ose("can't match cohort without a given cohort property value");let a=r[i];return vjy(a,t,r,n)}function vjy(e,t,r,n=!1){if(!e)return!0;let i=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=vjy(c,t,r,n);if(i==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Ose)n&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new Ose("Can't match cohort without a given cohort property value");return i==="AND"}else{for(let c of a)try{let d;c.type==="cohort"?d=yjy(c,t,r,n):d=hjy(c,t);let s=c.negation||!1;if(i==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof Ose)n&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new Ose("can't match cohort without a given cohort property value");return i==="AND"}}function kwy(e){try{return new RegExp(e),!0}catch{return!1}}function ejy(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 Ose(`${e} is in an invalid date format`)}else throw new Ose(`The date provided ${e} must be a string, number, or date object`)}function scC(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let a=r.groups.interval;if(a=="h")n.setUTCHours(n.getUTCHours()-i);else if(a=="d")n.setUTCDate(n.getUTCDate()-i);else if(a=="w")n.setUTCDate(n.getUTCDate()-i*7);else if(a=="m")n.setUTCMonth(n.getUTCMonth()-i);else if(a=="y")n.setUTCFullYear(n.getUTCFullYear()-i);else return null;return n}else return null}var e0f=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},ccC=100,tjy=30*1e3,lcC=50*1e3,t0f=class extends Xgf{constructor(t,r={}){if(super(t,r),this._memoryStorage=new e0f,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,ccC):tjy,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.');this.featureFlagsPoller=new kgf({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()})}this.errorTracking=new Vka(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||lcC}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):pjy(t,r)}getLibraryVersion(){return zsC}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.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:n,properties:i,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=A=>{super.captureStateless(r,n,A,{timestamp:c,disableGeoip:d,uuid:s})},l=async(A,P,C)=>(await super.getFeatureFlagsStateless(A,P,void 0,void 0,C)).flags,m=Promise.resolve().then(async()=>{if(o)return await l(r,a,d);if(n==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let A={};for(let[P,C]of Object.entries(a||{}))A[P]=String(C);return await this.getAllFlags(r,{groups:A,disableGeoip:d,onlyEvaluateLocally:!0})}return{}}).then(A=>{let P={};if(A)for(let[M,T]of Object.entries(A))P[`$feature/${M}`]=T;let C=Object.keys(A||{}).filter(M=>A?.[M]!==!1).sort();return C.length>0&&(P.$active_feature_flags=C),P}).catch(()=>({})).then(A=>{u({...A,...i,$groups:a})});this.addPendingPromise(m)}async captureImmediate(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:n,properties:i,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=A=>super.captureStatelessImmediate(r,n,A,{timestamp:c,disableGeoip:d,uuid:s}),l=async(A,P,C)=>(await super.getFeatureFlagsStateless(A,P,void 0,void 0,C)).flags;await Promise.resolve().then(async()=>{if(o)return await l(r,a,d);if(n==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let A={};for(let[P,C]of Object.entries(a||{}))A[P]=String(C);return await this.getAllFlags(r,{groups:A,disableGeoip:d,onlyEvaluateLocally:!0})}return{}}).then(A=>{let P={};if(A)for(let[M,T]of Object.entries(A))P[`$feature/${M}`]=T;let C=Object.keys(A||{}).filter(M=>A?.[M]!==!1).sort();return C.length>0&&(P.$active_feature_flags=C),P}).catch(()=>({})).then(A=>{u({...A,...i,$groups:a})})}identify({distinctId:t,properties:r,disableGeoip:n}){let i=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;super.identifyStateless(t,{$set:a,$set_once:i},{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r,disableGeoip:n}){let i=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;await super.identifyStatelessImmediate(t,{$set:a,$set_once:i},{disableGeoip:n})}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=tjy){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(n),i(),r(a>0)})})}async getFeatureFlag(t,r,n){let{groups:i,disableGeoip:a}=n||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,i,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,i,d,s),m=l!==void 0,A,P;if(!m&&!o){let M=await super.getFeatureFlagDetailStateless(t,r,i,d,s,a);if(M===void 0)return;P=M.response,l=i0f(P),A=M?.requestId}let C=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(C))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(C):this.distinctIdHasSentFlagCalls[r]=[C],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:P?.metadata?.id,$feature_flag_version:P?.metadata?.version,$feature_flag_reason:P?.reason?.description??P?.reason?.code,locally_evaluated:m,[`$feature/${t}`]:l,$feature_flag_request_id:A},groups:i,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,n,i){let{groups:a,disableGeoip:o}=i||{},{onlyEvaluateLocally:c,sendFeatureFlagEvents:d,personProperties:s,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,a,s,u);s=l.allPersonProperties,u=l.allGroupProperties;let m;return this.featureFlagsPoller!==void 0&&(n||(n=await this.getFeatureFlag(t,r,{...i,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),n&&(m=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,n))),c==null&&(c=!1),d==null&&(d=!0),c==null&&(c=!1),!(m!==void 0)&&!c&&(m=await super.getFeatureFlagPayloadStateless(t,r,a,s,u,o)),m}async getRemoteConfigPayload(t){return(await this.featureFlagsPoller?._requestRemoteConfigPayload(t))?.json()}async isFeatureEnabled(t,r,n){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:n,disableGeoip:i}=r||{},{onlyEvaluateLocally:a,personProperties:o,groupProperties:c}=r||{},d=this.addLocalPersonAndGroupProperties(t,n,o,c);o=d.allPersonProperties,c=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,n,o,c),u={},l={},m=!0;if(s&&(u=s.response,l=s.payloads,m=s.fallbackToDecide),m&&!a){let A=await super.getFeatureFlagsAndPayloadsStateless(t,n,o,c,i);u={...u,...A.flags||{}},l={...l,...A.payloads||{}}}return{featureFlags:u,featureFlagPayloads:l}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:a}){super.groupIdentifyStateless(t,r,n,{disableGeoip:a},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(),super._shutdown(t)}addLocalPersonAndGroupProperties(t,r,n,i){let a={distinct_id:t,...n||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...i?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,n){let i=new Error("PostHog syntheticException");Vka.captureException(this,t,{syntheticException:i},r,n)}},rjy=/\(error: (.*)\)/,bjy=50,gjy="?";function fcC(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return n=>{let i=n.match(r);if(i){let a,o,c,d,s;if(i[1]){c=i[1];let m=c.lastIndexOf(".");if(c[m-1]==="."&&m--,m>0){a=c.slice(0,m),o=c.slice(m+1);let A=a.indexOf(".Module");A>0&&(c=c.slice(A+1),a=a.slice(0,A))}d=void 0}o&&(d=a,s=o),o==="<anonymous>"&&(s=void 0,c=void 0),c===void 0&&(s=s||gjy,c=d?`${d}.${s}`:s);let u=i[2]?.startsWith("file://")?i[2].slice(7):i[2],l=i[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&i[5]&&!l&&(u=i[5]),{filename:u?decodeURI(u):void 0,module:e?e(u):void 0,function:c,lineno:njy(i[3]),colno:njy(i[4]),in_app:dcC(u||"",l),platform:"node:javascript"}}if(n.match(t))return{filename:n,platform:"node:javascript"}}}function dcC(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 njy(e){return parseInt(e||"",10)||void 0}function pcC(e){return[90,fcC(e)]}function _cC(e){let r=[pcC(e)].sort((n,i)=>n[0]-i[0]).map(n=>n[1]);return(n,i=0)=>{let a=[],o=n.split(`
2166
- `);for(let c=i;c<o.length;c++){let d=o[c];if(d.length>1024)continue;let s=rjy.test(d)?d.replace(rjy,"$1"):d;if(!s.match(/\S*Error: /)){for(let u of r){let l=u(s);if(l){a.push(l);break}}if(a.length>=bjy)break}}return hcC(a)}}function hcC(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,bjy).map(r=>({...r,filename:r.filename||ycC(t).filename,function:r.function||gjy}))}function ycC(e){return e[e.length-1]||{}}Vka.stackParser=_cC(EsC());Vka.frameModifiers=[CsC];var Hka=class extends t0f{getLibraryId(){return"posthog-node"}};var qSs=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Hka(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.94.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var BKo=class{async sendEvent(){}async identify(){}async flush(){}};var Jka=require("fs/promises"),Pjy=require("os"),wjy=require("path");var mjy=fa(require("crypto")),NSs=new Uint8Array(256),RSs=NSs.length;function a0f(){return RSs>NSs.length-16&&(mjy.default.randomFillSync(NSs),RSs=0),NSs.slice(RSs,RSs+=16)}var $be=[];for(let e=0;e<256;++e)$be.push((e+256).toString(16).slice(1));function Ojy(e,t=0){return $be[e[t+0]]+$be[e[t+1]]+$be[e[t+2]]+$be[e[t+3]]+"-"+$be[e[t+4]]+$be[e[t+5]]+"-"+$be[e[t+6]]+$be[e[t+7]]+"-"+$be[e[t+8]]+$be[e[t+9]]+"-"+$be[e[t+10]]+$be[e[t+11]]+$be[e[t+12]]+$be[e[t+13]]+$be[e[t+14]]+$be[e[t+15]]}var Ajy=fa(require("crypto")),o0f={randomUUID:Ajy.default.randomUUID};function vcC(e,t,r){if(o0f.randomUUID&&!t&&!e)return o0f.randomUUID();e=e||{};let n=e.random||(e.rng||a0f)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(let i=0;i<16;++i)t[r+i]=n[i];return t}return Ojy(n)}var xht=vcC;var bcC="id",gcC=".fern",TKo=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new Hka(r),this.userId=t==null?void 0:mdf(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.94.0",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Jl(x_.of((0,Pjy.homedir)()),ys.of(gcC),ys.of(bcC));await qv(t)||(await(0,Jka.mkdir)((0,wjy.dirname)(t),{recursive:!0}),await(0,Jka.writeFile)(t,xht())),this.persistedDistinctId=(await(0,Jka.readFile)(t)).toString()}return this.persistedDistinctId}};var u0f;async function Kka(){return u0f==null&&(u0f=await mcC()),u0f}async function mcC(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new BKo;let r=await HOs();return r!=null?new TKo({token:r,posthogApiKey:e}):await KXa()!=null?new qSs({posthogApiKey:e}):new TKo({token:void 0,posthogApiKey:e})}catch{return new BKo}}function qKo(e,t){return function(){return e.apply(t,arguments)}}var{toString:OcC}=Object.prototype,{getPrototypeOf:c0f}=Object,{iterator:xSs,toStringTag:Ejy}=Symbol,zSs=(e=>t=>{let r=OcC.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),bqr=e=>(e=e.toLowerCase(),t=>zSs(t)===e),QSs=e=>t=>typeof t===e,{isArray:Yka}=Array,$ka=QSs("undefined");function RKo(e){return e!==null&&!$ka(e)&&e.constructor!==null&&!$ka(e.constructor)&&r3e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Sjy=bqr("ArrayBuffer");function AcC(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Sjy(e.buffer),t}var PcC=QSs("string"),r3e=QSs("function"),Djy=QSs("number"),NKo=e=>e!==null&&typeof e=="object",wcC=e=>e===!0||e===!1,FSs=e=>{if(zSs(e)!=="object")return!1;let t=c0f(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Ejy in e)&&!(xSs in e)},jcC=e=>{if(!NKo(e)||RKo(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},EcC=bqr("Date"),ScC=bqr("File"),DcC=bqr("Blob"),CcC=bqr("FileList"),IcC=e=>NKo(e)&&r3e(e.pipe),McC=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||r3e(e.append)&&((t=zSs(e))==="formdata"||t==="object"&&r3e(e.toString)&&e.toString()==="[object FormData]"))},BcC=bqr("URLSearchParams"),[TcC,qcC,RcC,NcC]=["ReadableStream","Request","Response","Headers"].map(bqr),FcC=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function FKo(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),Yka(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(RKo(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(n=0;n<o;n++)c=a[n],t.call(null,e[c],c,e)}}function Cjy(e,t){if(RKo(e))return null;t=t.toLowerCase();let r=Object.keys(e),n=r.length,i;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}var bca=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ijy=e=>!$ka(e)&&e!==bca;function s0f(){let{caseless:e,skipUndefined:t}=Ijy(this)&&this||{},r={},n=(i,a)=>{let o=e&&Cjy(r,a)||a;FSs(r[o])&&FSs(i)?r[o]=s0f(r[o],i):FSs(i)?r[o]=s0f({},i):Yka(i)?r[o]=i.slice():(!t||!$ka(i))&&(r[o]=i)};for(let i=0,a=arguments.length;i<a;i++)arguments[i]&&FKo(arguments[i],n);return r}var xcC=(e,t,r,{allOwnKeys:n}={})=>(FKo(t,(i,a)=>{r&&r3e(i)?e[a]=qKo(i,r):e[a]=i},{allOwnKeys:n}),e),zcC=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),QcC=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},LcC=(e,t,r,n)=>{let i,a,o,c={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)o=i[a],(!n||n(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&c0f(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},UcC=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return n!==-1&&n===r},VcC=e=>{if(!e)return null;if(Yka(e))return e;let t=e.length;if(!Djy(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},WcC=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&c0f(Uint8Array)),HcC=(e,t)=>{let n=(e&&e[xSs]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},GcC=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},JcC=bqr("HTMLFormElement"),KcC=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),jjy=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),$cC=bqr("RegExp"),Mjy=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};FKo(r,(i,a)=>{let o;(o=t(i,a,e))!==!1&&(n[a]=o||i)}),Object.defineProperties(e,n)},YcC=e=>{Mjy(e,(t,r)=>{if(r3e(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(r3e(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},XcC=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return Yka(e)?n(e):n(String(e).split(t)),r},ZcC=()=>{},kcC=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function elC(e){return!!(e&&r3e(e.append)&&e[Ejy]==="FormData"&&e[xSs])}var tlC=e=>{let t=new Array(10),r=(n,i)=>{if(NKo(n)){if(t.indexOf(n)>=0)return;if(RKo(n))return n;if(!("toJSON"in n)){t[i]=n;let a=Yka(n)?[]:{};return FKo(n,(o,c)=>{let d=r(o,i+1);!$ka(d)&&(a[c]=d)}),t[i]=void 0,a}}return n};return r(e,0)},rlC=bqr("AsyncFunction"),nlC=e=>e&&(NKo(e)||r3e(e))&&r3e(e.then)&&r3e(e.catch),Bjy=((e,t)=>e?setImmediate:t?((r,n)=>(bca.addEventListener("message",({source:i,data:a})=>{i===bca&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),bca.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",r3e(bca.postMessage)),ilC=typeof queueMicrotask<"u"?queueMicrotask.bind(bca):typeof process<"u"&&process.nextTick||Bjy,alC=e=>e!=null&&r3e(e[xSs]),Yf={isArray:Yka,isArrayBuffer:Sjy,isBuffer:RKo,isFormData:McC,isArrayBufferView:AcC,isString:PcC,isNumber:Djy,isBoolean:wcC,isObject:NKo,isPlainObject:FSs,isEmptyObject:jcC,isReadableStream:TcC,isRequest:qcC,isResponse:RcC,isHeaders:NcC,isUndefined:$ka,isDate:EcC,isFile:ScC,isBlob:DcC,isRegExp:$cC,isFunction:r3e,isStream:IcC,isURLSearchParams:BcC,isTypedArray:WcC,isFileList:CcC,forEach:FKo,merge:s0f,extend:xcC,trim:FcC,stripBOM:zcC,inherits:QcC,toFlatObject:LcC,kindOf:zSs,kindOfTest:bqr,endsWith:UcC,toArray:VcC,forEachEntry:HcC,matchAll:GcC,isHTMLForm:JcC,hasOwnProperty:jjy,hasOwnProp:jjy,reduceDescriptors:Mjy,freezeMethods:YcC,toObjectSet:XcC,toCamelCase:KcC,noop:ZcC,toFiniteNumber:kcC,findKey:Cjy,global:bca,isContextDefined:Ijy,isSpecCompliantForm:elC,toJSONObject:tlC,isAsyncFn:rlC,isThenable:nlC,setImmediate:Bjy,asap:ilC,isIterable:alC};function Xka(e,t,r,n,i){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),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Yf.inherits(Xka,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:Yf.toJSONObject(this.config),code:this.code,status:this.status}}});var Tjy=Xka.prototype,qjy={};["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=>{qjy[e]={value:e}});Object.defineProperties(Xka,qjy);Object.defineProperty(Tjy,"isAxiosError",{value:!0});Xka.from=(e,t,r,n,i,a)=>{let o=Object.create(Tjy);Yf.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 Xka.call(o,c,d,r,n,i),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 Im=Xka;var Rjy=fa(cSs(),1),LSs=Rjy.default;function l0f(e){return Yf.isPlainObject(e)||Yf.isArray(e)}function Fjy(e){return Yf.endsWith(e,"[]")?e.slice(0,-2):e}function Njy(e,t,r){return e?e.concat(t).map(function(i,a){return i=Fjy(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function olC(e){return Yf.isArray(e)&&!e.some(l0f)}var ulC=Yf.toFlatObject(Yf,{},null,function(t){return/^is[A-Z]/.test(t)});function slC(e,t,r){if(!Yf.isObject(e))throw new TypeError("target must be an object");t=t||new(LSs||FormData),r=Yf.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(C,M){return!Yf.isUndefined(M[C])});let n=r.metaTokens,i=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&Yf.isSpecCompliantForm(t);if(!Yf.isFunction(i))throw new TypeError("visitor must be a function");function s(P){if(P===null)return"";if(Yf.isDate(P))return P.toISOString();if(Yf.isBoolean(P))return P.toString();if(!d&&Yf.isBlob(P))throw new Im("Blob is not supported. Use a Buffer instead.");return Yf.isArrayBuffer(P)||Yf.isTypedArray(P)?d&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function u(P,C,M){let T=P;if(P&&!M&&typeof P=="object"){if(Yf.endsWith(C,"{}"))C=n?C:C.slice(0,-2),P=JSON.stringify(P);else if(Yf.isArray(P)&&olC(P)||(Yf.isFileList(P)||Yf.endsWith(C,"[]"))&&(T=Yf.toArray(P)))return C=Fjy(C),T.forEach(function(U,R){!(Yf.isUndefined(U)||U===null)&&t.append(o===!0?Njy([C],R,a):o===null?C:C+"[]",s(U))}),!1}return l0f(P)?!0:(t.append(Njy(M,C,a),s(P)),!1)}let l=[],m=Object.assign(ulC,{defaultVisitor:u,convertValue:s,isVisitable:l0f});function A(P,C){if(!Yf.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+C.join("."));l.push(P),Yf.forEach(P,function(T,z){(!(Yf.isUndefined(T)||T===null)&&i.call(t,T,Yf.isString(z)?z.trim():z,C,m))===!0&&A(T,C?C.concat(z):[z])}),l.pop()}}if(!Yf.isObject(e))throw new TypeError("data must be an object");return A(e),t}var i7i=slC;function xjy(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function zjy(e,t){this._pairs=[],e&&i7i(e,this,t)}var Qjy=zjy.prototype;Qjy.append=function(t,r){this._pairs.push([t,r])};Qjy.toString=function(t){let r=t?function(n){return t.call(this,n,xjy)}:xjy;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var Ljy=zjy;function clC(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function gca(e,t,r){if(!t)return e;let n=r&&r.encode||clC;Yf.isFunction(r)&&(r={serialize:r});let i=r&&r.serialize,a;if(i?a=i(t,r):a=Yf.isURLSearchParams(t)?t.toString():new Ljy(t,r).toString(n),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var f0f=class{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){Yf.forEach(this.handlers,function(n){n!==null&&t(n)})}},d0f=f0f;var Zka={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Hjy=fa(require("crypto"),1);var Ujy=fa(require("url"),1),Vjy=Ujy.default.URLSearchParams;var p0f="abcdefghijklmnopqrstuvwxyz",Wjy="0123456789",Gjy={DIGIT:Wjy,ALPHA:p0f,ALPHA_DIGIT:p0f+p0f.toUpperCase()+Wjy},llC=(e=16,t=Gjy.ALPHA_DIGIT)=>{let r="",{length:n}=t,i=new Uint32Array(e);Hjy.default.randomFillSync(i);for(let a=0;a<e;a++)r+=t[i[a]%n];return r},Jjy={isNode:!0,classes:{URLSearchParams:Vjy,FormData:LSs,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Gjy,generateString:llC,protocols:["http","https","file","data"]};var y0f={};ff(y0f,{hasBrowserEnv:()=>h0f,hasStandardBrowserEnv:()=>flC,hasStandardBrowserWebWorkerEnv:()=>dlC,navigator:()=>_0f,origin:()=>plC});var h0f=typeof window<"u"&&typeof document<"u",_0f=typeof navigator=="object"&&navigator||void 0,flC=h0f&&(!_0f||["ReactNative","NativeScript","NS"].indexOf(_0f.product)<0),dlC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",plC=h0f&&window.location.href||"http://localhost";var e8={...y0f,...Jjy};function v0f(e,t){return i7i(e,new e8.classes.URLSearchParams,{visitor:function(r,n,i,a){return e8.isNode&&Yf.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function _lC(e){return Yf.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function hlC(e){let t={},r=Object.keys(e),n,i=r.length,a;for(n=0;n<i;n++)a=r[n],t[a]=e[a];return t}function ylC(e){function t(r,n,i,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),d=a>=r.length;return o=!o&&Yf.isArray(i)?i.length:o,d?(Yf.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!c):((!i[o]||!Yf.isObject(i[o]))&&(i[o]=[]),t(r,n,i[o],a)&&Yf.isArray(i[o])&&(i[o]=hlC(i[o])),!c)}if(Yf.isFormData(e)&&Yf.isFunction(e.entries)){let r={};return Yf.forEachEntry(e,(n,i)=>{t(_lC(n),i,r,0)}),r}return null}var USs=ylC;function vlC(e,t,r){if(Yf.isString(e))try{return(t||JSON.parse)(e),Yf.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var b0f={transitional:Zka,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=Yf.isObject(t);if(a&&Yf.isHTMLForm(t)&&(t=new FormData(t)),Yf.isFormData(t))return i?JSON.stringify(USs(t)):t;if(Yf.isArrayBuffer(t)||Yf.isBuffer(t)||Yf.isStream(t)||Yf.isFile(t)||Yf.isBlob(t)||Yf.isReadableStream(t))return t;if(Yf.isArrayBufferView(t))return t.buffer;if(Yf.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return v0f(t,this.formSerializer).toString();if((c=Yf.isFileList(t))||n.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return i7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),vlC(t)):t}],transformResponse:[function(t){let r=this.transitional||b0f.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Yf.isResponse(t)||Yf.isReadableStream(t))return t;if(t&&Yf.isString(t)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?Im.from(c,Im.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:e8.classes.FormData,Blob:e8.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Yf.forEach(["delete","get","head","post","put","patch"],e=>{b0f.headers[e]={}});var kka=b0f;var blC=Yf.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"]),Kjy=e=>{let t={},r,n,i;return e&&e.split(`
2166
+ `);for(let c=i;c<o.length;c++){let d=o[c];if(d.length>1024)continue;let s=rjy.test(d)?d.replace(rjy,"$1"):d;if(!s.match(/\S*Error: /)){for(let u of r){let l=u(s);if(l){a.push(l);break}}if(a.length>=bjy)break}}return hcC(a)}}function hcC(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,bjy).map(r=>({...r,filename:r.filename||ycC(t).filename,function:r.function||gjy}))}function ycC(e){return e[e.length-1]||{}}Vka.stackParser=_cC(EsC());Vka.frameModifiers=[CsC];var Hka=class extends t0f{getLibraryId(){return"posthog-node"}};var qSs=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Hka(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.94.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var BKo=class{async sendEvent(){}async identify(){}async flush(){}};var Jka=require("fs/promises"),Pjy=require("os"),wjy=require("path");var mjy=fa(require("crypto")),NSs=new Uint8Array(256),RSs=NSs.length;function a0f(){return RSs>NSs.length-16&&(mjy.default.randomFillSync(NSs),RSs=0),NSs.slice(RSs,RSs+=16)}var $be=[];for(let e=0;e<256;++e)$be.push((e+256).toString(16).slice(1));function Ojy(e,t=0){return $be[e[t+0]]+$be[e[t+1]]+$be[e[t+2]]+$be[e[t+3]]+"-"+$be[e[t+4]]+$be[e[t+5]]+"-"+$be[e[t+6]]+$be[e[t+7]]+"-"+$be[e[t+8]]+$be[e[t+9]]+"-"+$be[e[t+10]]+$be[e[t+11]]+$be[e[t+12]]+$be[e[t+13]]+$be[e[t+14]]+$be[e[t+15]]}var Ajy=fa(require("crypto")),o0f={randomUUID:Ajy.default.randomUUID};function vcC(e,t,r){if(o0f.randomUUID&&!t&&!e)return o0f.randomUUID();e=e||{};let n=e.random||(e.rng||a0f)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(let i=0;i<16;++i)t[r+i]=n[i];return t}return Ojy(n)}var xht=vcC;var bcC="id",gcC=".fern",TKo=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new Hka(r),this.userId=t==null?void 0:mdf(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.94.1",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Jl(x_.of((0,Pjy.homedir)()),ys.of(gcC),ys.of(bcC));await qv(t)||(await(0,Jka.mkdir)((0,wjy.dirname)(t),{recursive:!0}),await(0,Jka.writeFile)(t,xht())),this.persistedDistinctId=(await(0,Jka.readFile)(t)).toString()}return this.persistedDistinctId}};var u0f;async function Kka(){return u0f==null&&(u0f=await mcC()),u0f}async function mcC(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new BKo;let r=await HOs();return r!=null?new TKo({token:r,posthogApiKey:e}):await KXa()!=null?new qSs({posthogApiKey:e}):new TKo({token:void 0,posthogApiKey:e})}catch{return new BKo}}function qKo(e,t){return function(){return e.apply(t,arguments)}}var{toString:OcC}=Object.prototype,{getPrototypeOf:c0f}=Object,{iterator:xSs,toStringTag:Ejy}=Symbol,zSs=(e=>t=>{let r=OcC.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),bqr=e=>(e=e.toLowerCase(),t=>zSs(t)===e),QSs=e=>t=>typeof t===e,{isArray:Yka}=Array,$ka=QSs("undefined");function RKo(e){return e!==null&&!$ka(e)&&e.constructor!==null&&!$ka(e.constructor)&&r3e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Sjy=bqr("ArrayBuffer");function AcC(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Sjy(e.buffer),t}var PcC=QSs("string"),r3e=QSs("function"),Djy=QSs("number"),NKo=e=>e!==null&&typeof e=="object",wcC=e=>e===!0||e===!1,FSs=e=>{if(zSs(e)!=="object")return!1;let t=c0f(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Ejy in e)&&!(xSs in e)},jcC=e=>{if(!NKo(e)||RKo(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},EcC=bqr("Date"),ScC=bqr("File"),DcC=bqr("Blob"),CcC=bqr("FileList"),IcC=e=>NKo(e)&&r3e(e.pipe),McC=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||r3e(e.append)&&((t=zSs(e))==="formdata"||t==="object"&&r3e(e.toString)&&e.toString()==="[object FormData]"))},BcC=bqr("URLSearchParams"),[TcC,qcC,RcC,NcC]=["ReadableStream","Request","Response","Headers"].map(bqr),FcC=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function FKo(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),Yka(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(RKo(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(n=0;n<o;n++)c=a[n],t.call(null,e[c],c,e)}}function Cjy(e,t){if(RKo(e))return null;t=t.toLowerCase();let r=Object.keys(e),n=r.length,i;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}var bca=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ijy=e=>!$ka(e)&&e!==bca;function s0f(){let{caseless:e,skipUndefined:t}=Ijy(this)&&this||{},r={},n=(i,a)=>{let o=e&&Cjy(r,a)||a;FSs(r[o])&&FSs(i)?r[o]=s0f(r[o],i):FSs(i)?r[o]=s0f({},i):Yka(i)?r[o]=i.slice():(!t||!$ka(i))&&(r[o]=i)};for(let i=0,a=arguments.length;i<a;i++)arguments[i]&&FKo(arguments[i],n);return r}var xcC=(e,t,r,{allOwnKeys:n}={})=>(FKo(t,(i,a)=>{r&&r3e(i)?e[a]=qKo(i,r):e[a]=i},{allOwnKeys:n}),e),zcC=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),QcC=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},LcC=(e,t,r,n)=>{let i,a,o,c={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)o=i[a],(!n||n(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&c0f(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},UcC=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return n!==-1&&n===r},VcC=e=>{if(!e)return null;if(Yka(e))return e;let t=e.length;if(!Djy(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},WcC=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&c0f(Uint8Array)),HcC=(e,t)=>{let n=(e&&e[xSs]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},GcC=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},JcC=bqr("HTMLFormElement"),KcC=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),jjy=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),$cC=bqr("RegExp"),Mjy=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};FKo(r,(i,a)=>{let o;(o=t(i,a,e))!==!1&&(n[a]=o||i)}),Object.defineProperties(e,n)},YcC=e=>{Mjy(e,(t,r)=>{if(r3e(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(r3e(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},XcC=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return Yka(e)?n(e):n(String(e).split(t)),r},ZcC=()=>{},kcC=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function elC(e){return!!(e&&r3e(e.append)&&e[Ejy]==="FormData"&&e[xSs])}var tlC=e=>{let t=new Array(10),r=(n,i)=>{if(NKo(n)){if(t.indexOf(n)>=0)return;if(RKo(n))return n;if(!("toJSON"in n)){t[i]=n;let a=Yka(n)?[]:{};return FKo(n,(o,c)=>{let d=r(o,i+1);!$ka(d)&&(a[c]=d)}),t[i]=void 0,a}}return n};return r(e,0)},rlC=bqr("AsyncFunction"),nlC=e=>e&&(NKo(e)||r3e(e))&&r3e(e.then)&&r3e(e.catch),Bjy=((e,t)=>e?setImmediate:t?((r,n)=>(bca.addEventListener("message",({source:i,data:a})=>{i===bca&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),bca.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",r3e(bca.postMessage)),ilC=typeof queueMicrotask<"u"?queueMicrotask.bind(bca):typeof process<"u"&&process.nextTick||Bjy,alC=e=>e!=null&&r3e(e[xSs]),Yf={isArray:Yka,isArrayBuffer:Sjy,isBuffer:RKo,isFormData:McC,isArrayBufferView:AcC,isString:PcC,isNumber:Djy,isBoolean:wcC,isObject:NKo,isPlainObject:FSs,isEmptyObject:jcC,isReadableStream:TcC,isRequest:qcC,isResponse:RcC,isHeaders:NcC,isUndefined:$ka,isDate:EcC,isFile:ScC,isBlob:DcC,isRegExp:$cC,isFunction:r3e,isStream:IcC,isURLSearchParams:BcC,isTypedArray:WcC,isFileList:CcC,forEach:FKo,merge:s0f,extend:xcC,trim:FcC,stripBOM:zcC,inherits:QcC,toFlatObject:LcC,kindOf:zSs,kindOfTest:bqr,endsWith:UcC,toArray:VcC,forEachEntry:HcC,matchAll:GcC,isHTMLForm:JcC,hasOwnProperty:jjy,hasOwnProp:jjy,reduceDescriptors:Mjy,freezeMethods:YcC,toObjectSet:XcC,toCamelCase:KcC,noop:ZcC,toFiniteNumber:kcC,findKey:Cjy,global:bca,isContextDefined:Ijy,isSpecCompliantForm:elC,toJSONObject:tlC,isAsyncFn:rlC,isThenable:nlC,setImmediate:Bjy,asap:ilC,isIterable:alC};function Xka(e,t,r,n,i){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),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Yf.inherits(Xka,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:Yf.toJSONObject(this.config),code:this.code,status:this.status}}});var Tjy=Xka.prototype,qjy={};["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=>{qjy[e]={value:e}});Object.defineProperties(Xka,qjy);Object.defineProperty(Tjy,"isAxiosError",{value:!0});Xka.from=(e,t,r,n,i,a)=>{let o=Object.create(Tjy);Yf.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 Xka.call(o,c,d,r,n,i),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 Im=Xka;var Rjy=fa(cSs(),1),LSs=Rjy.default;function l0f(e){return Yf.isPlainObject(e)||Yf.isArray(e)}function Fjy(e){return Yf.endsWith(e,"[]")?e.slice(0,-2):e}function Njy(e,t,r){return e?e.concat(t).map(function(i,a){return i=Fjy(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function olC(e){return Yf.isArray(e)&&!e.some(l0f)}var ulC=Yf.toFlatObject(Yf,{},null,function(t){return/^is[A-Z]/.test(t)});function slC(e,t,r){if(!Yf.isObject(e))throw new TypeError("target must be an object");t=t||new(LSs||FormData),r=Yf.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(C,M){return!Yf.isUndefined(M[C])});let n=r.metaTokens,i=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&Yf.isSpecCompliantForm(t);if(!Yf.isFunction(i))throw new TypeError("visitor must be a function");function s(P){if(P===null)return"";if(Yf.isDate(P))return P.toISOString();if(Yf.isBoolean(P))return P.toString();if(!d&&Yf.isBlob(P))throw new Im("Blob is not supported. Use a Buffer instead.");return Yf.isArrayBuffer(P)||Yf.isTypedArray(P)?d&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function u(P,C,M){let T=P;if(P&&!M&&typeof P=="object"){if(Yf.endsWith(C,"{}"))C=n?C:C.slice(0,-2),P=JSON.stringify(P);else if(Yf.isArray(P)&&olC(P)||(Yf.isFileList(P)||Yf.endsWith(C,"[]"))&&(T=Yf.toArray(P)))return C=Fjy(C),T.forEach(function(U,R){!(Yf.isUndefined(U)||U===null)&&t.append(o===!0?Njy([C],R,a):o===null?C:C+"[]",s(U))}),!1}return l0f(P)?!0:(t.append(Njy(M,C,a),s(P)),!1)}let l=[],m=Object.assign(ulC,{defaultVisitor:u,convertValue:s,isVisitable:l0f});function A(P,C){if(!Yf.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+C.join("."));l.push(P),Yf.forEach(P,function(T,z){(!(Yf.isUndefined(T)||T===null)&&i.call(t,T,Yf.isString(z)?z.trim():z,C,m))===!0&&A(T,C?C.concat(z):[z])}),l.pop()}}if(!Yf.isObject(e))throw new TypeError("data must be an object");return A(e),t}var i7i=slC;function xjy(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function zjy(e,t){this._pairs=[],e&&i7i(e,this,t)}var Qjy=zjy.prototype;Qjy.append=function(t,r){this._pairs.push([t,r])};Qjy.toString=function(t){let r=t?function(n){return t.call(this,n,xjy)}:xjy;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var Ljy=zjy;function clC(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function gca(e,t,r){if(!t)return e;let n=r&&r.encode||clC;Yf.isFunction(r)&&(r={serialize:r});let i=r&&r.serialize,a;if(i?a=i(t,r):a=Yf.isURLSearchParams(t)?t.toString():new Ljy(t,r).toString(n),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var f0f=class{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){Yf.forEach(this.handlers,function(n){n!==null&&t(n)})}},d0f=f0f;var Zka={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Hjy=fa(require("crypto"),1);var Ujy=fa(require("url"),1),Vjy=Ujy.default.URLSearchParams;var p0f="abcdefghijklmnopqrstuvwxyz",Wjy="0123456789",Gjy={DIGIT:Wjy,ALPHA:p0f,ALPHA_DIGIT:p0f+p0f.toUpperCase()+Wjy},llC=(e=16,t=Gjy.ALPHA_DIGIT)=>{let r="",{length:n}=t,i=new Uint32Array(e);Hjy.default.randomFillSync(i);for(let a=0;a<e;a++)r+=t[i[a]%n];return r},Jjy={isNode:!0,classes:{URLSearchParams:Vjy,FormData:LSs,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Gjy,generateString:llC,protocols:["http","https","file","data"]};var y0f={};ff(y0f,{hasBrowserEnv:()=>h0f,hasStandardBrowserEnv:()=>flC,hasStandardBrowserWebWorkerEnv:()=>dlC,navigator:()=>_0f,origin:()=>plC});var h0f=typeof window<"u"&&typeof document<"u",_0f=typeof navigator=="object"&&navigator||void 0,flC=h0f&&(!_0f||["ReactNative","NativeScript","NS"].indexOf(_0f.product)<0),dlC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",plC=h0f&&window.location.href||"http://localhost";var e8={...y0f,...Jjy};function v0f(e,t){return i7i(e,new e8.classes.URLSearchParams,{visitor:function(r,n,i,a){return e8.isNode&&Yf.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function _lC(e){return Yf.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function hlC(e){let t={},r=Object.keys(e),n,i=r.length,a;for(n=0;n<i;n++)a=r[n],t[a]=e[a];return t}function ylC(e){function t(r,n,i,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),d=a>=r.length;return o=!o&&Yf.isArray(i)?i.length:o,d?(Yf.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!c):((!i[o]||!Yf.isObject(i[o]))&&(i[o]=[]),t(r,n,i[o],a)&&Yf.isArray(i[o])&&(i[o]=hlC(i[o])),!c)}if(Yf.isFormData(e)&&Yf.isFunction(e.entries)){let r={};return Yf.forEachEntry(e,(n,i)=>{t(_lC(n),i,r,0)}),r}return null}var USs=ylC;function vlC(e,t,r){if(Yf.isString(e))try{return(t||JSON.parse)(e),Yf.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var b0f={transitional:Zka,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=Yf.isObject(t);if(a&&Yf.isHTMLForm(t)&&(t=new FormData(t)),Yf.isFormData(t))return i?JSON.stringify(USs(t)):t;if(Yf.isArrayBuffer(t)||Yf.isBuffer(t)||Yf.isStream(t)||Yf.isFile(t)||Yf.isBlob(t)||Yf.isReadableStream(t))return t;if(Yf.isArrayBufferView(t))return t.buffer;if(Yf.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return v0f(t,this.formSerializer).toString();if((c=Yf.isFileList(t))||n.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return i7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),vlC(t)):t}],transformResponse:[function(t){let r=this.transitional||b0f.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Yf.isResponse(t)||Yf.isReadableStream(t))return t;if(t&&Yf.isString(t)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?Im.from(c,Im.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:e8.classes.FormData,Blob:e8.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Yf.forEach(["delete","get","head","post","put","patch"],e=>{b0f.headers[e]={}});var kka=b0f;var blC=Yf.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"]),Kjy=e=>{let t={},r,n,i;return e&&e.split(`
2167
2167
  `).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||t[r]&&blC[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};var $jy=Symbol("internals");function xKo(e){return e&&String(e).trim().toLowerCase()}function VSs(e){return e===!1||e==null?e:Yf.isArray(e)?e.map(VSs):String(e)}function glC(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}var mlC=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function g0f(e,t,r,n,i){if(Yf.isFunction(n))return n.call(this,t,r);if(i&&(t=r),!!Yf.isString(t)){if(Yf.isString(n))return t.indexOf(n)!==-1;if(Yf.isRegExp(n))return n.test(t)}}function OlC(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function AlC(e,t){let r=Yf.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(i,a,o){return this[n].call(this,t,i,a,o)},configurable:!0})})}var eeo=class{constructor(t){t&&this.set(t)}set(t,r,n){let i=this;function a(c,d,s){let u=xKo(d);if(!u)throw new Error("header name must be a non-empty string");let l=Yf.findKey(i,u);(!l||i[l]===void 0||s===!0||s===void 0&&i[l]!==!1)&&(i[l||d]=VSs(c))}let o=(c,d)=>Yf.forEach(c,(s,u)=>a(s,u,d));if(Yf.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(Yf.isString(t)&&(t=t.trim())&&!mlC(t))o(Kjy(t),r);else if(Yf.isObject(t)&&Yf.isIterable(t)){let c={},d,s;for(let u of t){if(!Yf.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(d=c[s])?Yf.isArray(d)?[...d,u[1]]:[d,u[1]]:u[1]}o(c,r)}else t!=null&&a(r,t,n);return this}get(t,r){if(t=xKo(t),t){let n=Yf.findKey(this,t);if(n){let i=this[n];if(!r)return i;if(r===!0)return glC(i);if(Yf.isFunction(r))return r.call(this,i,n);if(Yf.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=xKo(t),t){let n=Yf.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||g0f(this,this[n],n,r)))}return!1}delete(t,r){let n=this,i=!1;function a(o){if(o=xKo(o),o){let c=Yf.findKey(n,o);c&&(!r||g0f(n,n[c],c,r))&&(delete n[c],i=!0)}}return Yf.isArray(t)?t.forEach(a):a(t),i}clear(t){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let a=r[n];(!t||g0f(this,this[a],a,t,!0))&&(delete this[a],i=!0)}return i}normalize(t){let r=this,n={};return Yf.forEach(this,(i,a)=>{let o=Yf.findKey(n,a);if(o){r[o]=VSs(i),delete r[a];return}let c=t?OlC(a):String(a).trim();c!==a&&delete r[a],r[c]=VSs(i),n[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return Yf.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=t&&Yf.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
2168
2168
  `)}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 n=new this(t);return r.forEach(i=>n.set(i)),n}static accessor(t){let n=(this[$jy]=this[$jy]={accessors:{}}).accessors,i=this.prototype;function a(o){let c=xKo(o);n[c]||(AlC(i,o),n[c]=!0)}return Yf.isArray(t)?t.forEach(a):a(t),this}};eeo.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Yf.reduceDescriptors(eeo.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});Yf.freezeMethods(eeo);var x$=eeo;function zKo(e,t){let r=this||kka,n=t||r,i=x$.from(n.headers),a=n.data;return Yf.forEach(e,function(c){a=c.call(r,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function QKo(e){return!!(e&&e.__CANCEL__)}function Yjy(e,t,r){Im.call(this,e??"canceled",Im.ERR_CANCELED,t,r),this.name="CanceledError"}Yf.inherits(Yjy,Im,{__CANCEL__:!0});var Knt=Yjy;function YUr(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new Im("Request failed with status code "+r.status,[Im.ERR_BAD_REQUEST,Im.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function m0f(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function O0f(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function mca(e,t,r){let n=!m0f(t);return e&&(n||r==!1)?O0f(e,t):t}var d1y=fa(lSs(),1),p1y=fa(require("http"),1),_1y=fa(require("https"),1),h1y=fa(require("util"),1),y1y=fa(Agf(),1),LAi=fa(require("zlib"),1);var Oca="1.12.2";function LKo(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var PlC=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function A0f(e,t,r){let n=r&&r.Blob||e8.classes.Blob,i=LKo(e);if(t===void 0&&n&&(t=!0),i==="data"){e=i.length?e.slice(i.length+1):e;let a=PlC.exec(e);if(!a)throw new Im("Invalid URL",Im.ERR_INVALID_URL);let o=a[1],c=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),c?"base64":"utf8");if(t){if(!n)throw new Im("Blob is not supported",Im.ERR_NOT_SUPPORT);return new n([s],{type:o})}return s}throw new Im("Unsupported protocol "+i,Im.ERR_NOT_SUPPORT)}var Pca=fa(require("stream"),1);var Xjy=fa(require("stream"),1);var P0f=Symbol("internals"),w0f=class extends Xjy.default.Transform{constructor(t){t=Yf.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(n,i)=>!Yf.isUndefined(i[n])),super({readableHighWaterMark:t.chunkSize});let r=this[P0f]={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",n=>{n==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[P0f];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,n){let i=this[P0f],a=i.maxRate,o=this.readableHighWaterMark,c=i.timeWindow,d=1e3/c,s=a/d,u=i.minChunkSize!==!1?Math.max(i.minChunkSize,s*.01):0,l=(A,P)=>{let C=Buffer.byteLength(A);i.bytesSeen+=C,i.bytes+=C,i.isCaptured&&this.emit("progress",i.bytesSeen),this.push(A)?process.nextTick(P):i.onReadCallback=()=>{i.onReadCallback=null,process.nextTick(P)}},m=(A,P)=>{let C=Buffer.byteLength(A),M=null,T=o,z,U=0;if(a){let R=Date.now();(!i.ts||(U=R-i.ts)>=c)&&(i.ts=R,z=s-i.bytes,i.bytes=z<0?-z:0,U=0),z=s-i.bytes}if(a){if(z<=0)return setTimeout(()=>{P(null,A)},c-U);z<T&&(T=z)}T&&C>T&&C-T>u&&(M=A.subarray(T),A=A.subarray(0,T)),l(A,M?()=>{process.nextTick(P,null,M)}:P)};m(t,function A(P,C){if(P)return n(P);C?m(C,A):n(null)})}},j0f=w0f;var v1y=require("events");var kjy=fa(require("util"),1),e1y=require("stream");var{asyncIterator:Zjy}=Symbol,wlC=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[Zjy]?yield*e[Zjy]():yield e},WSs=wlC;var jlC=e8.ALPHABET.ALPHA_DIGIT+"-_",UKo=typeof TextEncoder=="function"?new TextEncoder:new kjy.default.TextEncoder,Aca=`\r
2169
2169
  `,ElC=UKo.encode(Aca),SlC=2,E0f=class{constructor(t,r){let{escapeName:n}=this.constructor,i=Yf.isString(r),a=`Content-Disposition: form-data; name="${n(t)}"${!i&&r.name?`; filename="${n(r.name)}"`:""}${Aca}`;i?r=UKo.encode(String(r).replace(/\r?\n|\r\n?/g,Aca)):a+=`Content-Type: ${r.type||"application/octet-stream"}${Aca}`,this.headers=UKo.encode(a+Aca),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+SlC,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;Yf.isTypedArray(t)?yield t:yield*WSs(t),yield ElC}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},DlC=(e,t,r)=>{let{tag:n="form-data-boundary",size:i=25,boundary:a=n+"-"+e8.generateString(i,jlC)}=r||{};if(!Yf.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=UKo.encode("--"+a+Aca),c=UKo.encode("--"+a+"--"+Aca),d=c.byteLength,s=Array.from(e.entries()).map(([l,m])=>{let A=new E0f(l,m);return d+=A.size,A});d+=o.byteLength*s.length,d=Yf.toFiniteNumber(d);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(u["Content-Length"]=d),t&&t(u),e1y.Readable.from((async function*(){for(let l of s)yield o,yield*l.encode();yield c})())},t1y=DlC;var r1y=fa(require("stream"),1),S0f=class extends r1y.default.Transform{__transform(t,r,n){this.push(t),n()}_transform(t,r,n){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let i=Buffer.alloc(2);i[0]=120,i[1]=156,this.push(i,r)}this.__transform(t,r,n)}},n1y=S0f;var ClC=(e,t)=>Yf.isAsyncFn(e)?function(...r){let n=r.pop();e.apply(this,r).then(i=>{try{t?n(null,...t(i)):n(null,i)}catch(a){n(a)}},n)}:e,i1y=ClC;function IlC(e,t){e=e||10;let r=new Array(e),n=new Array(e),i=0,a=0,o;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),u=n[a];o||(o=s),r[i]=d,n[i]=s;let l=a,m=0;for(;l!==i;)m+=r[l++],l=l%e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),s-o<t)return;let A=u&&s-u;return A?Math.round(m*1e3/A):void 0}}var a1y=IlC;function MlC(e,t){let r=0,n=1e3/t,i,a,o=(s,u=Date.now())=>{r=u,i=null,a&&(clearTimeout(a),a=null),e(...s)};return[(...s)=>{let u=Date.now(),l=u-r;l>=n?o(s,u):(i=s,a||(a=setTimeout(()=>{a=null,o(i)},n-l)))},()=>i&&o(i)]}var o1y=MlC;var QAi=(e,t,r=3)=>{let n=0,i=a1y(50,250);return o1y(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,d=o-n,s=i(d),u=o<=c;n=o;let l={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(l)},r)},teo=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},reo=e=>(...t)=>Yf.asap(()=>e(...t));function D0f(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),n=e.slice(t+1);if(/;base64/i.test(r)){let a=n.length,o=n.length;for(let m=0;m<o;m++)if(n.charCodeAt(m)===37&&m+2<o){let A=n.charCodeAt(m+1),P=n.charCodeAt(m+2);(A>=48&&A<=57||A>=65&&A<=70||A>=97&&A<=102)&&(P>=48&&P<=57||P>=65&&P<=70||P>=97&&P<=102)&&(a-=2,m+=2)}let c=0,d=o-1,s=m=>m>=2&&n.charCodeAt(m-2)===37&&n.charCodeAt(m-1)===51&&(n.charCodeAt(m)===68||n.charCodeAt(m)===100);d>=0&&(n.charCodeAt(d)===61?(c++,d--):s(d)&&(c++,d-=3)),c===1&&d>=0&&(n.charCodeAt(d)===61||s(d))&&c++;let l=Math.floor(a/4)*3-(c||0);return l>0?l:0}return Buffer.byteLength(n,"utf8")}var u1y={flush:LAi.default.constants.Z_SYNC_FLUSH,finishFlush:LAi.default.constants.Z_SYNC_FLUSH},BlC={flush:LAi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:LAi.default.constants.BROTLI_OPERATION_FLUSH},s1y=Yf.isFunction(LAi.default.createBrotliDecompress),{http:TlC,https:qlC}=y1y.default,RlC=/https:?/,c1y=e8.protocols.map(e=>e+":"),l1y=(e,[t,r])=>(e.on("end",r).on("error",r),t);function NlC(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function b1y(e,t,r){let n=t;if(!n&&n!==!1){let i=d1y.default.getProxyForUrl(r);i&&(n=new URL(i))}if(n){if(n.username&&(n.auth=(n.username||"")+":"+(n.password||"")),n.auth){(n.auth.username||n.auth.password)&&(n.auth=(n.auth.username||"")+":"+(n.auth.password||""));let a=Buffer.from(n.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let i=n.hostname||n.host;e.hostname=i,e.host=i,e.port=n.port,e.path=r,n.protocol&&(e.protocol=n.protocol.includes(":")?n.protocol:`${n.protocol}:`)}e.beforeRedirects.proxy=function(a){b1y(a,t,a.href)}}var FlC=typeof process<"u"&&Yf.kindOf(process)==="process",xlC=e=>new Promise((t,r)=>{let n,i,a=(d,s)=>{i||(i=!0,n&&n(d,s))},o=d=>{a(d),t(d)},c=d=>{a(d,!0),r(d)};e(o,c,d=>n=d).catch(c)}),zlC=({address:e,family:t})=>{if(!Yf.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},f1y=(e,t)=>zlC(Yf.isObject(e)?e:{address:e,family:t}),g1y=FlC&&function(t){return xlC(async function(n,i,a){let{data:o,lookup:c,family:d}=t,{responseType:s,responseEncoding:u}=t,l=t.method.toUpperCase(),m,A=!1,P;if(c){let Ee=i1y(c,St=>Yf.isArray(St)?St:[St]);c=(St,gt,xe)=>{Ee(St,gt,(Ie,Ut,et)=>{if(Ie)return xe(Ie);let Xt=Yf.isArray(Ut)?Ut.map(Bt=>f1y(Bt)):[f1y(Ut,et)];gt.all?xe(Ie,Xt):xe(Ie,Xt[0].address,Xt[0].family)})}}let C=new v1y.EventEmitter,M=()=>{t.cancelToken&&t.cancelToken.unsubscribe(T),t.signal&&t.signal.removeEventListener("abort",T),C.removeAllListeners()};a((Ee,St)=>{m=!0,St&&(A=!0,M())});function T(Ee){C.emit("abort",!Ee||Ee.type?new Knt(null,t,P):Ee)}C.once("abort",i),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(T),t.signal&&(t.signal.aborted?T():t.signal.addEventListener("abort",T)));let z=mca(t.baseURL,t.url,t.allowAbsoluteUrls),U=new URL(z,e8.hasBrowserEnv?e8.origin:void 0),R=U.protocol||c1y[0];if(R==="data:"){if(t.maxContentLength>-1){let St=String(t.url||z||"");if(D0f(St)>t.maxContentLength)return i(new Im("maxContentLength size of "+t.maxContentLength+" exceeded",Im.ERR_BAD_RESPONSE,t))}let Ee;if(l!=="GET")return YUr(n,i,{status:405,statusText:"method not allowed",headers:{},config:t});try{Ee=A0f(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(St){throw Im.from(St,Im.ERR_BAD_REQUEST,t)}return s==="text"?(Ee=Ee.toString(u),(!u||u==="utf8")&&(Ee=Yf.stripBOM(Ee))):s==="stream"&&(Ee=Pca.default.Readable.from(Ee)),YUr(n,i,{data:Ee,status:200,statusText:"OK",headers:new x$,config:t})}if(c1y.indexOf(R)===-1)return i(new Im("Unsupported protocol "+R,Im.ERR_BAD_REQUEST,t));let V=x$.from(t.headers).normalize();V.set("User-Agent","axios/"+Oca,!1);let{onUploadProgress:Y,onDownloadProgress:re}=t,X=t.maxRate,ee,ne;if(Yf.isSpecCompliantForm(o)){let Ee=V.getContentType(/boundary=([-_\w\d]{10,70})/i);o=t1y(o,St=>{V.set(St)},{tag:`axios-${Oca}-boundary`,boundary:Ee&&Ee[1]||void 0})}else if(Yf.isFormData(o)&&Yf.isFunction(o.getHeaders)){if(V.set(o.getHeaders()),!V.hasContentLength())try{let Ee=await h1y.default.promisify(o.getLength).call(o);Number.isFinite(Ee)&&Ee>=0&&V.setContentLength(Ee)}catch{}}else if(Yf.isBlob(o)||Yf.isFile(o))o.size&&V.setContentType(o.type||"application/octet-stream"),V.setContentLength(o.size||0),o=Pca.default.Readable.from(WSs(o));else if(o&&!Yf.isStream(o)){if(!Buffer.isBuffer(o))if(Yf.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(Yf.isString(o))o=Buffer.from(o,"utf-8");else return i(new Im("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Im.ERR_BAD_REQUEST,t));if(V.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return i(new Im("Request body larger than maxBodyLength limit",Im.ERR_BAD_REQUEST,t))}let me=Yf.toFiniteNumber(V.getContentLength());Yf.isArray(X)?(ee=X[0],ne=X[1]):ee=ne=X,o&&(Y||ee)&&(Yf.isStream(o)||(o=Pca.default.Readable.from(o,{objectMode:!1})),o=Pca.default.pipeline([o,new j0f({maxRate:Yf.toFiniteNumber(ee)})],Yf.noop),Y&&o.on("progress",l1y(o,teo(me,QAi(reo(Y),!1,3)))));let be;if(t.auth){let Ee=t.auth.username||"",St=t.auth.password||"";be=Ee+":"+St}if(!be&&U.username){let Ee=U.username,St=U.password;be=Ee+":"+St}be&&V.delete("authorization");let Ae;try{Ae=gca(U.pathname+U.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(Ee){let St=new Error(Ee.message);return St.config=t,St.url=t.url,St.exists=!0,i(St)}V.set("Accept-Encoding","gzip, compress, deflate"+(s1y?", br":""),!1);let he={path:Ae,method:l,headers:V.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:be,protocol:R,family:d,beforeRedirect:NlC,beforeRedirects:{}};!Yf.isUndefined(c)&&(he.lookup=c),t.socketPath?he.socketPath=t.socketPath:(he.hostname=U.hostname.startsWith("[")?U.hostname.slice(1,-1):U.hostname,he.port=U.port,b1y(he,t.proxy,R+"//"+U.hostname+(U.port?":"+U.port:"")+he.path));let Me,Be=RlC.test(he.protocol);if(he.agent=Be?t.httpsAgent:t.httpAgent,t.transport?Me=t.transport:t.maxRedirects===0?Me=Be?_1y.default:p1y.default:(t.maxRedirects&&(he.maxRedirects=t.maxRedirects),t.beforeRedirect&&(he.beforeRedirects.config=t.beforeRedirect),Me=Be?qlC:TlC),t.maxBodyLength>-1?he.maxBodyLength=t.maxBodyLength:he.maxBodyLength=1/0,t.insecureHTTPParser&&(he.insecureHTTPParser=t.insecureHTTPParser),P=Me.request(he,function(St){if(P.destroyed)return;let gt=[St],xe=+St.headers["content-length"];if(re||ne){let Bt=new j0f({maxRate:Yf.toFiniteNumber(ne)});re&&Bt.on("progress",l1y(Bt,teo(xe,QAi(reo(re),!0,3)))),gt.push(Bt)}let Ie=St,Ut=St.req||P;if(t.decompress!==!1&&St.headers["content-encoding"])switch((l==="HEAD"||St.statusCode===204)&&delete St.headers["content-encoding"],(St.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":gt.push(LAi.default.createUnzip(u1y)),delete St.headers["content-encoding"];break;case"deflate":gt.push(new n1y),gt.push(LAi.default.createUnzip(u1y)),delete St.headers["content-encoding"];break;case"br":s1y&&(gt.push(LAi.default.createBrotliDecompress(BlC)),delete St.headers["content-encoding"])}Ie=gt.length>1?Pca.default.pipeline(gt,Yf.noop):gt[0];let et=Pca.default.finished(Ie,()=>{et(),M()}),Xt={status:St.statusCode,statusText:St.statusMessage,headers:new x$(St.headers),config:t,request:Ut};if(s==="stream")Xt.data=Ie,YUr(n,i,Xt);else{let Bt=[],$e=0;Ie.on("data",function(cr){Bt.push(cr),$e+=cr.length,t.maxContentLength>-1&&$e>t.maxContentLength&&(A=!0,Ie.destroy(),i(new Im("maxContentLength size of "+t.maxContentLength+" exceeded",Im.ERR_BAD_RESPONSE,t,Ut)))}),Ie.on("aborted",function(){if(A)return;let cr=new Im("stream has been aborted",Im.ERR_BAD_RESPONSE,t,Ut);Ie.destroy(cr),i(cr)}),Ie.on("error",function(cr){P.destroyed||i(Im.from(cr,null,t,Ut))}),Ie.on("end",function(){try{let cr=Bt.length===1?Bt[0]:Buffer.concat(Bt);s!=="arraybuffer"&&(cr=cr.toString(u),(!u||u==="utf8")&&(cr=Yf.stripBOM(cr))),Xt.data=cr}catch(cr){return i(Im.from(cr,null,t,Xt.request,Xt))}YUr(n,i,Xt)})}C.once("abort",Bt=>{Ie.destroyed||(Ie.emit("error",Bt),Ie.destroy())})}),C.once("abort",Ee=>{i(Ee),P.destroy(Ee)}),P.on("error",function(St){i(Im.from(St,null,t,P))}),P.on("socket",function(St){St.setKeepAlive(!0,1e3*60)}),t.timeout){let Ee=parseInt(t.timeout,10);if(Number.isNaN(Ee)){i(new Im("error trying to parse `config.timeout` to int",Im.ERR_BAD_OPTION_VALUE,t,P));return}P.setTimeout(Ee,function(){if(m)return;let gt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",xe=t.transitional||Zka;t.timeoutErrorMessage&&(gt=t.timeoutErrorMessage),i(new Im(gt,xe.clarifyTimeoutError?Im.ETIMEDOUT:Im.ECONNABORTED,t,P)),T()})}if(Yf.isStream(o)){let Ee=!1,St=!1;o.on("end",()=>{Ee=!0}),o.once("error",gt=>{St=!0,P.destroy(gt)}),o.on("close",()=>{!Ee&&!St&&T(new Knt("Request stream has been aborted",t,P))}),o.pipe(P)}else P.end(o)})};var m1y=e8.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,e8.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(e8.origin),e8.navigator&&/(msie|trident)/i.test(e8.navigator.userAgent)):()=>!0;var O1y=e8.hasStandardBrowserEnv?{write(e,t,r,n,i,a){let o=[e+"="+encodeURIComponent(t)];Yf.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Yf.isString(n)&&o.push("path="+n),Yf.isString(i)&&o.push("domain="+i),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 A1y=e=>e instanceof x$?{...e}:e;function gqr(e,t){t=t||{};let r={};function n(s,u,l,m){return Yf.isPlainObject(s)&&Yf.isPlainObject(u)?Yf.merge.call({caseless:m},s,u):Yf.isPlainObject(u)?Yf.merge({},u):Yf.isArray(u)?u.slice():u}function i(s,u,l,m){if(Yf.isUndefined(u)){if(!Yf.isUndefined(s))return n(void 0,s,l,m)}else return n(s,u,l,m)}function a(s,u){if(!Yf.isUndefined(u))return n(void 0,u)}function o(s,u){if(Yf.isUndefined(u)){if(!Yf.isUndefined(s))return n(void 0,s)}else return n(void 0,u)}function c(s,u,l){if(l in t)return n(s,u);if(l in e)return n(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,l)=>i(A1y(s),A1y(u),l,!0)};return Yf.forEach(Object.keys({...e,...t}),function(u){let l=d[u]||i,m=l(e[u],t[u],u);Yf.isUndefined(m)&&l!==c||(r[u]=m)}),r}var HSs=e=>{let t=gqr({},e),{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=x$.from(o),t.url=gca(mca(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Yf.isFormData(r)){if(e8.hasStandardBrowserEnv||e8.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(Yf.isFunction(r.getHeaders)){let d=r.getHeaders(),s=["content-type","content-length"];Object.entries(d).forEach(([u,l])=>{s.includes(u.toLowerCase())&&o.set(u,l)})}}if(e8.hasStandardBrowserEnv&&(n&&Yf.isFunction(n)&&(n=n(t)),n||n!==!1&&m1y(t.url))){let d=i&&a&&O1y.read(a);d&&o.set(i,d)}return t};var QlC=typeof XMLHttpRequest<"u",P1y=QlC&&function(e){return new Promise(function(r,n){let i=HSs(e),a=i.data,o=x$.from(i.headers).normalize(),{responseType:c,onUploadProgress:d,onDownloadProgress:s}=i,u,l,m,A,P;function C(){A&&A(),P&&P(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let M=new XMLHttpRequest;M.open(i.method.toUpperCase(),i.url,!0),M.timeout=i.timeout;function T(){if(!M)return;let U=x$.from("getAllResponseHeaders"in M&&M.getAllResponseHeaders()),V={data:!c||c==="text"||c==="json"?M.responseText:M.response,status:M.status,statusText:M.statusText,headers:U,config:e,request:M};YUr(function(re){r(re),C()},function(re){n(re),C()},V),M=null}"onloadend"in M?M.onloadend=T:M.onreadystatechange=function(){!M||M.readyState!==4||M.status===0&&!(M.responseURL&&M.responseURL.indexOf("file:")===0)||setTimeout(T)},M.onabort=function(){M&&(n(new Im("Request aborted",Im.ECONNABORTED,e,M)),M=null)},M.onerror=function(R){let V=R&&R.message?R.message:"Network Error",Y=new Im(V,Im.ERR_NETWORK,e,M);Y.event=R||null,n(Y),M=null},M.ontimeout=function(){let R=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",V=i.transitional||Zka;i.timeoutErrorMessage&&(R=i.timeoutErrorMessage),n(new Im(R,V.clarifyTimeoutError?Im.ETIMEDOUT:Im.ECONNABORTED,e,M)),M=null},a===void 0&&o.setContentType(null),"setRequestHeader"in M&&Yf.forEach(o.toJSON(),function(R,V){M.setRequestHeader(V,R)}),Yf.isUndefined(i.withCredentials)||(M.withCredentials=!!i.withCredentials),c&&c!=="json"&&(M.responseType=i.responseType),s&&([m,P]=QAi(s,!0),M.addEventListener("progress",m)),d&&M.upload&&([l,A]=QAi(d),M.upload.addEventListener("progress",l),M.upload.addEventListener("loadend",A)),(i.cancelToken||i.signal)&&(u=U=>{M&&(n(!U||U.type?new Knt(null,e,M):U),M.abort(),M=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));let z=LKo(i.url);if(z&&e8.protocols.indexOf(z)===-1){n(new Im("Unsupported protocol "+z+":",Im.ERR_BAD_REQUEST,e));return}M.send(a||null)})};var LlC=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let n=new AbortController,i,a=function(s){if(!i){i=!0,c();let u=s instanceof Error?s:this.reason;n.abort(u instanceof Im?u:new Knt(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new Im(`timeout ${t} of ms exceeded`,Im.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}=n;return d.unsubscribe=()=>Yf.asap(c),d}},w1y=LlC;var UlC=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let n=0,i;for(;n<r;)i=n+t,yield e.slice(n,i),n=i},VlC=async function*(e,t){for await(let r of WlC(e))yield*UlC(r,t)},WlC=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;yield n}}finally{await t.cancel()}},C0f=(e,t,r,n)=>{let i=VlC(e,t),a=0,o,c=d=>{o||(o=!0,n&&n(d))};return new ReadableStream({async pull(d){try{let{done:s,value:u}=await i.next();if(s){c(),d.close();return}let l=u.byteLength;if(r){let m=a+=l;r(m)}d.enqueue(new Uint8Array(u))}catch(s){throw c(s),s}},cancel(d){return c(d),i.return()}},{highWaterMark:2})};var j1y=64*1024,{isFunction:GSs}=Yf,HlC=(({Request:e,Response:t})=>({Request:e,Response:t}))(Yf.global),{ReadableStream:E1y,TextEncoder:S1y}=Yf.global,D1y=(e,...t)=>{try{return!!e(...t)}catch{return!1}},GlC=e=>{e=Yf.merge.call({skipUndefined:!0},HlC,e);let{fetch:t,Request:r,Response:n}=e,i=t?GSs(t):typeof fetch=="function",a=GSs(r),o=GSs(n);if(!i)return!1;let c=i&&GSs(E1y),d=i&&(typeof S1y=="function"?(P=>C=>P.encode(C))(new S1y):async P=>new Uint8Array(await new r(P).arrayBuffer())),s=a&&c&&D1y(()=>{let P=!1,C=new r(e8.origin,{body:new E1y,method:"POST",get duplex(){return P=!0,"half"}}).headers.has("Content-Type");return P&&!C}),u=o&&c&&D1y(()=>Yf.isReadableStream(new n("").body)),l={stream:u&&(P=>P.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(P=>{!l[P]&&(l[P]=(C,M)=>{let T=C&&C[P];if(T)return T.call(C);throw new Im(`Response type '${P}' is not supported`,Im.ERR_NOT_SUPPORT,M)})});let m=async P=>{if(P==null)return 0;if(Yf.isBlob(P))return P.size;if(Yf.isSpecCompliantForm(P))return(await new r(e8.origin,{method:"POST",body:P}).arrayBuffer()).byteLength;if(Yf.isArrayBufferView(P)||Yf.isArrayBuffer(P))return P.byteLength;if(Yf.isURLSearchParams(P)&&(P=P+""),Yf.isString(P))return(await d(P)).byteLength},A=async(P,C)=>{let M=Yf.toFiniteNumber(P.getContentLength());return M??m(C)};return async P=>{let{url:C,method:M,data:T,signal:z,cancelToken:U,timeout:R,onDownloadProgress:V,onUploadProgress:Y,responseType:re,headers:X,withCredentials:ee="same-origin",fetchOptions:ne}=HSs(P),me=t||fetch;re=re?(re+"").toLowerCase():"text";let be=w1y([z,U&&U.toAbortSignal()],R),Ae=null,he=be&&be.unsubscribe&&(()=>{be.unsubscribe()}),Me;try{if(Y&&s&&M!=="get"&&M!=="head"&&(Me=await A(X,T))!==0){let Ie=new r(C,{method:"POST",body:T,duplex:"half"}),Ut;if(Yf.isFormData(T)&&(Ut=Ie.headers.get("content-type"))&&X.setContentType(Ut),Ie.body){let[et,Xt]=teo(Me,QAi(reo(Y)));T=C0f(Ie.body,j1y,et,Xt)}}Yf.isString(ee)||(ee=ee?"include":"omit");let Be=a&&"credentials"in r.prototype,Ee={...ne,signal:be,method:M.toUpperCase(),headers:X.normalize().toJSON(),body:T,duplex:"half",credentials:Be?ee:void 0};Ae=a&&new r(C,Ee);let St=await(a?me(Ae,ne):me(C,Ee)),gt=u&&(re==="stream"||re==="response");if(u&&(V||gt&&he)){let Ie={};["status","statusText","headers"].forEach(Bt=>{Ie[Bt]=St[Bt]});let Ut=Yf.toFiniteNumber(St.headers.get("content-length")),[et,Xt]=V&&teo(Ut,QAi(reo(V),!0))||[];St=new n(C0f(St.body,j1y,et,()=>{Xt&&Xt(),he&&he()}),Ie)}re=re||"text";let xe=await l[Yf.findKey(l,re)||"text"](St,P);return!gt&&he&&he(),await new Promise((Ie,Ut)=>{YUr(Ie,Ut,{data:xe,headers:x$.from(St.headers),status:St.status,statusText:St.statusText,config:P,request:Ae})})}catch(Be){throw he&&he(),Be&&Be.name==="TypeError"&&/Load failed|fetch/i.test(Be.message)?Object.assign(new Im("Network Error",Im.ERR_NETWORK,P,Ae),{cause:Be.cause||Be}):Im.from(Be,Be&&Be.code,P,Ae)}}},JlC=new Map,I0f=e=>{let t=e?e.env:{},{fetch:r,Request:n,Response:i}=t,a=[n,i,r],o=a.length,c=o,d,s,u=JlC;for(;c--;)d=a[c],s=u.get(d),s===void 0&&u.set(d,s=c?new Map:GlC(t)),u=s;return s},kFU=I0f();var M0f={http:g1y,xhr:P1y,fetch:{get:I0f}};Yf.forEach(M0f,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var C1y=e=>`- ${e}`,$lC=e=>Yf.isFunction(e)||e===null||e===!1,JSs={getAdapter:(e,t)=>{e=Yf.isArray(e)?e:[e];let{length:r}=e,n,i,a={};for(let o=0;o<r;o++){n=e[o];let c;if(i=n,!$lC(n)&&(i=M0f[(c=String(n)).toLowerCase()],i===void 0))throw new Im(`Unknown adapter '${c}'`);if(i&&(Yf.isFunction(i)||(i=i.get(t))))break;a[c||"#"+o]=i}if(!i){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 :
@@ -2399,7 +2399,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
2399
2399
  Run ${od.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
2400
2400
  Run ${od.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),ieo(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function WTf({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!jGy(e))return;let i=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)i+=`
2401
2401
  ${await HVC(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+od.dim(c.currentVersion)+od.reset(" \u2192 ")+od.green(c.latestVersion);return i+=`
2402
- `,n?ieo(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function HVC(e){let r=await new wGy.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 GVC({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await SGy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let m=Vzi(u.name,l),A=await ULr({generatorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:a,context:l});A!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),c}let o={type:"multiApi",versions:{}};return await SGy({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 l=Vzi(s.name,u),m=await ULr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:i,includeMajor:a,context:u});m!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:m})},generatorFilter:r,groupFilter:n}),o}async function SGy({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await YTr({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(!(c==null||c.groups==null)){for(let d of c.groups)if(!(i!=null&&d.groupName!==i))for(let s of d.generators)n!=null&&s.name!==n||await r(a.workspaceName,d.groupName,s,o)}})}))}function DGy(e,t,r){let n=[];for(let[i,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${i} has an upgrade available...`);let d=b3e(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),n.push({generatorName:o,generatorGroup:i,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return n}async function lFs({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let o=[];if(e!=null){let c=await GVC({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...DGy(s,d,t.logger));else o.push(...DGy(c.versions,void 0,t.logger))}return o}var Tfa=class extends Error{response;request;options;constructor(t,r,n){let i=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${i} ${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=n}};var HTf=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";if(r&&n)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(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return e&&!t})(),CGy=typeof globalThis.AbortController=="function",fFs=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",IGy=typeof globalThis.ReadableStream=="function",MGy=typeof globalThis.FormData=="function",dFs=["get","post","put","patch","head","delete"],JVC=()=>{};JVC();var BGy={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},pFs=2147483647,TGy=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,_Fs=Symbol("stop"),qGy={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},RGy={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,duplex:!0};var KVC=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,n]of e)t+=TGy,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof n=="string"?new TextEncoder().encode(n).length:n.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},NGy=(e,t,r)=>{let n,i=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),n){i+=n.byteLength;let c=t===0?0:i/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,i),transferredBytes:i},n)}n=a},flush(){n&&(i+=n.byteLength,r?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},n))}}))},FGy=(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(NGy(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},xGy=(e,t,r)=>{if(!e.body)return e;let n=KVC(r??e.body);return new Request(e,{duplex:"half",body:NGy(e.body,n,t)})};var qfa=e=>e!==null&&typeof e=="object";var TZo=(...e)=>{for(let t of e)if((!qfa(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return KTf({},...e)},GTf=(e={},t={})=>{let r=new globalThis.Headers(e),n=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[a,o]of i.entries())n&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function hFs(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:KTf(e[r]??[],t[r]??[])}var JTf=(e={},t={})=>({beforeRequest:hFs(e,t,"beforeRequest"),beforeRetry:hFs(e,t,"beforeRetry"),afterResponse:hFs(e,t,"afterResponse"),beforeError:hFs(e,t,"beforeError")}),$VC=(e,t)=>{let r=new URLSearchParams;for(let n of[e,t])if(n!==void 0)if(n instanceof URLSearchParams)for(let[i,a]of n.entries())r.append(i,a);else if(Array.isArray(n))for(let i of n){if(!Array.isArray(i)||i.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");r.append(String(i[0]),String(i[1]))}else if(qfa(n))for(let[i,a]of Object.entries(n))a!==void 0&&r.append(i,String(a));else{let i=new URLSearchParams(n);for(let[a,o]of i.entries())r.append(a,o)}return r},KTf=(...e)=>{let t={},r={},n={},i,a=[];for(let o of e)if(Array.isArray(o))Array.isArray(t)||(t=[]),t=[...t,...o];else if(qfa(o)){for(let[c,d]of Object.entries(o)){if(c==="signal"&&d instanceof globalThis.AbortSignal){a.push(d);continue}if(c==="searchParams"){d==null?i=void 0:i=i===void 0?d:$VC(i,d);continue}qfa(d)&&c in t&&(d=KTf(t[c],d)),t={...t,[c]:d}}qfa(o.hooks)&&(n=JTf(n,o.hooks),t.hooks=n),qfa(o.headers)&&(r=GTf(r,o.headers),t.headers=r)}return i!==void 0&&(t.searchParams=i),a.length>0&&(a.length===1?t.signal=a[0]:fFs?t.signal=AbortSignal.any(a):t.signal=a.at(-1)),t};var QGy=e=>dFs.includes(e)?e.toUpperCase():e,YVC=["get","put","head","delete","options","trace"],XVC=[408,413,429,500,502,503,504],ZVC=[413,429,503],zGy={limit:2,methods:YVC,statusCodes:XVC,afterStatusCodes:ZVC,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},LGy=(e={})=>{if(typeof e=="number")return{...zGy,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{...zGy,...e}};var Rfa=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};async function $Tf(e,t,r,n){return new Promise((i,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new Rfa(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function YTf(e,{signal:t}){return new Promise((r,n)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(a),n(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e)})}var UGy=(e,t)=>{let r={};for(let n in t)!(n in RGy)&&!(n in qGy)&&!(n in e)&&(r[n]=t[n]);return r},VGy=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;function WGy(e){return e instanceof Tfa||e?.name===Tfa.name}function HGy(e){return e instanceof Rfa||e?.name===Rfa.name}var qZo=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>pFs)throw new RangeError(`The \`timeout\` option cannot be greater than ${pFs}`);await Promise.resolve();let c=await n._fetch();for(let d of n._options.hooks.afterResponse){let s=await d(n.request,n.#r(),n._decorateResponse(c.clone()),{retryCount:n._retryCount});s instanceof globalThis.Response&&(c=s)}if(n._decorateResponse(c),!c.ok&&n._options.throwHttpErrors){let d=new Tfa(c,n.request,n.#r());for(let s of n._options.hooks.beforeError)d=await s(d,{retryCount:n._retryCount});throw d}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!IGy)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return FGy(c.clone(),n._options.onDownloadProgress)}return c},o=(n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i()).finally(async()=>{let c=n._originalRequest,d=[];c&&!c.bodyUsed&&d.push(c.body?.cancel()),n.request.bodyUsed||d.push(n.request.body?.cancel()),await Promise.all(d)});for(let[c,d]of Object.entries(BGy))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{n.request.headers.set("accept",n.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;#t;constructor(t,r={}){if(this._input=t,this._options={...r,headers:GTf(this._input.headers,r.headers),hooks:JTf({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:QGy(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:LGy(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(CGy&&fFs){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}HTf&&(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"));let n=r.headers&&new globalThis.Headers(r.headers).has("content-type");if(this._input instanceof globalThis.Request&&(MGy&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!n&&this._options.headers.delete("content-type"),this.request=new globalThis.Request(this._input,this._options),VGy(this._options.searchParams)){let a="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),o=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,a);this.request=new globalThis.Request(new globalThis.Request(o,{...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(!HTf)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=xGy(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||HGy(t))throw t;if(WGy(t)){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let n=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(n&&this._options.retry.afterStatusCodes.includes(t.response.status)){let i=Number(n)*1e3;Number.isNaN(i)?i=Date.parse(n)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());let a=this._options.retry.maxRetryAfter??i;return i<a?i: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 n=Math.min(this._calculateRetryDelay(r),pFs);if(this._retryCount<1)throw r;await YTf(n,{signal:this._options.signal});for(let i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this.#r(),error:r,retryCount:this._retryCount})===_Fs)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let n=await r(this.request,this.#r(),{retryCount:this._retryCount});if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=UGy(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):$Tf(this._originalRequest,t,this.abortController,this._options)}#r(){if(!this.#t){let{hooks:t,...r}=this._options;this.#t=Object.freeze(r)}return this.#t}};var XTf=e=>{let t=(r,n)=>qZo.create(r,TZo(e,n));for(let r of dFs)t[r]=(n,i)=>qZo.create(n,TZo(e,i,{method:r}));return t.create=r=>XTf(TZo(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),XTf(TZo(e,r))),t.stop=_Fs,t},kVC=XTf(),GGy=kVC;var hJy=fa(_Jy(),1);function rqf(e){let t=(0,hJy.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var cKy=fa(sKy(),1),lKy=fa(FQr(),1),hqf=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},yqf=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function vqf(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??rqf(i),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,cKy.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 GGy(o,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new hqf(e):l}if(t.allVersions)return s;let u=new yqf(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(n&&!l)for(let[A,P]of Object.entries(s.versions))P.deprecated&&delete s.versions[A];if(!l){let A=Object.keys(s.versions);if(r=lKy.default.maxSatisfying(A,r),!r)throw u}let{time:m}=s;if(s=s.versions[r],s.time=m,!s)throw u}return s}async function QZo(e,t){let{version:r}=await vqf(e.toLowerCase(),t);return r}async function C8i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:QZo(e.packageName,{version:t?"prerelease":"latest"})}var fKy=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],SFs=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=eE.Info;isLocal;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new cFs(t,r),this.isLocal=n??!1;let i=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(i==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.94.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${od.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new Aie}failWithoutThrowing(t,r){this.didSucceed=!1,oFs({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await Kka()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await EGy({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
2402
+ `,n?ieo(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function HVC(e){let r=await new wGy.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 GVC({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await SGy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let m=Vzi(u.name,l),A=await ULr({generatorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:a,context:l});A!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),c}let o={type:"multiApi",versions:{}};return await SGy({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 l=Vzi(s.name,u),m=await ULr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:i,includeMajor:a,context:u});m!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:m})},generatorFilter:r,groupFilter:n}),o}async function SGy({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await YTr({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(!(c==null||c.groups==null)){for(let d of c.groups)if(!(i!=null&&d.groupName!==i))for(let s of d.generators)n!=null&&s.name!==n||await r(a.workspaceName,d.groupName,s,o)}})}))}function DGy(e,t,r){let n=[];for(let[i,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${i} has an upgrade available...`);let d=b3e(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),n.push({generatorName:o,generatorGroup:i,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return n}async function lFs({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let o=[];if(e!=null){let c=await GVC({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...DGy(s,d,t.logger));else o.push(...DGy(c.versions,void 0,t.logger))}return o}var Tfa=class extends Error{response;request;options;constructor(t,r,n){let i=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${i} ${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=n}};var HTf=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";if(r&&n)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(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return e&&!t})(),CGy=typeof globalThis.AbortController=="function",fFs=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",IGy=typeof globalThis.ReadableStream=="function",MGy=typeof globalThis.FormData=="function",dFs=["get","post","put","patch","head","delete"],JVC=()=>{};JVC();var BGy={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},pFs=2147483647,TGy=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,_Fs=Symbol("stop"),qGy={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},RGy={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,duplex:!0};var KVC=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,n]of e)t+=TGy,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof n=="string"?new TextEncoder().encode(n).length:n.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},NGy=(e,t,r)=>{let n,i=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),n){i+=n.byteLength;let c=t===0?0:i/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,i),transferredBytes:i},n)}n=a},flush(){n&&(i+=n.byteLength,r?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},n))}}))},FGy=(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(NGy(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},xGy=(e,t,r)=>{if(!e.body)return e;let n=KVC(r??e.body);return new Request(e,{duplex:"half",body:NGy(e.body,n,t)})};var qfa=e=>e!==null&&typeof e=="object";var TZo=(...e)=>{for(let t of e)if((!qfa(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return KTf({},...e)},GTf=(e={},t={})=>{let r=new globalThis.Headers(e),n=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[a,o]of i.entries())n&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function hFs(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:KTf(e[r]??[],t[r]??[])}var JTf=(e={},t={})=>({beforeRequest:hFs(e,t,"beforeRequest"),beforeRetry:hFs(e,t,"beforeRetry"),afterResponse:hFs(e,t,"afterResponse"),beforeError:hFs(e,t,"beforeError")}),$VC=(e,t)=>{let r=new URLSearchParams;for(let n of[e,t])if(n!==void 0)if(n instanceof URLSearchParams)for(let[i,a]of n.entries())r.append(i,a);else if(Array.isArray(n))for(let i of n){if(!Array.isArray(i)||i.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");r.append(String(i[0]),String(i[1]))}else if(qfa(n))for(let[i,a]of Object.entries(n))a!==void 0&&r.append(i,String(a));else{let i=new URLSearchParams(n);for(let[a,o]of i.entries())r.append(a,o)}return r},KTf=(...e)=>{let t={},r={},n={},i,a=[];for(let o of e)if(Array.isArray(o))Array.isArray(t)||(t=[]),t=[...t,...o];else if(qfa(o)){for(let[c,d]of Object.entries(o)){if(c==="signal"&&d instanceof globalThis.AbortSignal){a.push(d);continue}if(c==="searchParams"){d==null?i=void 0:i=i===void 0?d:$VC(i,d);continue}qfa(d)&&c in t&&(d=KTf(t[c],d)),t={...t,[c]:d}}qfa(o.hooks)&&(n=JTf(n,o.hooks),t.hooks=n),qfa(o.headers)&&(r=GTf(r,o.headers),t.headers=r)}return i!==void 0&&(t.searchParams=i),a.length>0&&(a.length===1?t.signal=a[0]:fFs?t.signal=AbortSignal.any(a):t.signal=a.at(-1)),t};var QGy=e=>dFs.includes(e)?e.toUpperCase():e,YVC=["get","put","head","delete","options","trace"],XVC=[408,413,429,500,502,503,504],ZVC=[413,429,503],zGy={limit:2,methods:YVC,statusCodes:XVC,afterStatusCodes:ZVC,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},LGy=(e={})=>{if(typeof e=="number")return{...zGy,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{...zGy,...e}};var Rfa=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};async function $Tf(e,t,r,n){return new Promise((i,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new Rfa(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function YTf(e,{signal:t}){return new Promise((r,n)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(a),n(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e)})}var UGy=(e,t)=>{let r={};for(let n in t)!(n in RGy)&&!(n in qGy)&&!(n in e)&&(r[n]=t[n]);return r},VGy=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;function WGy(e){return e instanceof Tfa||e?.name===Tfa.name}function HGy(e){return e instanceof Rfa||e?.name===Rfa.name}var qZo=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>pFs)throw new RangeError(`The \`timeout\` option cannot be greater than ${pFs}`);await Promise.resolve();let c=await n._fetch();for(let d of n._options.hooks.afterResponse){let s=await d(n.request,n.#r(),n._decorateResponse(c.clone()),{retryCount:n._retryCount});s instanceof globalThis.Response&&(c=s)}if(n._decorateResponse(c),!c.ok&&n._options.throwHttpErrors){let d=new Tfa(c,n.request,n.#r());for(let s of n._options.hooks.beforeError)d=await s(d,{retryCount:n._retryCount});throw d}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!IGy)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return FGy(c.clone(),n._options.onDownloadProgress)}return c},o=(n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i()).finally(async()=>{let c=n._originalRequest,d=[];c&&!c.bodyUsed&&d.push(c.body?.cancel()),n.request.bodyUsed||d.push(n.request.body?.cancel()),await Promise.all(d)});for(let[c,d]of Object.entries(BGy))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{n.request.headers.set("accept",n.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;#t;constructor(t,r={}){if(this._input=t,this._options={...r,headers:GTf(this._input.headers,r.headers),hooks:JTf({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:QGy(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:LGy(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(CGy&&fFs){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}HTf&&(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"));let n=r.headers&&new globalThis.Headers(r.headers).has("content-type");if(this._input instanceof globalThis.Request&&(MGy&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!n&&this._options.headers.delete("content-type"),this.request=new globalThis.Request(this._input,this._options),VGy(this._options.searchParams)){let a="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),o=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,a);this.request=new globalThis.Request(new globalThis.Request(o,{...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(!HTf)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=xGy(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||HGy(t))throw t;if(WGy(t)){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let n=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(n&&this._options.retry.afterStatusCodes.includes(t.response.status)){let i=Number(n)*1e3;Number.isNaN(i)?i=Date.parse(n)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());let a=this._options.retry.maxRetryAfter??i;return i<a?i: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 n=Math.min(this._calculateRetryDelay(r),pFs);if(this._retryCount<1)throw r;await YTf(n,{signal:this._options.signal});for(let i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this.#r(),error:r,retryCount:this._retryCount})===_Fs)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let n=await r(this.request,this.#r(),{retryCount:this._retryCount});if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=UGy(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):$Tf(this._originalRequest,t,this.abortController,this._options)}#r(){if(!this.#t){let{hooks:t,...r}=this._options;this.#t=Object.freeze(r)}return this.#t}};var XTf=e=>{let t=(r,n)=>qZo.create(r,TZo(e,n));for(let r of dFs)t[r]=(n,i)=>qZo.create(n,TZo(e,i,{method:r}));return t.create=r=>XTf(TZo(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),XTf(TZo(e,r))),t.stop=_Fs,t},kVC=XTf(),GGy=kVC;var hJy=fa(_Jy(),1);function rqf(e){let t=(0,hJy.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var cKy=fa(sKy(),1),lKy=fa(FQr(),1),hqf=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},yqf=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function vqf(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??rqf(i),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,cKy.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 GGy(o,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new hqf(e):l}if(t.allVersions)return s;let u=new yqf(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(n&&!l)for(let[A,P]of Object.entries(s.versions))P.deprecated&&delete s.versions[A];if(!l){let A=Object.keys(s.versions);if(r=lKy.default.maxSatisfying(A,r),!r)throw u}let{time:m}=s;if(s=s.versions[r],s.time=m,!s)throw u}return s}async function QZo(e,t){let{version:r}=await vqf(e.toLowerCase(),t);return r}async function C8i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:QZo(e.packageName,{version:t?"prerelease":"latest"})}var fKy=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],SFs=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=eE.Info;isLocal;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new cFs(t,r),this.isLocal=n??!1;let i=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(i==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.94.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${od.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new Aie}failWithoutThrowing(t,r){this.didSucceed=!1,oFs({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await Kka()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await EGy({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
2403
2403
  `)||(r+=`
2404
2404
  `),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=WYl(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.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 SZo(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 n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(a){throw a.message.includes("globalThis")?(n.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),n.failWithoutThrowing()):n.failWithoutThrowing(void 0,a),new Aie}finally{n.finish()}return i}async instrumentPostHogEvent(t){this.isLocal||(await Kka()).sendEvent(t)}logger=e5r((t,...r)=>this.log(t,...r));stderr=e5r((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=dKy(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?dKy(this.longestWorkspaceName):r).length,i=r.padEnd(n),a=fKy[this.numTasks++%fKy.length],o=od.hex(a)(i);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===MV.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 n=t.filter(i=>ezi.indexOf(i.level)>=ezi.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===eE.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 C8i({cliEnvironment:this.environment,includePreReleases:t}),n=b3e(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},a=await lFs({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await TTf({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:od.yellow("?"),style:{answer:i=>od.cyan(i),message:i=>od.bold(i),highlight:i=>od.cyan(i)}}})}catch(n){throw n?.name==="ExitPromptError"?(this.logger.info(`
2405
2405
  Cancelled by user.`),new Aie):n}}async getInput(t){return await ITf({message:t.message,default:t.default})}};function dKy(e){return`[${e}]:`}var Vqr=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:n,absoluteFilePath:i,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=n,this.absoluteFilePath=i,this.changelog=a}};var Oit=class extends Vqr{definition;sources;type="fern";constructor({definition:t,sources:r,...n}){super(n),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var Dyt={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,wrapReferencesToNullableInOptional:!0,coerceOptionalSchemasToNullable:!0,groupEnvironmentsByHost:!1};function LZo({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??Dyt.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??Dyt.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??Dyt.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??Dyt.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??Dyt.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??Dyt.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??Dyt.inlinePathParameters,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??Dyt.useBytesForBinaryResponse,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??Dyt.respectForwardCompatibleEnums,wrapReferencesToNullableInOptional:t?.wrapReferencesToNullableInOptional??e?.wrapReferencesToNullableInOptional??Dyt.wrapReferencesToNullableInOptional,coerceOptionalSchemasToNullable:t?.coerceOptionalSchemasToNullable??e?.coerceOptionalSchemasToNullable??Dyt.coerceOptionalSchemasToNullable,groupEnvironmentsByHost:t?.groupEnvironmentsByHost??e?.groupEnvironmentsByHost??Dyt.groupEnvironmentsByHost}}var Twe={openapi:e=>({...e,type:"openapi",_visit:function(t){return Twe._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Twe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var tio={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return tio._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var npe={basic:e=>({...e,type:"basic",_visit:function(t){return npe._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return npe._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return npe._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return npe._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return npe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var CS={primitive:e=>({value:e,type:"primitive",_visit:function(t){return CS._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return CS._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return CS._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return CS._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return CS._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return CS._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return CS._visit(this,t)}}),null:e=>({...e,type:"null",_visit:function(t){return CS._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return CS._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"null":return t.null(e);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var SO={int:e=>({value:e,type:"int",_visit:function(t){return SO._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return SO._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return SO._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return SO._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return SO._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return SO._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return SO._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return SO._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return SO._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return SO._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return SO._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var I8i={boolean:e=>({value:e,type:"boolean",_visit:function(t){return I8i._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return I8i._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var M8i={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return M8i._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return M8i._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var DFs={};ff(DFs,{Availability:()=>ipe,CustomCodeSample:()=>UVr,EndpointExample:()=>Cyt,EndpointResponseExample:()=>Iyt,HttpMethod:()=>ope,LiteralSchemaValue:()=>YV,MultipartRequestPropertyEncoding:()=>mqf,MultipartSchema:()=>VVr,OneOfSchema:()=>WVr,Pagination:()=>Ait,PrimitiveSchemaValue:()=>Iq,Request:()=>Wqr,Response:()=>nge,RetriesConfiguration:()=>UZo,Schema:()=>a1,SupportedSdkLanguage:()=>ape,WebhookHttpMethod:()=>gqf,WebsocketMessageOrigin:()=>bqf});var bqf={Client:"client",Server:"server",_visit:(e,t)=>{switch(e){case bqf.Client:return t.client();case bqf.Server:return t.server();default:return t._other()}}};var gqf={Get:"GET",Post:"POST",_visit:(e,t)=>{switch(e){case gqf.Get:return t.get();case gqf.Post:return t.post();default:return t._other()}}};var ipe={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case ipe.GenerallyAvailable:return t.generallyAvailable();case ipe.Beta:return t.beta();case ipe.Deprecated:return t.deprecated();default:return t._other()}}};var UZo={disabled:e=>({value:e,type:"disabled",_visit:function(t){return UZo._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"disabled":return t.disabled(e.value);default:return t._other(e)}}};var Ait={cursor:e=>({...e,type:"cursor",_visit:function(t){return Ait._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return Ait._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return Ait._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);default:return t._other(e)}}};var UVr={language:e=>({...e,type:"language",_visit:function(t){return UVr._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return UVr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var ape={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",_visit:(e,t)=>{switch(e){case ape.Curl:return t.curl();case ape.Python:return t.python();case ape.Javascript:return t.javascript();case ape.Typescript:return t.typescript();case ape.Go:return t.go();case ape.Ruby:return t.ruby();case ape.Csharp:return t.csharp();case ape.Java:return t.java();case ape.Js:return t.js();case ape.Node:return t.node();case ape.Ts:return t.ts();case ape.Nodets:return t.nodets();case ape.Golang:return t.golang();case ape.Dotnet:return t.dotnet();case ape.Jvm:return t.jvm();default:return t._other()}}};var Cyt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return Cyt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return Cyt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var Iyt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return Iyt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return Iyt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var ope={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case ope.Get:return t.get();case ope.Post:return t.post();case ope.Put:return t.put();case ope.Patch:return t.patch();case ope.Delete:return t.delete();case ope.Head:return t.head();case ope.Options:return t.options();case ope.Trace:return t.trace();default:return t._other()}}};var Wqr={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Wqr._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Wqr._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Wqr._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return Wqr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var mqf={Json:"json",Form:"form",_visit:(e,t)=>{switch(e){case mqf.Json:return t.json();case mqf.Form:return t.form();default:return t._other()}}};var VVr={file:e=>({...e,type:"file",_visit:function(t){return VVr._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return VVr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var nge={file:e=>({...e,type:"file",_visit:function(t){return nge._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return nge._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return nge._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return nge._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return nge._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return nge._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return nge._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var a1={primitive:e=>({...e,type:"primitive",_visit:function(t){return a1._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return a1._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return a1._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return a1._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return a1._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return a1._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return a1._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return a1._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return a1._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return a1._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return a1._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Iq={int:e=>({...e,type:"int",_visit:function(t){return Iq._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Iq._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return Iq._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return Iq._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return Iq._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return Iq._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Iq._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return Iq._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return Iq._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return Iq._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Iq._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var YV={boolean:e=>({value:e,type:"boolean",_visit:function(t){return YV._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return YV._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var WVr={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return WVr._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return WVr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var wIe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return wIe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return wIe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return wIe._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return wIe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var c9={file:e=>({...e,type:"file",_visit:function(t){return c9._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return c9._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return c9._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return c9._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return c9._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return c9._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return c9._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Ah={primitive:e=>({...e,type:"primitive",_visit:function(t){return Ah._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Ah._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Ah._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Ah._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Ah._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Ah._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Ah._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Ah._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Ah._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Ah._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Ah._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Pit={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Pit._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Pit._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var W0={int:e=>({...e,type:"int",_visit:function(t){return W0._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return W0._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return W0._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return W0._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return W0._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return W0._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return W0._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return W0._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return W0._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return W0._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return W0._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var Nj={};ff(Nj,{AllOfPropertyConflict:()=>Sio,ArraySchema:()=>Hxs,ArraySchemaWithExample:()=>A3s,Availability:()=>xFs,Base64WithExample:()=>v3s,BasicSecurityScheme:()=>QFs,BearerSecurityScheme:()=>LFs,BooleanSchema:()=>zxs,BooleanWithExample:()=>b3s,BytesResponse:()=>vio,CasingOverrides:()=>WFs,CommonProperty:()=>kxs,CommonPropertyWithExample:()=>M3s,CursorPagination:()=>Axs,CustomCodeSample:()=>mxs,CustomCodeSampleLanguage:()=>vxs,CustomCodeSampleSdk:()=>gxs,CustomPagination:()=>wxs,DateWithExample:()=>y3s,DatetimeWithExample:()=>h3s,DiscriminatedOneOfSchema:()=>Xxs,DiscriminatedOneOfSchemaWithExample:()=>C3s,DoubleSchema:()=>Fxs,DoubleWithExample:()=>p3s,Encoding:()=>FFs,Endpoint:()=>jxs,EndpointExample:()=>Oio,EndpointResponseExample:()=>yxs,EndpointSdkName:()=>JVr,EndpointSecurity:()=>cio,EndpointWithExample:()=>UKy,EnumSchema:()=>oio,EnumSchemaWithExample:()=>m3s,EnumValue:()=>q8i,ErrorExample:()=>fxs,FernExample:()=>pxs,FileResponse:()=>hio,FileSchema:()=>nxs,FloatWithExample:()=>d3s,FormUrlEncodedRequest:()=>sxs,FullEndpointExample:()=>Oxs,FullExample:()=>BQ,FullObjectExample:()=>ZFs,FullOneOfExample:()=>exs,GlobalHeader:()=>Lxs,Header:()=>N8i,HeaderExample:()=>mio,HeaderSecurityScheme:()=>UFs,HeaderWithExample:()=>z8i,HttpEndpointServer:()=>bio,HttpError:()=>dxs,HttpErrorWithExample:()=>u3s,HttpMethod:()=>lio,IdempotencyHeader:()=>Uxs,Int64WithExample:()=>c3s,IntSchema:()=>Rxs,IntWithExample:()=>s3s,JsonRequest:()=>uxs,JsonRequestWithExample:()=>n3s,JsonResponse:()=>yio,JsonResponseWithExample:()=>Iio,KeyValuePair:()=>kFs,LiteralExample:()=>YFs,LiteralSchema:()=>Eio,LiteralSchemaValue:()=>Vxs,LongSchema:()=>Nxs,MapSchema:()=>Gxs,MapSchemaWithExample:()=>P3s,MultipartRequest:()=>_io,MultipartRequestProperty:()=>oxs,MultipartRequestPropertyEncoding:()=>axs,MultipartSchema:()=>ixs,NamedFullExample:()=>Byt,Namespace:()=>HFs,NamespaceId:()=>$Fs,NullExample:()=>XFs,NullableSchema:()=>Kxs,NullableSchemaWithExample:()=>j3s,OauthSecurityScheme:()=>JFs,ObjectProperty:()=>Yxs,ObjectPropertyConflictInfo:()=>Dio,ObjectPropertyWithExample:()=>D3s,ObjectSchema:()=>Wxs,ObjectSchemaWithExample:()=>E3s,OctetStreamRequest:()=>pio,OffsetPagination:()=>Pxs,OneOfSchema:()=>$xs,OneOfSchemaWithExample:()=>S3s,OpenApiIntermediateRepresentation:()=>QKy,OpenApiSource:()=>TFs,OptionalSchema:()=>Jxs,OptionalSchemaWithExample:()=>w3s,Pagination:()=>Aio,ParseFormUrlEncodedRequest:()=>i3s,ParseMultipartRequest:()=>r3s,ParseOctetStreamRequest:()=>t3s,PathParameter:()=>fio,PathParameterExample:()=>_xs,PathParameterWithExample:()=>e3s,PrimitiveExample:()=>sio,PrimitiveSchema:()=>x8i,PrimitiveSchemaValue:()=>Qxs,PrimitiveSchemaValueWithExample:()=>g3s,PrimitiveSchemaWithExample:()=>Mio,PropertyKey:()=>uio,ProtobufEncoding:()=>NFs,ProtobufSource:()=>qFs,QueryParameter:()=>dio,QueryParameterExample:()=>gio,QueryParameterWithExample:()=>Cio,QuerySecurityScheme:()=>VFs,ReferencedSchema:()=>KVr,Request:()=>cxs,RequestWithExample:()=>a3s,Response:()=>lxs,ResponseWithExample:()=>o3s,RetriesConfiguration:()=>Pio,Schema:()=>NI,SchemaId:()=>jIe,SchemaWithExample:()=>n6,Schemas:()=>qxs,SdkGroup:()=>GFs,SdkGroupInfo:()=>txs,SdkGroupName:()=>R8i,SecurityScheme:()=>KFs,SecuritySchemeId:()=>aio,Server:()=>GZo,Source:()=>RFs,StatusCode:()=>HVr,StreamingResponseExample:()=>hxs,StringSchema:()=>xxs,StringSchemaWithExample:()=>_3s,SupportedSdkLanguage:()=>bxs,Tag:()=>zFs,TagId:()=>EIe,Tags:()=>rxs,TextResponse:()=>F8i,Uint64WithExample:()=>f3s,UintWithExample:()=>l3s,UnDiscriminatedOneOfSchema:()=>Zxs,UnDiscriminatedOneOfSchemaWithExample:()=>I3s,UnknownSchemaWithExample:()=>O3s,Webhook:()=>Exs,WebhookExampleCall:()=>jio,WebhookHttpMethod:()=>wio,WebhookWithExample:()=>VKy,WebsocketChannel:()=>Txs,WebsocketHandshake:()=>Sxs,WebsocketHandshakeWithExample:()=>LKy,WebsocketMessageExample:()=>Mxs,WebsocketMessageOrigin:()=>Dxs,WebsocketMessageSchema:()=>Cxs,WebsocketServer:()=>Ixs,WebsocketSessionExample:()=>Bxs,WithAvailability:()=>QP,WithDescription:()=>nv,WithEncoding:()=>O3e,WithInline:()=>r6,WithName:()=>yD,WithNamespace:()=>IS,WithSdkGroupName:()=>BM,WithSdkMethodName:()=>GVr,WithSource:()=>iP,WithStatusCode:()=>Myt,WithTitle:()=>MM,commons:()=>jqf,example:()=>Eqf,finalIr:()=>Sqf,parseIr:()=>Dqf});var jqf={};ff(jqf,{BasicSecurityScheme:()=>QFs,BearerSecurityScheme:()=>LFs,Encoding:()=>FFs,HeaderSecurityScheme:()=>UFs,Namespace:()=>HFs,NamespaceId:()=>$Fs,OauthSecurityScheme:()=>JFs,OpenApiSource:()=>TFs,ProtobufEncoding:()=>NFs,ProtobufSource:()=>qFs,QuerySecurityScheme:()=>VFs,SchemaId:()=>jIe,SdkGroup:()=>GFs,SdkGroupName:()=>R8i,SecurityScheme:()=>KFs,SecuritySchemeId:()=>aio,Server:()=>GZo,Source:()=>RFs,StatusCode:()=>HVr,Tag:()=>zFs,TagId:()=>EIe,WithAvailability:()=>QP,WithDescription:()=>nv,WithEncoding:()=>O3e,WithInline:()=>r6,WithName:()=>yD,WithNamespace:()=>IS,WithSdkGroupName:()=>BM,WithSdkMethodName:()=>GVr,WithSource:()=>iP,WithStatusCode:()=>Myt,WithTitle:()=>MM});var Jr={};ff(Jr,{JsonError:()=>rio,ParseError:()=>nio,any:()=>SKy,bigint:()=>_Ky,boolean:()=>DKy,booleanLiteral:()=>EKy,date:()=>hKy,discriminant:()=>FKy,enum_:()=>IFs,getObjectLikeUtils:()=>Hqr,getObjectUtils:()=>Wfa,getSchemaUtils:()=>MQ,isProperty:()=>T8i,lazy:()=>yKy,lazyObject:()=>PKy,list:()=>BFs,number:()=>CKy,object:()=>MFs,objectWithoutOptionalProperties:()=>AKy,optional:()=>Oqf,property:()=>bKy,record:()=>TKy,set:()=>qKy,string:()=>IKy,stringLiteral:()=>jKy,transform:()=>Aqf,undiscriminatedUnion:()=>NKy,union:()=>zKy,unknown:()=>MKy,withParsedProperties:()=>wqf});var Mq={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function o8(e,t){return`Expected ${t}. Received ${aHC(e)}.`}function aHC(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function upe(e){return{...e,json:pKy(e.json),parse:pKy(e.parse)}}function pKy(e){return(t,r)=>{let n=e(t,r),{skipValidation:i=!1}=r??{};return!n.ok&&i?(console.warn(["Failed to validate.",...n.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
@@ -3041,7 +3041,7 @@ If you believe this is an error, please contact support@buildwithfern.com`),orgN
3041
3041
  `):void 0);for(let i of t.logs.slice(this.lengthOfLastLogs))this.context.logger.log(ktL(i.level),i.message);this.lengthOfLastLogs=t.logs.length;let n=i=>{this.context.logger.debug(`Generated files. ${nTi("View here",i,{fallback:(a,o)=>`${a}: ${o}`})}`)};return await t.status._visit({notStarted:Hc,running:Hc,failed:({message:i,s3PreSignedReadUrl:a})=>{a!=null&&n(a),this.context.failAndThrow(i)},finished:async i=>{if(i.s3PreSignedReadUrlV2!=null){n(i.s3PreSignedReadUrlV2);let a=this.getAbsolutePathToLocalOutput();a!=null&&await XtL({s3PreSignedReadUrl:i.s3PreSignedReadUrlV2,absolutePathToLocalOutput:a,context:this.context})}if(this.absolutePathToPreview==null)for(let a of r)this.context.logger.info(`Published ${a}`);this.#e=!0,this.#t=i.createdSnippets!=null?i.createdSnippets:!1,this.#r=i.snippetsS3PreSignedReadUrl},_other:()=>{this.context.logger.warn("Received unknown update type: "+t.status.type)}}),this.#e?{createdSnippets:this.#t,snippetsS3PreSignedReadUrl:this.#r}:void 0}getAbsolutePathToLocalOutput(){return this.absolutePathToPreview!=null?Jl(this.absolutePathToPreview,ys.of(X9_.default.basename(this.generatorInvocation.name))):this.generatorInvocation.absolutePathToLocalOutput}#e=!1;get isFinished(){return this.#e}#t=!1;get createdSnippets(){return this.#t}#r=void 0;get snippetsS3PreSignedReadUrl(){return this.#r}};async function XtL({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){try{await ZtL({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}),r.logger.info(od.green(`Downloaded to ${t}`))}catch(n){r.failAndThrow("Failed to download files",n)}}async function ZtL({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await hZ.get(e,{responseType:"stream"}),n=await _HE.default.dir({prefix:"fern",unsafeCleanup:!0}),i=X9_.default.join(n.path,"output.zip");await(0,pHE.pipeline)(r.data,(0,dHE.createWriteStream)(i)),await qv(t)&&await(0,aOl.rm)(t,{recursive:!0}),await(0,aOl.mkdir)(t,{recursive:!0}),await(0,fHE.default)(i,t)}function ktL(e){switch(e){case"DEBUG":return eE.Debug;case"INFO":return eE.Info;case"WARN":return eE.Warn;case"ERROR":return eE.Error;default:return eE.Info}}var uOl=require("fs/promises"),hHE=fa(RCe(),1),erL="proto.zip",oOl=class{sourceTypes;context;sources;constructor(t,r){this.context=t,this.sources=Object.fromEntries(r.map(n=>[n.id,n])),this.sourceTypes=new Set(Object.values(this.sources).map(n=>n.type))}async uploadSources(t){for(let[r,n]of Object.entries(t)){let i=this.getSourceOrThrow(r);await this.uploadSource(i,n.uploadUrl)}return this.convertFdrSourceUploadsToSourceConfig(t)}async uploadSource(t,r){let n=await this.getUploadCommand(t),i=await(0,uOl.readFile)(n.absoluteFilePath),a=await fetch(r,{method:"PUT",body:i,headers:{"Content-Type":"application/octet-stream"}});await n.cleanup(),a.ok||this.context.failAndThrow(`Failed to upload source file: ${t.absoluteFilePath}. Status: ${a.status}, ${a.statusText}`)}async getUploadCommand(t){if(t.type==="protobuf"){let r=await this.zipSource(t.absoluteFilePath);return{absoluteFilePath:r,cleanup:async()=>{this.context.logger.debug(`Removing ${r}`),await(0,uOl.unlink)(r)}}}return{absoluteFilePath:t.absoluteFilePath,cleanup:async()=>{}}}async zipSource(t){let r=await hHE.default.dir(),n=Jl(x_.of(r.path),ys.of(erL));return this.context.logger.debug(`Zipping source ${t} into ${n}`),await UH(this.context.logger,"zip",["-r",n,"."],{cwd:t,doNotPipeOutput:!0}),n}convertFdrSourceUploadsToSourceConfig(t){let r=[];for(let[n,i]of Object.entries(t))switch(this.getSourceOrThrow(n).type){case"protobuf":r.push(Axe.proto({id:n,protoRootUrl:i.downloadUrl}));continue;case"openapi":r.push(Axe.openapi());continue;case"asyncapi":continue}return{sources:r}}getSourceOrThrow(t){let r=this.sources[t];return r==null&&this.context.failAndThrow(`Internal error; server responded with source id "${t}" which does not exist in the workspace.`),r}};async function yHE({projectConfig:e,organization:t,workspace:r,interactiveTaskContext:n,generatorInvocation:i,version:a,audiences:o,shouldLogS3Url:c,token:d,whitelabel:s,irVersionOverride:u,absolutePathToPreview:l,readme:m}){let A=wsa({token:d.value}),P=XP.getPackageName({generatorInvocation:i}),C=l!=null,M=Me=>O3i(Me,{onError:Be=>n.failAndThrow(Be)},{substituteAsEmpty:C}),T=M(i),z=rOl({apiName:r.definition.rootApiFile.contents.name,organization:t,generatorInvocation:T}),U=JH({workspace:r,generationLanguage:i.language,keywords:i.keywords,smartCasing:i.smartCasing,exampleGeneration:{disabled:i.disableExamples,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!1},audiences:o,readme:m,packageName:P,version:a??await rrL({fdr:A,packageName:P,generatorInvocation:i}),context:n,sourceResolver:new VH(n,r),dynamicGeneratorConfig:z}),V=await rIe({token:d.value}).organization.get(dR.OrganizationId(e.organization));V.ok&&V.body.isWhitelabled&&(U.readmeConfig==null&&(U.readmeConfig=irL),U.readmeConfig.whiteLabel=!0);let Y=r.getSources(),re=VIe({ir:U,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},context:n}),X=await A.api.v1.register.registerApiDefinition({orgId:Z9_.FernRegistry.OrgId(t),apiId:Z9_.FernRegistry.ApiId(U.apiName.originalName),definition:re,sources:Y.length>0?nrL(Y):void 0}),ee,ne;X.ok&&(ee=X.body.apiDefinitionId,ne=X.body.sources);let me=new oOl(n,Y);if(ne==null&&me.sourceTypes.has("protobuf")&&(X.ok||n.failAndThrow(`Failed to register API definition: ${JSON.stringify(X.error.content)}`),n.failAndThrow("Did not successfully upload Protobuf source files.")),ne!=null){n.logger.debug("Uploading source files ...");let Me=await me.uploadSources(ne);n.logger.debug("Setting IR source configuration ..."),U.sourceConfig=Me}let be=await iHE({projectConfig:e,workspace:r,organization:t,generatorInvocation:T,context:n,version:a,intermediateRepresentation:{...U,fdrApiDefinitionId:ee,publishConfig:trL({generatorInvocation:T})},shouldLogS3Url:c,token:d,whitelabel:s!=null?M(s):void 0,irVersionOverride:u,absolutePathToPreview:l});n.logger.debug(`Job ID: ${be.jobId}`);let Ae=be.taskIds[0];if(Ae==null){n.failAndThrow("Did not receive a task ID.");return}n.logger.debug(`Task ID: ${Ae}`);let he=new iOl({job:be,taskId:Ae,generatorInvocation:i,interactiveTaskContext:n,absolutePathToPreview:l});return await uHE({job:be,taskHandler:he,taskId:Ae,context:n})}function trL({generatorInvocation:e}){return e.outputMode._visit({downloadFiles:()=>{},github:()=>{},githubV2:()=>{},publish:()=>{},publishV2:t=>t._visit({mavenOverride:()=>{},pypiOverride:()=>{},nugetOverride:()=>{},npmOverride:()=>{},rubyGemsOverride:()=>{},cratesOverride:()=>{},postman:r=>{let n;return e.raw?.output?.location==="postman"&&(n=e.raw.output?.["collection-id"]),Jd.PublishingConfig.direct({target:Jd.PublishTarget.postman({apiKey:r.apiKey,workspaceId:r.workspaceId,collectionId:n})})},_other:()=>{}}),_other:()=>{}})}async function rrL({fdr:e,packageName:t,generatorInvocation:r}){if(r.language==null)return;let n;switch(r.language){case"csharp":n="Csharp";break;case"go":n="Go";break;case"java":n="Java";break;case"python":n="Python";break;case"ruby":n="Ruby";break;case"typescript":n="TypeScript";break;case"php":n="Php";break;case"swift":n="Swift";break;default:return}if(t==null)return;let i=await e.sdks.versions.computeSemanticVersion({githubRepository:r.outputMode.type==="githubV2"?`${r.outputMode.githubV2.owner}/${r.outputMode.githubV2.repo}`:void 0,language:n,package:t});if(i.ok)return i.body.version}function nrL(e){return Object.fromEntries(Object.values(e).map(t=>[t.id,{type:t.type==="protobuf"?"proto":t.type}]))}var irL={defaultEndpoint:void 0,bannerLink:void 0,introduction:void 0,apiReferenceLink:void 0,apiName:void 0,disabledFeatures:void 0,whiteLabel:void 0,customSections:void 0,features:void 0,exampleStyle:void 0};async function k9_({projectConfig:e,organization:t,workspace:r,context:n,generatorGroup:i,version:a,shouldLogS3Url:o,token:c,whitelabel:d,absolutePathToPreview:s,mode:u}){if(i.generators.length===0)return n.logger.warn("No generators specified."),null;let l=[],m=[];return l.push(...i.generators.map(P=>n.runInteractiveTask({name:P.name},async C=>{let M=zao(P),T=await r.toFernWorkspace({context:n},M),z=await yHE({projectConfig:e,organization:t,workspace:T,interactiveTaskContext:C,generatorInvocation:{...P,outputMode:P.outputMode._visit({downloadFiles:()=>P.outputMode,github:U=>sOl.FernFiddle.OutputMode.github({...U,makePr:u==="pull-request"}),githubV2:U=>u==="pull-request"?sOl.FernFiddle.OutputMode.githubV2(sOl.FernFiddle.GithubOutputModeV2.pullRequest(U)):P.outputMode,publish:()=>P.outputMode,publishV2:()=>P.outputMode,_other:()=>P.outputMode})},version:a,audiences:i.audiences,shouldLogS3Url:o,token:c,whitelabel:d,readme:P.readme,irVersionOverride:P.irVersionOverride,absolutePathToPreview:s});z!=null&&z.createdSnippets&&(m.push(P),P.absolutePathToLocalSnippets!=null&&z.snippetsS3PreSignedReadUrl!=null&&await kWE({snippetsS3PreSignedReadUrl:z.snippetsS3PreSignedReadUrl,absolutePathToLocalSnippetJSON:P.absolutePathToLocalSnippets,context:C}))}))),(await Promise.all(l)).some(P=>!P)&&n.failAndThrow(),{snippetsProducedBy:m}}var ovi=fa(Bnt(),1);var CGE=require("fs/promises");var IU_=fa(cXa(),1);var ZRo=(e,t,r)=>JSON.stringify(e,t,r);function l3u(e,t){return JSON.parse(e,t)}var zp=class e extends Error{constructor({message:t,statusCode:r,body:n,rawResponse:i}){super(arL({message:t,statusCode:r,body:n})),Object.setPrototypeOf(this,e.prototype),this.statusCode=r,this.body=n,this.rawResponse=i}};function arL({message:e,statusCode:t,body:r}){let n=[];return e!=null&&n.push(e),t!=null&&n.push(`Status code: ${t.toString()}`),r!=null&&n.push(`Body: ${ZRo(r,void 0,2)}`),n.join(`
3042
3042
  `)}var aw=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};var lE=class e extends zp{constructor(t,r){super({message:"UnprocessableEntityError",statusCode:422,body:t,rawResponse:r}),Object.setPrototypeOf(this,e.prototype)}};var orL={arrayFormat:"indices",encode:!0};function vHE(e,t){if(e===void 0||e===null)return"";let r=String(e);return t?encodeURIComponent(r):r}function eU_(e,t="",r){let n=[];for(let[i,a]of Object.entries(e)){let o=t?`${t}[${i}]`:i;if(a!==void 0)if(Array.isArray(a)){if(a.length===0)continue;for(let c=0;c<a.length;c++){let d=a[c];if(d!==void 0)if(typeof d=="object"&&!Array.isArray(d)&&d!==null){let s=r.arrayFormat==="indices"?`${o}[${c}]`:o;n.push(...eU_(d,s,r))}else{let s=r.arrayFormat==="indices"?`${o}[${c}]`:o,u=r.encode?encodeURIComponent(s):s;n.push(`${u}=${vHE(d,r.encode)}`)}}}else if(typeof a=="object"&&a!==null){if(Object.keys(a).length===0)continue;n.push(...eU_(a,o,r))}else{let c=r.encode?encodeURIComponent(o):o;n.push(`${c}=${vHE(a,r.encode)}`)}}return n}function cOl(e,t){return e==null||typeof e!="object"?"":eU_(e,"",Object.assign(Object.assign({},orL),t)).join("&")}function bHE(e,t){let r=cOl(t,{arrayFormat:"repeat"});return r?`${e}?${r}`:e}function gHE(e){let t={get bodyUsed(){return e.bodyUsed},stream:()=>e.body,arrayBuffer:e.arrayBuffer.bind(e),blob:e.blob.bind(e)};return"bytes"in e&&typeof e.bytes=="function"&&(t.bytes=e.bytes.bind(e)),t}function mHE(e){return e.body!=null}var urL=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})};function lOl(e,t){return urL(this,void 0,void 0,function*(){if(!mHE(e))return;switch(t){case"binary-response":return gHE(e);case"blob":return yield e.blob();case"arrayBuffer":return yield e.arrayBuffer();case"sse":return e.body;case"streaming":return e.body;case"text":return yield e.text()}let r=yield e.text();if(r.length>0)try{return l3u(r)}catch{return{ok:!1,error:{reason:"non-json",statusCode:e.status,rawBody:r}}}})}var srL=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})};function OHE(e){return srL(this,void 0,void 0,function*(){var t,r,n;let i=(t=e.headers.get("Content-Type"))===null||t===void 0?void 0:t.toLowerCase();if(i==null||i.length===0)return lOl(e);switch(i.indexOf(";")!==-1&&(i=(n=(r=i.split(";")[0])===null||r===void 0?void 0:r.trim())!==null&&n!==void 0?n:""),i){case"application/hal+json":case"application/json":case"application/ld+json":case"application/problem+json":case"application/vnd.api+json":case"text/json":let a=yield e.text();return a.length>0?l3u(a):void 0;default:if(i.startsWith("application/vnd.")&&i.endsWith("+json")){let o=yield e.text();return o.length>0?l3u(o):void 0}return yield e.text()}})}var crL=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})};function AHE(){return crL(this,void 0,void 0,function*(){return fetch})}var lrL=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})};function PHE(e){return lrL(this,arguments,void 0,function*({body:t,type:r}){return r.includes("json")?ZRo(t):t})}var frL="timeout";function wHE(e){let t=new AbortController,r=setTimeout(()=>t.abort(frL),e);return{signal:t.signal,abortId:r}}function jHE(...e){let t=e.length===1&&Array.isArray(e[0])?e[0]:e,r=new AbortController;for(let n of t){if(n.aborted){r.abort(n?.reason);break}n.addEventListener("abort",()=>r.abort(n?.reason),{signal:r.signal})}return r.signal}var drL=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},EHE=(e,t,r,n,i,a,o,c,d)=>drL(void 0,void 0,void 0,function*(){let s=[],u;if(a!=null){let{signal:A,abortId:P}=wHE(a);u=P,s.push(A)}o!=null&&s.push(o);let l=jHE(s),m=yield e(t,{method:r,headers:n,body:i,signal:l,credentials:c?"include":void 0,duplex:d});return u!=null&&clearTimeout(u),m});var f3u;typeof globalThis.Headers<"u"?f3u=globalThis.Headers:f3u=class SHE{constructor(t){if(this.headers=new Map,t)if(t instanceof SHE)t.forEach((r,n)=>this.append(n,r));else if(Array.isArray(t))for(let[r,n]of t)if(typeof r=="string"&&typeof n=="string")this.append(r,n);else throw new TypeError("Each header entry must be a [string, string] tuple");else for(let[r,n]of Object.entries(t))if(typeof n=="string")this.append(r,n);else throw new TypeError("Header values must be strings")}append(t,r){let n=t.toLowerCase(),i=this.headers.get(n)||[];this.headers.set(n,[...i,r])}delete(t){let r=t.toLowerCase();this.headers.delete(r)}get(t){let r=t.toLowerCase(),n=this.headers.get(r);return n?n.join(", "):null}has(t){let r=t.toLowerCase();return this.headers.has(r)}set(t,r){let n=t.toLowerCase();this.headers.set(n,[r])}forEach(t,r){let n=r?t.bind(r):t;this.headers.forEach((i,a)=>n(i.join(", "),a,this))}getSetCookie(){return this.headers.get("set-cookie")||[]}*entries(){for(let[t,r]of this.headers.entries())yield[t,r.join(", ")]}*keys(){yield*this.headers.keys()}*values(){for(let t of this.headers.values())yield t.join(", ")}[Symbol.iterator](){return this.entries()}};var tU_={headers:new f3u,redirected:!1,status:499,statusText:"Client Closed Request",type:"error",url:""},rU_={headers:new f3u,redirected:!1,status:0,statusText:"Unknown Error",type:"error",url:""};function nU_(e){return{headers:e.headers,redirected:e.redirected,status:e.status,statusText:e.statusText,type:e.type,url:e.url}}var prL=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})};function _rL(e){let t=1+(Math.random()*2-1)*.2;return e*t}function DHE(e){return prL(this,arguments,void 0,function*(t,r=2){let n=yield t();for(let i=0;i<r&&([408,429].includes(n.status)||n.status>=500);++i){let a=Math.min(1e3*Math.pow(2,i),6e4),o=_rL(a);yield new Promise(c=>setTimeout(c,o)),n=yield t()}return n})}var hrL=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},ly={get:e=>hrL(void 0,void 0,void 0,function*(){return typeof e=="function"?e():e})};var iU_=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})};function yrL(e){return iU_(this,void 0,void 0,function*(){let t={};if(e.body!==void 0&&e.contentType!=null&&(t["Content-Type"]=e.contentType),e.headers==null)return t;for(let[r,n]of Object.entries(e.headers)){let i=yield ly.get(n);if(typeof i=="string"){t[r]=i;continue}i!=null&&(t[r]=`${i}`)}return t})}function vrL(e){return iU_(this,void 0,void 0,function*(){let t=bHE(e.url,e.queryParameters),r=yield PHE({body:e.body,type:e.requestType==="json"?"json":"other"}),n=yield AHE();try{let i=yield DHE(()=>iU_(this,void 0,void 0,function*(){return EHE(n,t,e.method,yield yrL(e),r,e.timeoutMs,e.abortSignal,e.withCredentials,e.duplex)}),e.maxRetries);return i.status>=200&&i.status<400?{ok:!0,body:yield lOl(i,e.responseType),headers:i.headers,rawResponse:nU_(i)}:{ok:!1,error:{reason:"status-code",statusCode:i.status,body:yield OHE(i)},rawResponse:nU_(i)}}catch(i){return e.abortSignal!=null&&e.abortSignal.aborted?{ok:!1,error:{reason:"unknown",errorMessage:"The user aborted a request"},rawResponse:tU_}:i instanceof Error&&i.name==="AbortError"?{ok:!1,error:{reason:"timeout"},rawResponse:tU_}:i instanceof Error?{ok:!1,error:{reason:"unknown",errorMessage:i.message},rawResponse:rU_}:{ok:!1,error:{reason:"unknown",errorMessage:ZRo(i)},rawResponse:rU_}}})}var Yw=vrL;var brL=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},ow=class e extends Promise{constructor(t){super(r=>{r(void 0)}),this.innerPromise=t}static fromFunction(t,...r){return new e(t(...r))}static interceptFunction(t){return(...r)=>e.fromPromise(t(...r))}static fromPromise(t){return new e(t)}static fromExecutor(t){let r=new Promise(t);return new e(r)}static fromResult(t){let r=Promise.resolve(t);return new e(r)}unwrap(){return this.unwrappedPromise||(this.unwrappedPromise=this.innerPromise.then(({data:t})=>t)),this.unwrappedPromise}then(t,r){return this.unwrap().then(t,r)}catch(t){return this.unwrap().catch(t)}finally(t){return this.unwrap().finally(t)}withRawResponse(){return brL(this,void 0,void 0,function*(){return yield this.innerPromise})}};var fOl=grL();function grL(){var e,t,r,n,i;return typeof window<"u"&&typeof window.document<"u"?{type:"browser",version:window.navigator.userAgent}:typeof globalThis<"u"&&((e=globalThis?.navigator)===null||e===void 0?void 0:e.userAgent)==="Cloudflare-Workers"?{type:"workerd"}:typeof EdgeRuntime=="string"?{type:"edge-runtime"}:typeof self=="object"&&typeof self?.importScripts=="function"&&(((t=self.constructor)===null||t===void 0?void 0:t.name)==="DedicatedWorkerGlobalScope"||((r=self.constructor)===null||r===void 0?void 0:r.name)==="ServiceWorkerGlobalScope"||((n=self.constructor)===null||n===void 0?void 0:n.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&&!!(!((i=process.versions)===null||i===void 0)&&i.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"}}var Iw={};ff(Iw,{join:()=>IHE,toQueryString:()=>cOl});function IHE(e,...t){if(!e)return"";if(t.length===0)return e;if(e.includes("://")){let r;try{r=new URL(e)}catch{return CHE(e,...t)}let n=t[t.length-1],i=n&&n.endsWith("/");for(let a of t){let o=BHE(a);o&&(r.pathname=MHE(r.pathname,o))}return i&&!r.pathname.endsWith("/")&&(r.pathname+="/"),r.toString()}return CHE(e,...t)}function CHE(e,...t){if(t.length===0)return e;let r=e,n=t[t.length-1],i=n&&n.endsWith("/");for(let a of t){let o=BHE(a);o&&(r=MHE(r,o))}return i&&!r.endsWith("/")&&(r+="/"),r}function MHE(e,t){return e.endsWith("/")?e+t:e+"/"+t}function BHE(e){if(!e)return e;let t=0,r=e.length;return e.startsWith("/")&&(t=1),e.endsWith("/")&&(r=e.length-1),t===0&&r===e.length?e:e.slice(t,r)}function Mw(...e){let t={};for(let[r,n]of e.filter(i=>i!=null).flatMap(i=>Object.entries(i)))n!=null?t[r]=n:r in t&&delete t[r];return t}function lj(...e){let t={};for(let[r,n]of e.filter(i=>i!=null).flatMap(i=>Object.entries(i)))n!=null&&(t[r]=n);return t}var fj={Production:"https://fai.buildwithfern.com",Development:"https://fai-dev.buildwithfern.com",Local:"http://localhost:8080"};var kRo=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},dOl=class{constructor(t={}){this._options=t}getAnalyticsHistogram(t,r={},n){return ow.fromPromise(this.__getAnalyticsHistogram(t,r,n))}__getAnalyticsHistogram(t){return kRo(this,arguments,void 0,function*(r,n={},i){var a,o,c;let{start_date:d,end_date:s,group_by:u}=n,l={};d!=null&&(l.start_date=d),s!=null&&(l.end_date=s),u!=null&&(l.group_by=u);let m=Mw((a=this._options)===null||a===void 0?void 0:a.headers,lj({Authorization:yield this._getAuthorizationHeader()}),i?.headers),A=yield Yw({url:Iw.join((c=(o=yield ly.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ly.get(this._options.environment))!==null&&c!==void 0?c:fj.Production,`analytics/histogram/${encodeURIComponent(r)}`),method:"GET",headers:m,queryParameters:Object.assign(Object.assign({},l),i?.queryParams),timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(A.ok)return{data:A.body,rawResponse:A.rawResponse};if(A.error.reason==="status-code")switch(A.error.statusCode){case 422:throw new lE(A.error.body,A.rawResponse);default:throw new zp({statusCode:A.error.statusCode,body:A.error.body,rawResponse:A.rawResponse})}switch(A.error.reason){case"non-json":throw new zp({statusCode:A.error.statusCode,body:A.error.rawBody,rawResponse:A.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /analytics/histogram/{domain}.");case"unknown":throw new zp({message:A.error.errorMessage,rawResponse:A.rawResponse})}})}getAnalyticsInsights(t,r={},n){return ow.fromPromise(this.__getAnalyticsInsights(t,r,n))}__getAnalyticsInsights(t){return kRo(this,arguments,void 0,function*(r,n={},i){var a,o,c;let{start_date:d,end_date:s}=n,u={};d!=null&&(u.start_date=d),s!=null&&(u.end_date=s);let l=Mw((a=this._options)===null||a===void 0?void 0:a.headers,lj({Authorization:yield this._getAuthorizationHeader()}),i?.headers),m=yield Yw({url:Iw.join((c=(o=yield ly.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ly.get(this._options.environment))!==null&&c!==void 0?c:fj.Production,`analytics/insights/${encodeURIComponent(r)}`),method:"GET",headers:l,queryParameters:Object.assign(Object.assign({},u),i?.queryParams),timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")switch(m.error.statusCode){case 422:throw new lE(m.error.body,m.rawResponse);default:throw new zp({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse})}switch(m.error.reason){case"non-json":throw new zp({statusCode:m.error.statusCode,body:m.error.rawBody,rawResponse:m.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /analytics/insights/{domain}.");case"unknown":throw new zp({message:m.error.errorMessage,rawResponse:m.rawResponse})}})}generateAllInsights(t={},r){return ow.fromPromise(this.__generateAllInsights(t,r))}__generateAllInsights(){return kRo(this,arguments,void 0,function*(t={},r){var n,i,a;let{start_date:o,end_date:c}=t,d={};o!=null&&(d.start_date=o),c!=null&&(d.end_date=c);let s=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),u=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"analytics/insights/generate_all"),method:"POST",headers:s,queryParameters:Object.assign(Object.assign({},d),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:u.body,rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 422:throw new lE(u.error.body,u.rawResponse);default:throw new zp({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new zp({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /analytics/insights/generate_all.");case"unknown":throw new zp({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}triggerScheduledInsightsGeneration(t){return ow.fromPromise(this.__triggerScheduledInsightsGeneration(t))}__triggerScheduledInsightsGeneration(t){return kRo(this,void 0,void 0,function*(){var r,n,i;let a=Mw((r=this._options)===null||r===void 0?void 0:r.headers,lj({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield Yw({url:Iw.join((i=(n=yield ly.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ly.get(this._options.environment))!==null&&i!==void 0?i:fj.Production,"analytics/insights/trigger_scheduled"),method:"POST",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new zp({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new zp({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /analytics/insights/trigger_scheduled.");case"unknown":throw new zp({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}getSchedulerStatus(t){return ow.fromPromise(this.__getSchedulerStatus(t))}__getSchedulerStatus(t){return kRo(this,void 0,void 0,function*(){var r,n,i;let a=Mw((r=this._options)===null||r===void 0?void 0:r.headers,lj({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield Yw({url:Iw.join((i=(n=yield ly.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ly.get(this._options.environment))!==null&&i!==void 0?i:fj.Production,"analytics/scheduler/status"),method:"GET",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new zp({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new zp({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /analytics/scheduler/status.");case"unknown":throw new zp({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}_getAuthorizationHeader(){return kRo(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var THE=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},pOl=class{constructor(t={}){this._options=t}postChatCompletion(t,r,n){return ow.fromPromise(this.__postChatCompletion(t,r,n))}__postChatCompletion(t,r,n){return THE(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`chat/${encodeURIComponent(t)}`),method:"POST",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /chat/{domain}.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}_getAuthorizationHeader(){return THE(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var qHE=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},_Ol=class{constructor(t={}){this._options=t}getConversationById(t,r,n){return ow.fromPromise(this.__getConversationById(t,r,n))}__getConversationById(t,r,n){return qHE(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`conversation/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),method:"GET",headers:c,queryParameters:n?.queryParams,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /conversation/{domain}/{conversation_id}.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}_getAuthorizationHeader(){return qHE(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var aU_=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},hOl=class{constructor(t={}){this._options=t}createDiscordIntegration(t,r){return ow.fromPromise(this.__createDiscordIntegration(t,r))}__createDiscordIntegration(t,r){return aU_(this,void 0,void 0,function*(){var n,i,a;let{domain:o}=t,c={};c.domain=o;let d=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"discord/install"),method:"POST",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new lE(s.error.body,s.rawResponse);default:throw new zp({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new zp({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /discord/install.");case"unknown":throw new zp({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}handleDiscordInstallCallback(t){return ow.fromPromise(this.__handleDiscordInstallCallback(t))}__handleDiscordInstallCallback(t){return aU_(this,void 0,void 0,function*(){var r,n,i;let a=Mw((r=this._options)===null||r===void 0?void 0:r.headers,lj({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield Yw({url:Iw.join((i=(n=yield ly.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ly.get(this._options.environment))!==null&&i!==void 0?i:fj.Production,"discord/install/callback"),method:"GET",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new zp({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new zp({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /discord/install/callback.");case"unknown":throw new zp({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}_getAuthorizationHeader(){return aU_(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var iTi=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},yOl=class{constructor(t={}){this._options=t}createDocument(t,r,n){return ow.fromPromise(this.__createDocument(t,r,n))}__createDocument(t,r,n){return iTi(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`document/${encodeURIComponent(t)}/create`),method:"POST",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /document/{domain}/create.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}batchCreateDocument(t,r,n){return ow.fromPromise(this.__batchCreateDocument(t,r,n))}__batchCreateDocument(t,r,n){return iTi(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`document/${encodeURIComponent(t)}/batch-create`),method:"POST",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /document/{domain}/batch-create.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getDocumentById(t,r,n){return ow.fromPromise(this.__getDocumentById(t,r,n))}__getDocumentById(t,r,n){return iTi(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`document/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),method:"GET",headers:c,queryParameters:n?.queryParams,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /document/{domain}/{document_id}.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}updateDocument(t,r,n={},i){return ow.fromPromise(this.__updateDocument(t,r,n,i))}__updateDocument(t,r){return iTi(this,arguments,void 0,function*(n,i,a={},o){var c,d,s;let u=Mw((c=this._options)===null||c===void 0?void 0:c.headers,lj({Authorization:yield this._getAuthorizationHeader()}),o?.headers),l=yield Yw({url:Iw.join((s=(d=yield ly.get(this._options.baseUrl))!==null&&d!==void 0?d:yield ly.get(this._options.environment))!==null&&s!==void 0?s:fj.Production,`document/${encodeURIComponent(n)}/${encodeURIComponent(i)}`),method:"PATCH",headers:u,contentType:"application/json",queryParameters:o?.queryParams,requestType:"json",body:a,timeoutMs:o?.timeoutInSeconds!=null?o.timeoutInSeconds*1e3:6e4,maxRetries:o?.maxRetries,abortSignal:o?.abortSignal});if(l.ok)return{data:l.body,rawResponse:l.rawResponse};if(l.error.reason==="status-code")switch(l.error.statusCode){case 422:throw new lE(l.error.body,l.rawResponse);default:throw new zp({statusCode:l.error.statusCode,body:l.error.body,rawResponse:l.rawResponse})}switch(l.error.reason){case"non-json":throw new zp({statusCode:l.error.statusCode,body:l.error.rawBody,rawResponse:l.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling PATCH /document/{domain}/{document_id}.");case"unknown":throw new zp({message:l.error.errorMessage,rawResponse:l.rawResponse})}})}deleteDocumentById(t,r,n){return ow.fromPromise(this.__deleteDocumentById(t,r,n))}__deleteDocumentById(t,r,n){return iTi(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`document/${encodeURIComponent(t)}/delete`),method:"DELETE",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling DELETE /document/{domain}/delete.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}batchDeleteDocument(t,r,n){return ow.fromPromise(this.__batchDeleteDocument(t,r,n))}__batchDeleteDocument(t,r,n){return iTi(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`document/${encodeURIComponent(t)}/batch-delete`),method:"DELETE",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling DELETE /document/{domain}/batch-delete.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getDocuments(t,r={},n){return ow.fromPromise(this.__getDocuments(t,r,n))}__getDocuments(t){return iTi(this,arguments,void 0,function*(r,n={},i){var a,o,c;let{page:d,limit:s}=n,u={};d!=null&&(u.page=d.toString()),s!=null&&(u.limit=s.toString());let l=Mw((a=this._options)===null||a===void 0?void 0:a.headers,lj({Authorization:yield this._getAuthorizationHeader()}),i?.headers),m=yield Yw({url:Iw.join((c=(o=yield ly.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ly.get(this._options.environment))!==null&&c!==void 0?c:fj.Production,`document/${encodeURIComponent(r)}`),method:"GET",headers:l,queryParameters:Object.assign(Object.assign({},u),i?.queryParams),timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")switch(m.error.statusCode){case 422:throw new lE(m.error.body,m.rawResponse);default:throw new zp({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse})}switch(m.error.reason){case"non-json":throw new zp({statusCode:m.error.statusCode,body:m.error.rawBody,rawResponse:m.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /document/{domain}.");case"unknown":throw new zp({message:m.error.errorMessage,rawResponse:m.rawResponse})}})}deleteAllDocuments(t,r){return ow.fromPromise(this.__deleteAllDocuments(t,r))}__deleteAllDocuments(t,r){return iTi(this,void 0,void 0,function*(){var n,i,a;let o=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,`document/${encodeURIComponent(t)}/delete-all`),method:"DELETE",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new lE(c.error.body,c.rawResponse);default:throw new zp({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new zp({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling DELETE /document/{domain}/delete-all.");case"unknown":throw new zp({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}_getAuthorizationHeader(){return iTi(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var oU_=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},vOl=class{constructor(t={}){this._options=t}createFeedback(t,r,n){return ow.fromPromise(this.__createFeedback(t,r,n))}__createFeedback(t,r,n){return oU_(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`feedback/${encodeURIComponent(t)}`),method:"POST",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /feedback/{domain}.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getFeedbackById(t,r,n){return ow.fromPromise(this.__getFeedbackById(t,r,n))}__getFeedbackById(t,r,n){return oU_(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`feedback/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),method:"GET",headers:c,queryParameters:n?.queryParams,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /feedback/{domain}/{conversation_id}.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}_getAuthorizationHeader(){return oU_(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var uU_=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},bOl=class{constructor(t={}){this._options=t}indexReferenceMd(t,r,n){return ow.fromPromise(this.__indexReferenceMd(t,r,n))}__indexReferenceMd(t,r,n){return uU_(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`github/${encodeURIComponent(t)}/reference-md/index`),method:"POST",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /github/{domain}/reference-md/index.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}checkCodeIndexStatus(t,r){return ow.fromPromise(this.__checkCodeIndexStatus(t,r))}__checkCodeIndexStatus(t,r){return uU_(this,void 0,void 0,function*(){var n,i,a;let o=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,`github/${encodeURIComponent(t)}/indexed`),method:"GET",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new lE(c.error.body,c.rawResponse);default:throw new zp({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new zp({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /github/{domain}/indexed.");case"unknown":throw new zp({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}_getAuthorizationHeader(){return uU_(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var eNo=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},gOl=class{constructor(t={}){this._options=t}createGuidance(t,r,n){return ow.fromPromise(this.__createGuidance(t,r,n))}__createGuidance(t,r,n){return eNo(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`guidance/${encodeURIComponent(t)}/create`),method:"POST",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /guidance/{domain}/create.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getGuidanceById(t,r,n){return ow.fromPromise(this.__getGuidanceById(t,r,n))}__getGuidanceById(t,r,n){return eNo(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`guidance/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),method:"GET",headers:c,queryParameters:n?.queryParams,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /guidance/{domain}/{guidance_id}.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}deleteGuidanceById(t,r,n){return ow.fromPromise(this.__deleteGuidanceById(t,r,n))}__deleteGuidanceById(t,r,n){return eNo(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`guidance/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),method:"DELETE",headers:c,queryParameters:n?.queryParams,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling DELETE /guidance/{domain}/{guidance_id}.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}update(t,r,n={},i){return ow.fromPromise(this.__update(t,r,n,i))}__update(t,r){return eNo(this,arguments,void 0,function*(n,i,a={},o){var c,d,s;let u=Mw((c=this._options)===null||c===void 0?void 0:c.headers,lj({Authorization:yield this._getAuthorizationHeader()}),o?.headers),l=yield Yw({url:Iw.join((s=(d=yield ly.get(this._options.baseUrl))!==null&&d!==void 0?d:yield ly.get(this._options.environment))!==null&&s!==void 0?s:fj.Production,`guidance/${encodeURIComponent(n)}/${encodeURIComponent(i)}`),method:"PATCH",headers:u,contentType:"application/json",queryParameters:o?.queryParams,requestType:"json",body:a,timeoutMs:o?.timeoutInSeconds!=null?o.timeoutInSeconds*1e3:6e4,maxRetries:o?.maxRetries,abortSignal:o?.abortSignal});if(l.ok)return{data:l.body,rawResponse:l.rawResponse};if(l.error.reason==="status-code")switch(l.error.statusCode){case 422:throw new lE(l.error.body,l.rawResponse);default:throw new zp({statusCode:l.error.statusCode,body:l.error.body,rawResponse:l.rawResponse})}switch(l.error.reason){case"non-json":throw new zp({statusCode:l.error.statusCode,body:l.error.rawBody,rawResponse:l.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling PATCH /guidance/{domain}/{guidance_id}.");case"unknown":throw new zp({message:l.error.errorMessage,rawResponse:l.rawResponse})}})}getGuidances(t,r={},n){return ow.fromPromise(this.__getGuidances(t,r,n))}__getGuidances(t){return eNo(this,arguments,void 0,function*(r,n={},i){var a,o,c;let{page:d,limit:s}=n,u={};d!=null&&(u.page=d.toString()),s!=null&&(u.limit=s.toString());let l=Mw((a=this._options)===null||a===void 0?void 0:a.headers,lj({Authorization:yield this._getAuthorizationHeader()}),i?.headers),m=yield Yw({url:Iw.join((c=(o=yield ly.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ly.get(this._options.environment))!==null&&c!==void 0?c:fj.Production,`guidance/${encodeURIComponent(r)}`),method:"GET",headers:l,queryParameters:Object.assign(Object.assign({},u),i?.queryParams),timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")switch(m.error.statusCode){case 422:throw new lE(m.error.body,m.rawResponse);default:throw new zp({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse})}switch(m.error.reason){case"non-json":throw new zp({statusCode:m.error.statusCode,body:m.error.rawBody,rawResponse:m.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /guidance/{domain}.");case"unknown":throw new zp({message:m.error.errorMessage,rawResponse:m.rawResponse})}})}_getAuthorizationHeader(){return eNo(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var RHE=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},mOl=class{constructor(t={}){this._options=t}check(t){return ow.fromPromise(this.__check(t))}__check(t){return RHE(this,void 0,void 0,function*(){var r,n,i;let a=Mw((r=this._options)===null||r===void 0?void 0:r.headers,lj({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield Yw({url:Iw.join((i=(n=yield ly.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ly.get(this._options.environment))!==null&&i!==void 0?i:fj.Production,"health"),method:"GET",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new zp({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new zp({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /health.");case"unknown":throw new zp({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}_getAuthorizationHeader(){return RHE(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var OOl=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},AOl=class{constructor(t={}){this._options=t}reconstructQueryIndex(t,r){return ow.fromPromise(this.__reconstructQueryIndex(t,r))}__reconstructQueryIndex(t,r){return OOl(this,void 0,void 0,function*(){var n,i,a;let o=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,`index/${encodeURIComponent(t)}/reconstruct`),method:"POST",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new lE(c.error.body,c.rawResponse);default:throw new zp({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new zp({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /index/{domain}/reconstruct.");case"unknown":throw new zp({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}syncIndexToQueryIndex(t,r,n){return ow.fromPromise(this.__syncIndexToQueryIndex(t,r,n))}__syncIndexToQueryIndex(t,r,n){return OOl(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`index/${encodeURIComponent(t)}/sync`),method:"POST",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /index/{domain}/sync.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getJobStatus(t,r){return ow.fromPromise(this.__getJobStatus(t,r))}__getJobStatus(t,r){return OOl(this,void 0,void 0,function*(){var n,i,a;let o=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,`jobs/${encodeURIComponent(t)}/status`),method:"GET",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new lE(c.error.body,c.rawResponse);default:throw new zp({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new zp({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /jobs/{job_id}/status.");case"unknown":throw new zp({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}_getAuthorizationHeader(){return OOl(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var sU_=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},POl=class{constructor(t={}){this._options=t}getMcpSemanticQuery(t,r,n){return ow.fromPromise(this.__getMcpSemanticQuery(t,r,n))}__getMcpSemanticQuery(t,r,n){return sU_(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`mcp/semantic/${encodeURIComponent(t)}`),method:"POST",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /mcp/semantic/{domain}.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getMcpBmfQuery(t,r,n){return ow.fromPromise(this.__getMcpBmfQuery(t,r,n))}__getMcpBmfQuery(t,r,n){return sU_(this,void 0,void 0,function*(){var i,a,o;let c=Mw((i=this._options)===null||i===void 0?void 0:i.headers,lj({Authorization:yield this._getAuthorizationHeader()}),n?.headers),d=yield Yw({url:Iw.join((o=(a=yield ly.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ly.get(this._options.environment))!==null&&o!==void 0?o:fj.Production,`mcp/bmf/${encodeURIComponent(t)}`),method:"POST",headers:c,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:r,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new lE(d.error.body,d.rawResponse);default:throw new zp({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new zp({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /mcp/bmf/{domain}.");case"unknown":throw new zp({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}_getAuthorizationHeader(){return sU_(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var cU_=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},wOl=class{constructor(t={}){this._options=t}createQuery(t,r){return ow.fromPromise(this.__createQuery(t,r))}__createQuery(t,r){return cU_(this,void 0,void 0,function*(){var n,i,a;let{domain:o,body:c}=t,d={};d.domain=o;let s=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),u=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"queries"),method:"POST",headers:s,contentType:"application/json",queryParameters:Object.assign(Object.assign({},d),r?.queryParams),requestType:"json",body:c,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:u.body,rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 422:throw new lE(u.error.body,u.rawResponse);default:throw new zp({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new zp({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /queries.");case"unknown":throw new zp({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}getRecentQueries(t,r={},n){return ow.fromPromise(this.__getRecentQueries(t,r,n))}__getRecentQueries(t){return cU_(this,arguments,void 0,function*(r,n={},i){var a,o,c;let{page:d,limit:s,cutoff_time:u,include_assistant:l,start_date:m,end_date:A}=n,P={};d!=null&&(P.page=d.toString()),s!=null&&(P.limit=s.toString()),u!=null&&(P.cutoff_time=u),l!=null&&(P.include_assistant=l.toString()),m!=null&&(P.start_date=m),A!=null&&(P.end_date=A);let C=Mw((a=this._options)===null||a===void 0?void 0:a.headers,lj({Authorization:yield this._getAuthorizationHeader()}),i?.headers),M=yield Yw({url:Iw.join((c=(o=yield ly.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ly.get(this._options.environment))!==null&&c!==void 0?c:fj.Production,`queries/${encodeURIComponent(r)}`),method:"GET",headers:C,queryParameters:Object.assign(Object.assign({},P),i?.queryParams),timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(M.ok)return{data:M.body,rawResponse:M.rawResponse};if(M.error.reason==="status-code")switch(M.error.statusCode){case 422:throw new lE(M.error.body,M.rawResponse);default:throw new zp({statusCode:M.error.statusCode,body:M.error.body,rawResponse:M.rawResponse})}switch(M.error.reason){case"non-json":throw new zp({statusCode:M.error.statusCode,body:M.error.rawBody,rawResponse:M.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /queries/{domain}.");case"unknown":throw new zp({message:M.error.errorMessage,rawResponse:M.rawResponse})}})}_getAuthorizationHeader(){return cU_(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var mQa=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},jOl=class{constructor(t={}){this._options=t}getSettings(t,r){return ow.fromPromise(this.__getSettings(t,r))}__getSettings(t,r){return mQa(this,void 0,void 0,function*(){var n,i,a;let{domain:o}=t,c={};c.domain=o;let d=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"settings/ask-ai"),method:"GET",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new lE(s.error.body,s.rawResponse);default:throw new zp({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new zp({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /settings/ask-ai.");case"unknown":throw new zp({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}getDocsSettings(t,r){return ow.fromPromise(this.__getDocsSettings(t,r))}__getDocsSettings(t,r){return mQa(this,void 0,void 0,function*(){var n,i,a;let{domain:o}=t,c={};c.domain=o;let d=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"settings/ask-ai/docs"),method:"GET",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new lE(s.error.body,s.rawResponse);default:throw new zp({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new zp({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /settings/ask-ai/docs.");case"unknown":throw new zp({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}toggleAskAi(t,r){return ow.fromPromise(this.__toggleAskAi(t,r))}__toggleAskAi(t,r){return mQa(this,void 0,void 0,function*(){var n,i,a;let{domain:o,org_name:c,preview:d}=t,s={};s.domain=o,s.org_name=c,d!=null&&(s.preview=d.toString());let u=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),l=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"settings/ask-ai/toggle"),method:"POST",headers:u,queryParameters:Object.assign(Object.assign({},s),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(l.ok)return{data:l.body,rawResponse:l.rawResponse};if(l.error.reason==="status-code")switch(l.error.statusCode){case 422:throw new lE(l.error.body,l.rawResponse);default:throw new zp({statusCode:l.error.statusCode,body:l.error.body,rawResponse:l.rawResponse})}switch(l.error.reason){case"non-json":throw new zp({statusCode:l.error.statusCode,body:l.error.rawBody,rawResponse:l.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /settings/ask-ai/toggle.");case"unknown":throw new zp({message:l.error.errorMessage,rawResponse:l.rawResponse})}})}reindexAskAi(t,r){return ow.fromPromise(this.__reindexAskAi(t,r))}__reindexAskAi(t,r){return mQa(this,void 0,void 0,function*(){var n,i,a;let{domain:o,org_name:c}=t,d={};d.domain=o,d.org_name=c;let s=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),u=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"settings/ask-ai/reindex"),method:"POST",headers:s,queryParameters:Object.assign(Object.assign({},d),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:u.body,rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 422:throw new lE(u.error.body,u.rawResponse);default:throw new zp({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new zp({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /settings/ask-ai/reindex.");case"unknown":throw new zp({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}getToggleStatus(t,r){return ow.fromPromise(this.__getToggleStatus(t,r))}__getToggleStatus(t,r){return mQa(this,void 0,void 0,function*(){var n,i,a;let{domain:o}=t,c={};c.domain=o;let d=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"settings/ask-ai/toggle/status"),method:"GET",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new lE(s.error.body,s.rawResponse);default:throw new zp({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new zp({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /settings/ask-ai/toggle/status.");case"unknown":throw new zp({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}reindexPreviewCallback(t,r){return ow.fromPromise(this.__reindexPreviewCallback(t,r))}__reindexPreviewCallback(t,r){return mQa(this,void 0,void 0,function*(){var n,i,a;let o=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"settings/reindex-preview-callback"),method:"POST",headers:o,contentType:"application/json",queryParameters:r?.queryParams,requestType:"json",body:t,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new lE(c.error.body,c.rawResponse);default:throw new zp({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new zp({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /settings/reindex-preview-callback.");case"unknown":throw new zp({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}_getAuthorizationHeader(){return mQa(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var aTi=function(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(n.next(u))}catch(l){o(l)}}function d(u){try{s(n.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):i(u.value).then(c,d)}s((n=n.apply(e,t||[])).next())})},EOl=class{constructor(t={}){this._options=t}createSlackIntegration(t,r){return ow.fromPromise(this.__createSlackIntegration(t,r))}__createSlackIntegration(t,r){return aTi(this,void 0,void 0,function*(){var n,i,a;let o=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"slack/integrations"),method:"POST",headers:o,contentType:"application/json",queryParameters:r?.queryParams,requestType:"json",body:t,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new lE(c.error.body,c.rawResponse);default:throw new zp({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new zp({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /slack/integrations.");case"unknown":throw new zp({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}handleSlackEvents(t){return ow.fromPromise(this.__handleSlackEvents(t))}__handleSlackEvents(t){return aTi(this,void 0,void 0,function*(){var r,n,i;let a=Mw((r=this._options)===null||r===void 0?void 0:r.headers,lj({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield Yw({url:Iw.join((i=(n=yield ly.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ly.get(this._options.environment))!==null&&i!==void 0?i:fj.Production,"slack/events"),method:"POST",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new zp({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new zp({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /slack/events.");case"unknown":throw new zp({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}handleSlackSlashCommands(t){return ow.fromPromise(this.__handleSlackSlashCommands(t))}__handleSlackSlashCommands(t){return aTi(this,void 0,void 0,function*(){var r,n,i;let a=Mw((r=this._options)===null||r===void 0?void 0:r.headers,lj({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield Yw({url:Iw.join((i=(n=yield ly.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ly.get(this._options.environment))!==null&&i!==void 0?i:fj.Production,"slack/slash-commands"),method:"POST",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new zp({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new zp({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /slack/slash-commands.");case"unknown":throw new zp({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}handleSlackInteractions(t){return ow.fromPromise(this.__handleSlackInteractions(t))}__handleSlackInteractions(t){return aTi(this,void 0,void 0,function*(){var r,n,i;let a=Mw((r=this._options)===null||r===void 0?void 0:r.headers,lj({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield Yw({url:Iw.join((i=(n=yield ly.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ly.get(this._options.environment))!==null&&i!==void 0?i:fj.Production,"slack/interactions"),method:"POST",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new zp({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new zp({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling POST /slack/interactions.");case"unknown":throw new zp({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}handleSlackOauthCallback(t,r){return ow.fromPromise(this.__handleSlackOauthCallback(t,r))}__handleSlackOauthCallback(t,r){return aTi(this,void 0,void 0,function*(){var n,i,a;let{code:o,state:c}=t,d={};d.code=o,c!=null&&(d.state=c);let s=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),u=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"slack/oauth/callback"),method:"GET",headers:s,queryParameters:Object.assign(Object.assign({},d),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:u.body,rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 422:throw new lE(u.error.body,u.rawResponse);default:throw new zp({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new zp({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /slack/oauth/callback.");case"unknown":throw new zp({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}getSlackInstallLink(t,r){return ow.fromPromise(this.__getSlackInstallLink(t,r))}__getSlackInstallLink(t,r){return aTi(this,void 0,void 0,function*(){var n,i,a;let{domain:o}=t,c={};c.domain=o;let d=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,"slack/get-install"),method:"GET",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new lE(s.error.body,s.rawResponse);default:throw new zp({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new zp({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /slack/get-install.");case"unknown":throw new zp({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}listSlackIntegrations(t,r){return ow.fromPromise(this.__listSlackIntegrations(t,r))}__listSlackIntegrations(t,r){return aTi(this,void 0,void 0,function*(){var n,i,a;let o=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,`slack/integrations/${encodeURIComponent(t)}`),method:"GET",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new lE(c.error.body,c.rawResponse);default:throw new zp({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new zp({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /slack/integrations/{domain}.");case"unknown":throw new zp({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}getSlackInstallLinkById(t,r){return ow.fromPromise(this.__getSlackInstallLinkById(t,r))}__getSlackInstallLinkById(t,r){return aTi(this,void 0,void 0,function*(){var n,i,a;let o=Mw((n=this._options)===null||n===void 0?void 0:n.headers,lj({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield Yw({url:Iw.join((a=(i=yield ly.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ly.get(this._options.environment))!==null&&a!==void 0?a:fj.Production,`slack/get-install/${encodeURIComponent(t)}`),method:"GET",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new lE(c.error.body,c.rawResponse);default:throw new zp({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new zp({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new aw("Timeout exceeded when calling GET /slack/get-install/{integration_id}.");case"unknown":throw new zp({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}_getAuthorizationHeader(){return aTi(this,void 0,void 0,function*(){let t=yield ly.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var d3u=class{constructor(t={}){this._options=Object.assign(Object.assign({},t),{headers:Mw({"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"@fern-api/fai-sdk","X-Fern-SDK-Version":"0.0.2-9f9be72b3","X-Fern-Runtime":fOl.type,"X-Fern-Runtime-Version":fOl.version},t?.headers)})}get analytics(){var t;return(t=this._analytics)!==null&&t!==void 0?t:this._analytics=new dOl(this._options)}get chat(){var t;return(t=this._chat)!==null&&t!==void 0?t:this._chat=new pOl(this._options)}get conversation(){var t;return(t=this._conversation)!==null&&t!==void 0?t:this._conversation=new _Ol(this._options)}get discord(){var t;return(t=this._discord)!==null&&t!==void 0?t:this._discord=new hOl(this._options)}get document(){var t;return(t=this._document)!==null&&t!==void 0?t:this._document=new yOl(this._options)}get feedback(){var t;return(t=this._feedback)!==null&&t!==void 0?t:this._feedback=new vOl(this._options)}get github(){var t;return(t=this._github)!==null&&t!==void 0?t:this._github=new bOl(this._options)}get guidance(){var t;return(t=this._guidance)!==null&&t!==void 0?t:this._guidance=new gOl(this._options)}get health(){var t;return(t=this._health)!==null&&t!==void 0?t:this._health=new mOl(this._options)}get index(){var t;return(t=this._index)!==null&&t!==void 0?t:this._index=new AOl(this._options)}get mcp(){var t;return(t=this._mcp)!==null&&t!==void 0?t:this._mcp=new POl(this._options)}get query(){var t;return(t=this._query)!==null&&t!==void 0?t:this._query=new wOl(this._options)}get settings(){var t;return(t=this._settings)!==null&&t!==void 0?t:this._settings=new jOl(this._options)}get slack(){var t;return(t=this._slack)!==null&&t!==void 0?t:this._slack=new EOl(this._options)}};function NHE({token:e}){return new d3u({baseUrl:"https://fai.buildwithfern.com",token:e})}var AGE=fa(OGE(),1);var PGE=require("util"),oiL=(0,PGE.promisify)(AGE.default);async function wGE(e,t,r){let n=kUo(e,t),i=[];for(let a of n){let o=await Promise.all(a.map(async c=>{try{let d=await oiL(c);return d==null||d.height==null||d.width==null?void 0:{filePath:c,width:d.width,height:d.height,blurDataUrl:void 0}}catch(d){r.logger.error(`Failed to measure image size for ${c}. ${d?.message}`);return}}));i.push(...o.filter(nj))}return new Map(i.map(a=>[a.filePath,a]))}var uiL=10,jGE=10;async function IGE({token:e,organization:t,docsWorkspace:r,domain:n,customDomains:i,apiWorkspaces:a,ossWorkspaces:o,context:c,preview:d,editThisPage:s,isPrivate:u=!1,disableTemplates:l=!1,skipUpload:m=!1}){let A=wsa({token:e.value}),P=u?{type:"private",authType:"sso"}:{type:"public"},C,M=i[0]??n,T=siL(n),z=r.config.experimental?.dynamicSnippets,U=d||z,V=await new kRr(n,r,o,a,c,s,async re=>{let X=new Map(re.map(he=>[he.absoluteFilePath,he])),ne=re.map(he=>({...he,mediaType:IU_.lookup(he.absoluteFilePath)})).filter(he=>he.mediaType!==!1).filter(he=>Y8.parse(he.mediaType)?.isImage()??!1).map(he=>he.absoluteFilePath),me=await wGE(ne,uiL,c),be=[];[...me.values()].forEach(he=>{let Me=X.get(he.filePath);if(Me==null)return;let Be={filePath:ovi.FernRegistry.docs.v1.write.FilePath(dus(Me.relativeFilePath)),width:he.width,height:he.height,blurDataUrl:he.blurDataUrl,alt:void 0};be.push(Be)});let Ae=re.filter(({absoluteFilePath:he})=>!me.has(he)).map(({relativeFilePath:he})=>dus(he));if(d){let he=await A.docs.v2.write.startDocsPreviewRegister({orgId:ovi.FernRegistry.OrgId(t),authConfig:u?{type:"private",authType:"sso"}:{type:"public"},filepaths:Ae.map(Me=>ovi.FernRegistry.docs.v1.write.FilePath(Me)),images:be,basePath:T});return he.ok?(M=he.body.previewUrl,C=he.body.docsRegistrationId,m?c.logger.debug("Skip-upload mode: skipping file uploads for docs preview"):await EGE(he.body.uploadUrls,r.absoluteFilePath,c,jGE),SGE(he.body.uploadUrls,r.absoluteFilePath)):await DGE(he.error,c)}else{let he=await A.docs.v2.write.startDocsRegister({domain:n,customDomains:i,authConfig:P,apiId:ovi.FernRegistry.ApiId(""),orgId:ovi.FernRegistry.OrgId(t),filepaths:Ae.map(Me=>ovi.FernRegistry.docs.v1.write.FilePath(Me)),images:be});return he.ok?(C=he.body.docsRegistrationId,m?c.logger.debug("Skip-upload mode: skipping file uploads for docs"):await EGE(he.body.uploadUrls,r.absoluteFilePath,c,jGE),SGE(he.body.uploadUrls,r.absoluteFilePath)):DGE(he.error,c)}},async({ir:re,snippetsConfig:X,playgroundConfig:ee,apiName:ne,workspace:me})=>{let be=VIe({ir:re,snippetsConfig:X,playgroundConfig:ee,context:c}),Ae;z&&(Ae=await ciL({workspace:me,organization:t,context:c,snippetsConfig:X}));let he=await A.api.v1.register.registerApiDefinition({orgId:ovi.FernRegistry.OrgId(t),apiId:ovi.FernRegistry.ApiId(re.apiName.originalName),definition:be,definitionV2:void 0,dynamicIRs:Ae});if(he.ok)return c.logger.debug(`Registered API Definition ${ne}: ${he.body.apiDefinitionId}`),he.body.dynamicIRs&&Ae&&(m?c.logger.debug("Skip-upload mode: skipping dynamic IR uploads"):await liL({dynamicIRs:Ae,dynamicIRUploadUrls:he.body.dynamicIRs,context:c,apiId:he.body.apiDefinitionId})),he.body.apiDefinitionId;switch(he.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return ne!=null?c.failAndThrow(`Failed to publish docs because API definition (${ne}) could not be uploaded. Please contact support@buildwithfern.com
3043
3043
  ${JSON.stringify(he.error)}`):c.failAndThrow(`Failed to publish docs because API definition could not be uploaded. Please contact support@buildwithfern.com
3044
- ${JSON.stringify(he.error)}`)}}).resolve();if(C==null)return c.failAndThrow("Failed to publish docs.","Docs registration ID is missing.");c.logger.debug("Publishing docs...");let Y=await A.docs.v2.write.finishDocsRegister(ovi.FernRegistry.docs.v1.write.DocsRegistrationId(C),{docsDefinition:V,excludeApis:!0});if(Y.ok){let re=oje(M);await fiL({docsDefinition:V,organization:t,token:e,url:re.replace("https://",""),context:c,fdr:A,preview:d});let X=nTi(re,re);c.logger.info(od.green(`Published docs to ${X}`))}else switch(Y.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("Insufficient permissions. Failed to publish docs to "+n);case"DocsRegistrationIdNotFound":return c.failAndThrow("Failed to publish docs to "+n,`Docs registration ID ${C} does not exist.`);default:return c.failAndThrow("Failed to publish docs to "+n,Y.error)}}async function EGE(e,t,r,n){let i=Date.now(),a=Object.keys(e).length;r.logger.debug(`Start uploading ${a} files...`);let o=kUo(Object.entries(e),n),c=0;for(let s of o){await Promise.all(s.map(async([l,{uploadUrl:m}])=>{let A=ys.of(l),P=D1(t,A);try{let C=IU_.lookup(P);await hZ.put(m,await(0,CGE.readFile)(P),{headers:{"Content-Type":C===!1?"application/octet-stream":C,"Cache-Control":"public, max-age=31536000, immutable"}})}catch(C){r.failAndThrow(`Failed to upload ${P}`,C)}}));let u=Date.now();c+=s.length,r.logger.debug(`Uploaded ${c}/${a} files in ${u-i}ms`)}let d=Date.now();r.logger.debug(`Finished uploading ${a} files in ${d-i}ms`)}function SGE(e,t){let r=[];for(let[n,i]of Object.entries(e)){let a=ys.of(n),o=D1(t,a);r.push({relativeFilePath:a,absoluteFilePath:o,fileId:i.fileId})}return r}async function DGE(e,t){switch(await t.instrumentPostHogEvent({command:"docs-generation",properties:{error:JSON.stringify(e)}}),e.error){case"InvalidCustomDomainError":return t.failAndThrow("Your docs domain should end with docs.buildwithfern.com");case"InvalidDomainError":return t.failAndThrow("Please make sure that none of your custom domains are not overlapping (i.e. one is a substring of another)");case"UnauthorizedError":return t.failAndThrow("Please make sure that your FERN_TOKEN is set.");case"UserNotInOrgError":return t.failAndThrow("Please verify if you have access to the organization you are trying to publish the docs to. If you are not a member of the organization, please reach out to the organization owner.");case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function siL(e){try{return new URL(oje(e)).pathname}catch{return}}async function ciL({workspace:e,organization:t,context:r,snippetsConfig:n}){let i={};if(!e)return;Object.keys(n).length===0&&(r.logger.warn(`WARNING: No snippets defined for ${e.workspaceName}.`),r.logger.warn("Did you add snippets to your docs configuration?"),r.logger.warn("For more info: https://buildwithfern.com/learn/docs/api-references/sdk-snippets"));let a={typescript:n.typescriptSdk?.package,python:n.pythonSdk?.package,java:n.javaSdk?.coordinate,go:n.goSdk?.githubRepo,csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let o of e.generatorsConfiguration.groups)for(let c of o.generators){let d=rOl({apiName:e.workspaceName??"",organization:t,generatorInvocation:c}),s="";if(d?.outputConfig.type==="publish")switch(d.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":s=d.outputConfig.value.packageName;break;case"maven":s=d.outputConfig.value.coordinate;break;case"go":s=d.outputConfig.value.repoUrl;break;case"crates":s=d.outputConfig.value.packageName;break}if(c.language==="php"&&c.config&&typeof c.config=="object"&&"packageName"in c.config&&(s=c.config.packageName??""),!!c.language&&c.language&&a[c.language]===s){let u=JH({workspace:e,generationLanguage:c.language,keywords:void 0,smartCasing:c.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:s,version:void 0,context:r,sourceResolver:new VH(r,e),dynamicGeneratorConfig:d}),l=bau({ir:u,disableExamples:!0,smartCasing:c.smartCasing,generationLanguage:c.language,generatorConfig:d});l?i[c.language]={dynamicIR:l}:r.logger.debug(`Failed to create dynamic IR for ${c.language}`)}}for(let[o,c]of Object.entries(a))o&&c&&!Object.keys(i).includes(o)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${o} SDK snippets because of unknown package \`${c}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${c} package.`),r.logger.warn());if(Object.keys(i).length>0)return i}async function liL({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:n}){if(Object.keys(t).length>0)for(let[i,a]of Object.entries(t)){let o=e[i]?.dynamicIR;o?(await fetch(a.uploadUrl,{method:"PUT",body:JSON.stringify(o),headers:{"Content-Type":"application/octet-stream","Content-Length":JSON.stringify(o).length.toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${n}:${i}`):r.logger.warn(`Failed to upload dynamic IR for ${n}:${i}`):r.logger.warn(`Could not find matching dynamic IR to upload for ${n}:${i}`)}}async function fiL({docsDefinition:e,organization:t,token:r,url:n,context:i,fdr:a,preview:o}){if(e.config.aiChatConfig==null)return;i.logger.debug("Processing AI Chat configuration from docs.yml");let c=new URL(oje(n)).hostname;if(e.config.aiChatConfig.location!=null){for(let d of e.config.aiChatConfig.location)if(d==="docs"){let s=NHE({token:r.value}),u=await s.settings.getDocsSettings({domain:c});if(u.job_id)continue;i.logger.debug(`Starting Ask Fern docs content ${u.ask_ai_enabled?"reindexing":"indexing"}...`),(await a.docs.v2.write.addAlgoliaPreviewWhitelistEntry({domain:c})).ok?(u.ask_ai_enabled?await s.settings.reindexAskAi({domain:c,org_name:t}):await s.settings.toggleAskAi({domain:c,org_name:t,preview:o})).success&&i.logger.info(od.green("Note: it may take a few minutes after publishing for Ask Fern answers to reflect new content.")):i.logger.warn(`Failed to add domain ${c} to Algolia whitelist. Please try regenerating to test AI chat in preview.`)}}}async function MU_({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:a,instanceUrl:o,preview:c,disableTemplates:d,skipUpload:s}){let u=n.config.instances;if(n.config=O3i(n.config,{onError:A=>i.failAndThrow(A)},{substituteAsEmpty:c}),u.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(u.length>1&&o==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${u[0]?.url})`);return}let l=u.find(A=>A.url===o)??u[0];if(l==null){i.failAndThrow(`No docs instance with url ${o}. Failed to register.`);return}let m=[];l.customDomain!=null&&(typeof l.customDomain=="string"?m.push(l.customDomain):Array.isArray(l.customDomain)&&m.push(...l.customDomain)),await i.runInteractiveTask({name:l.url},async()=>{await IGE({docsWorkspace:n,customDomains:m,domain:l.url,token:a,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:c,editThisPage:l.editThisPage,isPrivate:l.private,disableTemplates:d,skipUpload:s})})}var MJE=fa(r6i(),1);var Ghe={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function bL(e,t){return r=>{r!=null&&e.docs?.(r,[...t,"docs"])}}function gDr({example:e,visitor:t,nodePath:r}){if(typeof e=="string")e.startsWith("$")&&t.exampleTypeReference?.(e,r);else if(uR(e))for(let n of Object.values(e))gDr({example:n,visitor:t,nodePath:r});else if(Array.isArray(e))for(let n of e)gDr({example:n,visitor:t,nodePath:r})}function p4r(e){return(t,r,{_default:n,validation:i,location:a}={})=>{e.typeReference?.({typeReference:t,_default:n,validation:i,location:a,nodePath:r},r)}}function MGE({service:e,visitor:t,nodePath:r}){t.httpService?.(e,r),dN(e,{url:n=>{t.serviceBaseUrl?.(n,[...r,"url"])},"base-path":Hc,"display-name":Hc,availability:Hc,headers:n=>{BGE({headers:n,visitor:t,nodePath:[...r,"headers"]})},audiences:Hc,auth:Hc,"path-parameters":n=>{h3u({pathParameters:n,visitor:t,nodePath:[...r,"path-parameters"]})},endpoints:n=>{for(let[i,a]of Object.entries(n)){let o=[...r,"endpoints",i];diL({endpointId:i,endpoint:a,service:e,visitor:t,nodePathForEndpoint:o})}},idempotent:Hc,transport:Hc,source:Hc})}function diL({endpointId:e,endpoint:t,service:r,visitor:n,nodePathForEndpoint:i}){let a=p4r(n);n.httpEndpoint?.({endpointId:e,endpoint:t,service:r},i),dN(t,{docs:bL(n,i),"display-name":Hc,availability:Hc,"base-path":Hc,path:Hc,idempotent:Hc,url:o=>{n.endpointBaseUrl?.({baseUrl:o,service:r},[...i,"url"])},"path-parameters":o=>{h3u({pathParameters:o,visitor:n,nodePath:[...i,"path-parameters"]})},request:o=>{if(o==null)return;let c=[...i,"request"];if(typeof o=="string"){a(o,c,{location:"requestReference"});return}dN(o,{name:Hc,docs:bL(n,c),"path-parameters":d=>{h3u({pathParameters:d,visitor:n,nodePath:[...c,"path-parameters"]})},"query-parameters":d=>{if(d!=null)for(let[s,u]of Object.entries(d)){let l=[...c,"query-parameters",s];n.queryParameter?.({queryParameterKey:s,queryParameter:u},l),typeof u=="string"?a(u,l):dN(u,{name:Hc,docs:bL(n,l),availability:Hc,type:m=>{a(m,[...l,"type"],{_default:u.default,validation:u.validation})},"allow-multiple":Hc,audiences:Hc,encoding:Hc,default:Hc,validation:Hc})}},"content-type":Hc,headers:d=>{BGE({headers:d,visitor:n,nodePath:[...c,"headers"]})},body:d=>{if(d==null)return;let s=[...c,"body"];typeof d=="string"?a(d,s,{location:"requestReference"}):OU(d)?(n.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:d},s),dN(d,{extends:u=>{if(u==null)return;let l=typeof u=="string"?[u]:u;for(let m of l){let A=[...s,"extends",m];n.extension?.(m,A),a(m,A)}},properties:u=>{if(u!=null)for(let[l,m]of Object.entries(u)){let A=[...s,"properties",l];typeof m=="string"?a(m,A,{location:Ghe.InlinedRequestProperty}):dN(m,{name:Hc,docs:bL(n,A),availability:Hc,type:P=>{a(P,[...A,"type"],{location:Ghe.InlinedRequestProperty,_default:m.default,validation:m.validation})},style:Hc,"content-type":Hc,audiences:Hc,encoding:Hc,default:Hc,validation:Hc})}},"extra-properties":Hc})):(bL(n,s)(d.docs),a(d.type,s))}})},audiences:Hc,method:Hc,auth:Hc,"stream-condition":o=>{n.streamCondition?.({streamCondition:o,endpoint:t},[...i,"stream-condition"])},"response-stream":o=>{o!=null&&(typeof o=="string"?a(o,[...i,"response-stream"],{location:Ghe.StreamingResponse}):a(o.type,[...i,"response-stream"],{location:Ghe.StreamingResponse}))},response:o=>{if(o==null)return;let c=[...i,"response"];typeof o=="string"?a(o,c,{location:Ghe.Response}):dN(o,{docs:bL(n,c),type:d=>{d!=null&&a(d,[...c,"type"],{location:Ghe.Response})},property:Hc,"status-code":Hc})},errors:o=>{if(o!=null)for(let c of o){let d=[...i,"errors",typeof c=="string"?c:c.error];typeof c=="string"?n.errorReference?.(c,d):dN(c,{docs:bL(n,d),error:s=>{n.errorReference?.(s,[...d,"error"])}})}},examples:o=>{if(o!=null)for(let[c,d]of o.entries())piL({nodePathForExample:[...i,{key:"examples",arrayIndex:c}],visitor:n,service:r,endpoint:t,example:d})},pagination:Hc,source:Hc,transport:Hc,retries:Hc})}function piL({nodePathForExample:e,visitor:t,service:r,endpoint:n,example:i}){if(i.headers==null&&i["path-parameters"]==null&&i["query-parameters"]==null&&i.request==null&&i.response==null&&i["code-samples"]!=null)return;t.exampleHttpEndpointCall?.({service:r,endpoint:n,example:i},e);let a=[...e,"headers"];if(t.exampleHeaders?.({service:r,endpoint:n,examples:i.headers},a),i.headers!=null)for(let u of Object.values(i.headers))gDr({example:u,visitor:t,nodePath:a});let o=[...e,"path-parameters"];if(t.examplePathParameters?.({service:r,endpoint:n,examples:i["path-parameters"]},o),i["path-parameters"]!=null)for(let u of Object.values(i["path-parameters"]))gDr({example:u,visitor:t,nodePath:o});let c=[...e,"query-parameters"];if(t.exampleQueryParameters?.({service:r,endpoint:n,examples:i["query-parameters"]},c),i["query-parameters"]!=null)for(let u of Object.values(i["query-parameters"]))gDr({example:u,visitor:t,nodePath:c});let d=[...e,"request"];t.exampleRequest?.({service:r,endpoint:n,example:i.request},d),i.request!=null&&gDr({example:i.request,visitor:t,nodePath:d});let s=[...e,"response"];if(t.exampleResponse?.({service:r,endpoint:n,example:i.response},s),i.response!=null&&$ua(n,i.response,{body:u=>{u.body!=null&&gDr({example:u.body,visitor:t,nodePath:s}),u.error!=null&&t.errorReference?.(u.error,[...s,"error"])},stream:u=>{for(let l of u.stream)gDr({example:l,visitor:t,nodePath:s})},events:u=>{for(let{data:l}of u.stream)gDr({example:l,visitor:t,nodePath:s})}}),i["code-samples"]!=null)for(let[u,l]of i["code-samples"].entries())t.exampleCodeSample?.({service:r,endpoint:n,example:i,sample:l},[...e,{key:"code-samples",arrayIndex:u}])}function h3u({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let n=p4r(t);for(let[i,a]of Object.entries(e)){let o=[...r,i];t.pathParameter?.({pathParameterKey:i,pathParameter:a},o),nXa(a)?typeof a=="string"?t.variableReference?.(a,o):dN(a,{docs:bL(t,o),variable:c=>t.variableReference?.(c,[...o,"variable"]),availability:Hc}):typeof a=="string"?n(a,o):dN(a,{docs:bL(t,o),type:c=>{n(c,[...o,"type"],{_default:a.default,validation:a.validation})},availability:Hc,encoding:Hc,default:Hc,validation:Hc,name:Hc,audiences:Hc})}}function BGE({headers:e,visitor:t,nodePath:r}){if(e==null)return;let n=p4r(t);for(let[i,a]of Object.entries(e)){let o=[...r,i];t.header?.({headerKey:i,header:a},o),typeof a=="string"?n(a,o):dN(a,{name:Hc,availability:Hc,type:c=>{n(c,o,{_default:a.default,validation:a.validation})},docs:bL(t,o),audiences:Hc,encoding:Hc,env:Hc,default:Hc,validation:Hc})}}function TGE({typeDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e)){let a=[...r,n];t.typeName?.(n,a),BU_({typeName:n,declaration:i,visitor:t,nodePathForType:a})}}function BU_({typeName:e,declaration:t,visitor:r,nodePathForType:n}){let i=p4r(r);r.typeDeclaration?.({typeName:{isInlined:!1,name:e},declaration:t,nodePath:n},n);let a=o=>{if(o!=null)for(let[c,d]of o.entries()){let s=[...n,{key:"examples",arrayIndex:c}];r.exampleType?.({typeName:e,typeDeclaration:t,example:d},s),gDr({example:d.value,nodePath:s,visitor:r})}};Tee(t,{alias:o=>{typeof o=="string"?i(o,n):dN(o,{type:c=>{i(c,[...n,"type"])},docs:bL(r,n),availability:Hc,audiences:Hc,examples:a,validation:Hc,encoding:Hc,source:Hc,inline:Hc})},object:o=>{dN(o,{docs:bL(r,n),extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let u=[...n,"extends",s];r.extension?.(s,u),i(s,u)}},properties:c=>{if(c!=null)for(let[d,s]of Object.entries(c)){let u=[...n,"properties",d];typeof s=="string"?i(s,u):dN(s,{name:Hc,docs:bL(r,u),availability:Hc,type:l=>{i(l,[...u,"type"],{_default:s.default,validation:s.validation})},audiences:Hc,encoding:Hc,default:Hc,validation:Hc,access:Hc})}},"extra-properties":Hc,availability:Hc,audiences:Hc,encoding:Hc,source:Hc,examples:a,inline:Hc})},discriminatedUnion:o=>{dN(o,{docs:bL(r,n),discriminant:Hc,extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let u=[...n,"extends",s];r.extension?.(s,u),i(s,u)}},union:c=>{for(let[d,s]of Object.entries(c)){let u=[...n,"union",d];typeof s=="string"?i(s,u):dN(s,{docs:bL(r,u),name:Hc,key:Hc,type:l=>{typeof l=="string"&&i(l,[...n,"type"])},"display-name":Hc,availability:Hc})}},"base-properties":Hc,availability:Hc,audiences:Hc,encoding:Hc,source:Hc,examples:a,inline:Hc})},undiscriminatedUnion:o=>{dN(o,{docs:bL(r,n),discriminated:Hc,union:c=>{for(let[d,s]of c.entries()){let u=[...n,`union[${d}]`];typeof s!="string"&&dN(s,{docs:bL(r,u),type:l=>{i(l,[...n,"type"])},"display-name":Hc,validation:Hc})}},availability:Hc,audiences:Hc,encoding:Hc,source:Hc,examples:a,inline:Hc})},enum:o=>{dN(o,{docs:bL(r,n),enum:c=>{for(let d of c){let s=[...n,typeof d=="string"?d:d.name??d.value];typeof d!="string"&&dN(d,{docs:bL(r,s),name:Hc,value:Hc,casing:Hc})}},availability:Hc,audiences:Hc,default:Hc,encoding:Hc,source:Hc,examples:a,inline:Hc})}})}function qGE({errorDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e)){let a=[...r,n];t.errorDeclaration?.({errorName:n,declaration:i},a),_iL({errorName:n,declaration:i,visitor:t,nodePathForError:a})}}function _iL({errorName:e,declaration:t,visitor:r,nodePathForError:n}){let i=p4r(r);typeof t=="string"?i(t,n):dN(t,{docs:bL(r,n),"status-code":Hc,type:a=>{if(a==null)return;let o=[...n,"type"];typeof a=="string"?i(a,o):BU_({typeName:e,declaration:a,visitor:r,nodePathForType:o})},examples:a=>{if(a!=null)for(let o of a){let c=[...n,"type"];r.exampleError?.({errorName:e,declaration:t,example:o},c)}}})}function RGE({imports:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e))t.import?.({importPath:i,importedAs:n},[...r,n])}function NGE({webhook:e,visitor:t,nodePathForWebhook:r}){let n=p4r(t);dN(e,{"display-name":Hc,method:Hc,examples:Hc,headers:i=>{hiL({headers:i,visitor:t,nodePath:[...r,"headers"]})},payload:i=>{let a=[...r,"payload"];if(typeof i=="string"){n(i,a,{location:"requestReference"});return}if(yiL(i)){n(i.type,[...a,"type"],{location:"requestReference"});return}let o=[...a];t.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:i},o),dN(i,{name:Hc,extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let u=[...o,"extends",s];t.extension?.(s,u),n(s,u)}},properties:c=>{if(c!=null)for(let[d,s]of Object.entries(c)){let u=[...o,"properties",d];typeof s=="string"?n(s,u,{location:Ghe.InlinedRequestProperty}):dN(s,{name:Hc,docs:bL(t,u),availability:Hc,type:l=>{n(l,[...u,"type"],{_default:s.default,validation:s.validation,location:Ghe.InlinedRequestProperty})},audiences:Hc,encoding:Hc,default:Hc,validation:Hc,access:Hc})}}})},audiences:Hc,availability:Hc,docs:bL(t,r)})}function hiL({headers:e,visitor:t,nodePath:r}){if(e==null)return;let n=p4r(t);for(let[i,a]of Object.entries(e)){let o=[...r,i];t.header?.({headerKey:i,header:a},o),typeof a=="string"?n(a,o):dN(a,{name:Hc,availability:Hc,type:c=>{n(c,o,{_default:a.default,validation:a.validation})},docs:bL(t,o),audiences:Hc,encoding:Hc,env:Hc,default:Hc,validation:Hc})}}function yiL(e){return e.type!=null}function Qme(e,t){dN(e,{docs:bL(t,[]),imports:r=>{RGE({imports:r,visitor:t,nodePath:["imports"]})},types:r=>{TGE({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:r=>{r!=null&&MGE({service:r,visitor:t,nodePath:["service"]})},webhooks:r=>{for(let[n,i]of Object.entries(r??{}))NGE({webhook:i,visitor:t,nodePathForWebhook:["webhooks",n]})},channel:Hc,errors:r=>{qGE({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}function TU_(e,t){dN(e,{docs:Hc,imports:Hc,types:Hc,service:Hc,webhooks:Hc,errors:Hc,channel:Hc,export:r=>{t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:r=>{t.navigation?.(r,["navigation"])}})}function qU_(e,t){t.file?.(e,[]),dN(e,{version:Hc,product:Hc,name:Hc,"default-url":Hc,"display-name":Hc,imports:Hc,auth:Hc,"idempotency-headers":Hc,"auth-schemes":r=>Object.entries(r??{}).map(([n,i])=>{Euf(i)&&t.oauth?.({name:n,oauth:i},["auth-scheme",n])}),pagination:Hc,"default-environment":r=>{t.defaultEnvironment?.(r,["default-environment"])},docs:Hc,headers:Hc,environments:r=>{if(r!=null)for(let[n,i]of Object.entries(r))t.environment?.({environmentId:n,environment:i},["environments",n])},"error-discrimination":r=>{t.errorDiscrimination?.(r,["error-discrimination"])},audiences:Hc,errors:r=>{if(r!=null)for(let n of r)t.errorReference?.(n,["errors",n])},"base-path":Hc,"path-parameters":r=>{h3u({pathParameters:r,visitor:t,nodePath:["path-parameters"]})},variables:r=>{if(r!=null)for(let[n,i]of Object.entries(r))t.variableDeclaration?.({variableId:n,variable:i},["variables",n])}})}var nAl=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function FGE({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let o=(c,d)=>{for(let s of r){let u=s.definitionFile?.[a];if(u!=null){let l=u(c,{relativeFilepath:e,contents:t});n(l.map(m=>({severity:m.severity,relativeFilepath:e,nodePath:d,message:m.message})))}}};return{[a]:o}}return{...i("docs"),...i("import"),...i("typeReference"),...i("typeDeclaration"),...i("typeName"),...i("httpService"),...i("httpEndpoint"),...i("pathParameter"),...i("queryParameter"),...i("streamCondition"),...i("header"),...i("errorDeclaration"),...i("errorReference"),...i("exampleType"),...i("exampleTypeReference"),...i("exampleHttpEndpointCall"),...i("exampleCodeSample"),...i("exampleHeaders"),...i("examplePathParameters"),...i("exampleQueryParameters"),...i("exampleRequest"),...i("exampleResponse"),...i("variableReference"),...i("extension"),...i("serviceBaseUrl"),...i("endpointBaseUrl"),...i("exampleError")}}function xGE({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let o=(c,d)=>{for(let s of r){let u=s.packageMarker?.[a];if(u!=null){let l=u(c,{relativeFilepath:e,contents:t});n(l.map(m=>({severity:m.severity,relativeFilepath:e,nodePath:d,message:m.message})))}}};return{[a]:o}}return{...i("export"),...i("navigation")}}function zGE({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let o=(c,d)=>{for(let s of r){let u=s.rootApiFile?.[a];if(u!=null){let l=u(c,{relativeFilepath:e,contents:t});n(l.map(m=>({severity:m.severity,relativeFilepath:e,nodePath:d,message:m.message})))}}};return{[a]:o}}return{...i("file"),...i("oauth"),...i("defaultEnvironment"),...i("environment"),...i("errorDiscrimination"),...i("errorReference"),...i("variableDeclaration"),...i("variableReference"),...i("pathParameter")}}var RU_={name:"content-type-only-for-multipart",DISABLE_RULE:!1,create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.request==null)return[];if(Kua(e.request)!=null)return[];if(typeof e.request!="string"&&e.request.body!=null&&OU(e.request.body)){let r=[];for(let[n,i]of Object.entries(e.request.body.properties??{}))typeof i!="string"&&i["content-type"]!=null&&r.push({severity:"fatal",message:`${n} has content-type, but the request is not multipart`});return r}return[]}}})};var e3=PIe({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var NU_={name:"exploded-form-data-is-array",create:({workspace:e})=>{let t=new MF(e);return{definitionFile:{httpEndpoint:({endpoint:r},{relativeFilepath:n,contents:i})=>{if(r.request==null||typeof r.request=="string"||r.request?.body==null||typeof r.request.body=="string")return[];if(!viL(r.request.body))return[];let a=[];for(let[o,c]of Object.entries(r.request.body.properties??{})){if(typeof c=="string"||c.style!=="exploded")continue;let d=eD({relativeFilepath:n,definitionFile:i,casingsGenerator:e3,rootApiFile:e.definition.rootApiFile.contents}),s=t.resolveType({type:c.type,file:d});if(s==null)return[];QGE(s)||a.push({message:`${o} is exploded and must be a list. Did you mean list<${c.type}>?`,severity:"error"})}return a}}}}};function QGE(e){return e._type!=="container"?!1:e.container._type==="list"?!0:e.container._type==="optional"||e.container._type==="nullable"?QGE(e.container.itemType):!1}function viL(e){return e?.properties!=null}var FU_={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(lwi(e.definition)),r=new Set;return t.forEach(n=>{let i=Jl(e.definition.absoluteFilePath,ys.of(n));r.add(i)}),{definitionFile:{import:({importedAs:n,importPath:i},{relativeFilepath:a})=>{let o=[],c=Jl(e.definition.absoluteFilePath,Wg(a),ys.of(i));return r.has(c)||o.push({severity:"fatal",message:`Import ${od.bold(n)} points to non-existent path ${od.bold(i)}.`}),o}}}}};function iAl(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(znt(r))for(let n of Object.keys(r.urls))t.includes(n)||t.push(n);return t},[])}var xU_={name:"matching-environment-urls",create:({workspace:e})=>{let t=iAl(e);return t.length===0?{}:{rootApiFile:{environment:({environmentId:r,environment:n})=>{let i=[],a=o=>{i.push({severity:"fatal",message:`Environment ${r} is missing URL for ${od.bold(o)}`})};return n9r(n,{singleBaseUrl:()=>{for(let o of t)a(o)},multipleBaseUrls:o=>{for(let c of t)o.urls[c]==null&&a(c)}}),i}}}}};var zU_={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=biL(e.definition.namedDefinitionFiles);return{definitionFile:{import:({importPath:r},{relativeFilepath:n})=>{let i=t[n];if(i==null)return[];let a=RQi({referencedIn:n,importPath:ys.of(r)});return i.filter(({chainWithoutStartingFilepath:c})=>c.length===0||c[0]===a).map(c=>({severity:"fatal",message:c.chainWithoutStartingFilepath.length===0?"A file cannot import itself":`Circular import detected: ${[c.startingFilepath,...c.chainWithoutStartingFilepath,c.startingFilepath].join(" -> ")}`}))}}}}};function biL(e){let t={};for(let r of uTr(e))t[r]=LGE(r,[r],e);return t}function LGE(e,t,r){let n=[],i=r[e];if(i==null)return[];if(i.contents.imports!=null)for(let a of Object.values(i.contents.imports)){let o=RQi({referencedIn:e,importPath:ys.of(a)});t.includes(o)?t[0]===o&&t[0]===giL(t)&&n.push({startingFilepath:o,chainWithoutStartingFilepath:t.slice(1)}):n.push(...LGE(o,[...t,o],r))}return n}function giL(e){return e.reduce((t,r)=>r<t?r:t)}var aAl=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new MF(t)}isTypeComplex(t,r){let n=eD({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:e3,rootApiFile:this.workspace.definition.rootApiFile.contents}),i=this.typeResolver.resolveType({type:t,file:n});if(i==null)return;let a=new Set;return this.isResolvedReferenceComplex({type:i,file:n,visited:a})}isResolvedReferenceComplex({type:t,file:r,visited:n}){switch(t._type){case"container":return this.isResolvedContainerComplex({type:t.container,file:r,visited:n});case"named":return this.isNamedTypeComplex({type:t,file:r,visited:n});case"primitive":return!1;case"unknown":return!0;default:tc(t)}}isResolvedContainerComplex({type:t,file:r,visited:n}){switch(t._type){case"literal":return!1;case"map":return(this.isResolvedReferenceComplex({type:t.keyType,file:r,visited:n})||this.isResolvedReferenceComplex({type:t.valueType,file:r,visited:n}))&&!(t.keyType._type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType._type==="unknown");case"optional":case"nullable":case"list":case"set":return this.isResolvedReferenceComplex({type:t.itemType,file:r,visited:n});default:tc(t)}}isNamedTypeComplex({type:t,file:r,visited:n}){if(n.has(t.rawName))return!1;if(n.add(t.rawName),q4i(t.declaration))return!0;if(JTr(t.declaration))return!1;if(Ix(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:n});if(iXa(t.declaration)){for(let i of t.declaration.union){let a=typeof i=="string"?i:i.type,o=this.isTypeComplex(a,{contents:r.definitionFile,relativeFilepath:r.relativeFilepath});if(o!=null&&o)return!0}return!1}tc(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:n,visited:i}){return XRr({typeName:t,objectDeclaration:r,typeResolver:this.typeResolver,definitionFile:n.definitionFile,workspace:this.workspace,filepathOfDeclaration:n.relativeFilepath,smartCasing:!1}).some(o=>this.isComplex({type:o.resolvedPropertyType,file:n,visited:i}))}isComplex({type:t,file:r,visited:n}){switch(t._type){case"named":return this.isNamedTypeComplex({type:t,file:r,visited:n});case"primitive":case"unknown":return!1;case"container":return this.isComplexContainer({type:t.container,file:r,visited:n});default:tc(t)}}isComplexContainer({type:t,file:r,visited:n}){switch(t._type){case"literal":return!1;case"map":return this.isComplex({type:t.keyType,file:r,visited:n})||this.isComplex({type:t.valueType,file:r,visited:n});case"optional":case"nullable":case"list":case"set":return this.isComplex({type:t.itemType,file:r,visited:n});default:tc(t)}}};var QU_={name:"no-complex-query-params",create:({workspace:e})=>{let t=new aAl(e);return{definitionFile:{queryParameter:({queryParameter:r},n)=>{let i=typeof r=="string"?r:r.type,a=t.isTypeComplex(i,n);return a!=null&&a?[{severity:"fatal",message:`${i} is not a valid type for a query parameter`}]:[]}}}}};var LU_={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===IWs?[{severity:"fatal",message:`Path parameter ${od.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function y3u({service:e,endpoint:t}){return e["base-path"]+t.path}var oAl=class{root=new UU_;registerEndpoint(t){this.root.insert(this.getPathPartsForEndpoint(t),t)}getConflictingEndpoints(t){return this.root.getMatchingEndpoints(this.getPathPartsForEndpoint(t)).filter(r=>!(r.relativeFilepath===t.relativeFilepath&&r.endpointId===t.endpointId)&&r.endpoint.method===t.endpoint.method)}getPathPartsForEndpoint(t){return y3u({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},UU_=class e{childPaths={};childPathParam;endpointsThatEndWithThisNode=[];insert(t,r){let[n,...i]=t;if(n==null){this.endpointsThatEndWithThisNode.push(r);return}(this.isPathParam(n)?this.childPathParam??=new e:this.childPaths[n]??=new e).insert(i,r)}getMatchingEndpoints(t){let[r,...n]=t;if(r==null)return this.endpointsThatEndWithThisNode;let i=[];if(this.isPathParam(r))i.push(...Object.values(this.childPaths).flatMap(a=>a.getMatchingEndpoints(n)));else{let a=this.childPaths[r];a!=null&&i.push(...a.getMatchingEndpoints(n))}return this.childPathParam!=null&&i.push(...this.childPathParam.getMatchingEndpoints(n)),i}isPathParam(t){return t.startsWith("{")&&t.endsWith("}")}};var VU_={name:"no-conflicting-endpoint-paths",create:({workspace:e})=>{let t=new oAl;return ete(e,(r,n)=>{Qme(n,{httpEndpoint:({service:i,endpointId:a,endpoint:o})=>{t.registerEndpoint({service:i,endpointId:a,endpoint:o,relativeFilepath:r})}})}),{definitionFile:{httpEndpoint:({service:r,endpoint:n,endpointId:i},{relativeFilepath:a})=>{let o=t.getConflictingEndpoints({service:r,endpointId:i,endpoint:n,relativeFilepath:a});return o.length===0?[]:[{severity:"warning",message:[`Endpoint path ${y3u({service:r,endpoint:n})} conflicts with other endpoints:`,...o.map(c=>` - ${c.relativeFilepath} -> ${c.endpointId} ${od.dim(y3u({service:c.service,endpoint:c.endpoint}))}`)].join(`
3044
+ ${JSON.stringify(he.error)}`)}}).resolve();if(C==null)return c.failAndThrow("Failed to publish docs.","Docs registration ID is missing.");c.logger.debug("Publishing docs...");let Y=await A.docs.v2.write.finishDocsRegister(ovi.FernRegistry.docs.v1.write.DocsRegistrationId(C),{docsDefinition:V});if(Y.ok){let re=oje(M);await fiL({docsDefinition:V,organization:t,token:e,url:re.replace("https://",""),context:c,fdr:A,preview:d});let X=nTi(re,re);c.logger.info(od.green(`Published docs to ${X}`))}else switch(Y.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("Insufficient permissions. Failed to publish docs to "+n);case"DocsRegistrationIdNotFound":return c.failAndThrow("Failed to publish docs to "+n,`Docs registration ID ${C} does not exist.`);default:return c.failAndThrow("Failed to publish docs to "+n,Y.error)}}async function EGE(e,t,r,n){let i=Date.now(),a=Object.keys(e).length;r.logger.debug(`Start uploading ${a} files...`);let o=kUo(Object.entries(e),n),c=0;for(let s of o){await Promise.all(s.map(async([l,{uploadUrl:m}])=>{let A=ys.of(l),P=D1(t,A);try{let C=IU_.lookup(P);await hZ.put(m,await(0,CGE.readFile)(P),{headers:{"Content-Type":C===!1?"application/octet-stream":C,"Cache-Control":"public, max-age=31536000, immutable"}})}catch(C){r.failAndThrow(`Failed to upload ${P}`,C)}}));let u=Date.now();c+=s.length,r.logger.debug(`Uploaded ${c}/${a} files in ${u-i}ms`)}let d=Date.now();r.logger.debug(`Finished uploading ${a} files in ${d-i}ms`)}function SGE(e,t){let r=[];for(let[n,i]of Object.entries(e)){let a=ys.of(n),o=D1(t,a);r.push({relativeFilePath:a,absoluteFilePath:o,fileId:i.fileId})}return r}async function DGE(e,t){switch(await t.instrumentPostHogEvent({command:"docs-generation",properties:{error:JSON.stringify(e)}}),e.error){case"InvalidCustomDomainError":return t.failAndThrow("Your docs domain should end with docs.buildwithfern.com");case"InvalidDomainError":return t.failAndThrow("Please make sure that none of your custom domains are not overlapping (i.e. one is a substring of another)");case"UnauthorizedError":return t.failAndThrow("Please make sure that your FERN_TOKEN is set.");case"UserNotInOrgError":return t.failAndThrow("Please verify if you have access to the organization you are trying to publish the docs to. If you are not a member of the organization, please reach out to the organization owner.");case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function siL(e){try{return new URL(oje(e)).pathname}catch{return}}async function ciL({workspace:e,organization:t,context:r,snippetsConfig:n}){let i={};if(!e)return;Object.keys(n).length===0&&(r.logger.warn(`WARNING: No snippets defined for ${e.workspaceName}.`),r.logger.warn("Did you add snippets to your docs configuration?"),r.logger.warn("For more info: https://buildwithfern.com/learn/docs/api-references/sdk-snippets"));let a={typescript:n.typescriptSdk?.package,python:n.pythonSdk?.package,java:n.javaSdk?.coordinate,go:n.goSdk?.githubRepo,csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let o of e.generatorsConfiguration.groups)for(let c of o.generators){let d=rOl({apiName:e.workspaceName??"",organization:t,generatorInvocation:c}),s="";if(d?.outputConfig.type==="publish")switch(d.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":s=d.outputConfig.value.packageName;break;case"maven":s=d.outputConfig.value.coordinate;break;case"go":s=d.outputConfig.value.repoUrl;break;case"crates":s=d.outputConfig.value.packageName;break}if(c.language==="php"&&c.config&&typeof c.config=="object"&&"packageName"in c.config&&(s=c.config.packageName??""),!!c.language&&c.language&&a[c.language]===s){let u=JH({workspace:e,generationLanguage:c.language,keywords:void 0,smartCasing:c.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:s,version:void 0,context:r,sourceResolver:new VH(r,e),dynamicGeneratorConfig:d}),l=bau({ir:u,disableExamples:!0,smartCasing:c.smartCasing,generationLanguage:c.language,generatorConfig:d});l?i[c.language]={dynamicIR:l}:r.logger.debug(`Failed to create dynamic IR for ${c.language}`)}}for(let[o,c]of Object.entries(a))o&&c&&!Object.keys(i).includes(o)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${o} SDK snippets because of unknown package \`${c}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${c} package.`),r.logger.warn());if(Object.keys(i).length>0)return i}async function liL({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:n}){if(Object.keys(t).length>0)for(let[i,a]of Object.entries(t)){let o=e[i]?.dynamicIR;o?(await fetch(a.uploadUrl,{method:"PUT",body:JSON.stringify(o),headers:{"Content-Type":"application/octet-stream","Content-Length":JSON.stringify(o).length.toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${n}:${i}`):r.logger.warn(`Failed to upload dynamic IR for ${n}:${i}`):r.logger.warn(`Could not find matching dynamic IR to upload for ${n}:${i}`)}}async function fiL({docsDefinition:e,organization:t,token:r,url:n,context:i,fdr:a,preview:o}){if(e.config.aiChatConfig==null)return;i.logger.debug("Processing AI Chat configuration from docs.yml");let c=new URL(oje(n)).hostname;if(e.config.aiChatConfig.location!=null){for(let d of e.config.aiChatConfig.location)if(d==="docs"){let s=NHE({token:r.value}),u=await s.settings.getDocsSettings({domain:c});if(u.job_id)continue;i.logger.debug(`Starting Ask Fern docs content ${u.ask_ai_enabled?"reindexing":"indexing"}...`),(await a.docs.v2.write.addAlgoliaPreviewWhitelistEntry({domain:c})).ok?(u.ask_ai_enabled?await s.settings.reindexAskAi({domain:c,org_name:t}):await s.settings.toggleAskAi({domain:c,org_name:t,preview:o})).success&&i.logger.info(od.green("Note: it may take a few minutes after publishing for Ask Fern answers to reflect new content.")):i.logger.warn(`Failed to add domain ${c} to Algolia whitelist. Please try regenerating to test AI chat in preview.`)}}}async function MU_({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:a,instanceUrl:o,preview:c,disableTemplates:d,skipUpload:s}){let u=n.config.instances;if(n.config=O3i(n.config,{onError:A=>i.failAndThrow(A)},{substituteAsEmpty:c}),u.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(u.length>1&&o==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${u[0]?.url})`);return}let l=u.find(A=>A.url===o)??u[0];if(l==null){i.failAndThrow(`No docs instance with url ${o}. Failed to register.`);return}let m=[];l.customDomain!=null&&(typeof l.customDomain=="string"?m.push(l.customDomain):Array.isArray(l.customDomain)&&m.push(...l.customDomain)),await i.runInteractiveTask({name:l.url},async()=>{await IGE({docsWorkspace:n,customDomains:m,domain:l.url,token:a,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:c,editThisPage:l.editThisPage,isPrivate:l.private,disableTemplates:d,skipUpload:s})})}var MJE=fa(r6i(),1);var Ghe={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function bL(e,t){return r=>{r!=null&&e.docs?.(r,[...t,"docs"])}}function gDr({example:e,visitor:t,nodePath:r}){if(typeof e=="string")e.startsWith("$")&&t.exampleTypeReference?.(e,r);else if(uR(e))for(let n of Object.values(e))gDr({example:n,visitor:t,nodePath:r});else if(Array.isArray(e))for(let n of e)gDr({example:n,visitor:t,nodePath:r})}function p4r(e){return(t,r,{_default:n,validation:i,location:a}={})=>{e.typeReference?.({typeReference:t,_default:n,validation:i,location:a,nodePath:r},r)}}function MGE({service:e,visitor:t,nodePath:r}){t.httpService?.(e,r),dN(e,{url:n=>{t.serviceBaseUrl?.(n,[...r,"url"])},"base-path":Hc,"display-name":Hc,availability:Hc,headers:n=>{BGE({headers:n,visitor:t,nodePath:[...r,"headers"]})},audiences:Hc,auth:Hc,"path-parameters":n=>{h3u({pathParameters:n,visitor:t,nodePath:[...r,"path-parameters"]})},endpoints:n=>{for(let[i,a]of Object.entries(n)){let o=[...r,"endpoints",i];diL({endpointId:i,endpoint:a,service:e,visitor:t,nodePathForEndpoint:o})}},idempotent:Hc,transport:Hc,source:Hc})}function diL({endpointId:e,endpoint:t,service:r,visitor:n,nodePathForEndpoint:i}){let a=p4r(n);n.httpEndpoint?.({endpointId:e,endpoint:t,service:r},i),dN(t,{docs:bL(n,i),"display-name":Hc,availability:Hc,"base-path":Hc,path:Hc,idempotent:Hc,url:o=>{n.endpointBaseUrl?.({baseUrl:o,service:r},[...i,"url"])},"path-parameters":o=>{h3u({pathParameters:o,visitor:n,nodePath:[...i,"path-parameters"]})},request:o=>{if(o==null)return;let c=[...i,"request"];if(typeof o=="string"){a(o,c,{location:"requestReference"});return}dN(o,{name:Hc,docs:bL(n,c),"path-parameters":d=>{h3u({pathParameters:d,visitor:n,nodePath:[...c,"path-parameters"]})},"query-parameters":d=>{if(d!=null)for(let[s,u]of Object.entries(d)){let l=[...c,"query-parameters",s];n.queryParameter?.({queryParameterKey:s,queryParameter:u},l),typeof u=="string"?a(u,l):dN(u,{name:Hc,docs:bL(n,l),availability:Hc,type:m=>{a(m,[...l,"type"],{_default:u.default,validation:u.validation})},"allow-multiple":Hc,audiences:Hc,encoding:Hc,default:Hc,validation:Hc})}},"content-type":Hc,headers:d=>{BGE({headers:d,visitor:n,nodePath:[...c,"headers"]})},body:d=>{if(d==null)return;let s=[...c,"body"];typeof d=="string"?a(d,s,{location:"requestReference"}):OU(d)?(n.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:d},s),dN(d,{extends:u=>{if(u==null)return;let l=typeof u=="string"?[u]:u;for(let m of l){let A=[...s,"extends",m];n.extension?.(m,A),a(m,A)}},properties:u=>{if(u!=null)for(let[l,m]of Object.entries(u)){let A=[...s,"properties",l];typeof m=="string"?a(m,A,{location:Ghe.InlinedRequestProperty}):dN(m,{name:Hc,docs:bL(n,A),availability:Hc,type:P=>{a(P,[...A,"type"],{location:Ghe.InlinedRequestProperty,_default:m.default,validation:m.validation})},style:Hc,"content-type":Hc,audiences:Hc,encoding:Hc,default:Hc,validation:Hc})}},"extra-properties":Hc})):(bL(n,s)(d.docs),a(d.type,s))}})},audiences:Hc,method:Hc,auth:Hc,"stream-condition":o=>{n.streamCondition?.({streamCondition:o,endpoint:t},[...i,"stream-condition"])},"response-stream":o=>{o!=null&&(typeof o=="string"?a(o,[...i,"response-stream"],{location:Ghe.StreamingResponse}):a(o.type,[...i,"response-stream"],{location:Ghe.StreamingResponse}))},response:o=>{if(o==null)return;let c=[...i,"response"];typeof o=="string"?a(o,c,{location:Ghe.Response}):dN(o,{docs:bL(n,c),type:d=>{d!=null&&a(d,[...c,"type"],{location:Ghe.Response})},property:Hc,"status-code":Hc})},errors:o=>{if(o!=null)for(let c of o){let d=[...i,"errors",typeof c=="string"?c:c.error];typeof c=="string"?n.errorReference?.(c,d):dN(c,{docs:bL(n,d),error:s=>{n.errorReference?.(s,[...d,"error"])}})}},examples:o=>{if(o!=null)for(let[c,d]of o.entries())piL({nodePathForExample:[...i,{key:"examples",arrayIndex:c}],visitor:n,service:r,endpoint:t,example:d})},pagination:Hc,source:Hc,transport:Hc,retries:Hc})}function piL({nodePathForExample:e,visitor:t,service:r,endpoint:n,example:i}){if(i.headers==null&&i["path-parameters"]==null&&i["query-parameters"]==null&&i.request==null&&i.response==null&&i["code-samples"]!=null)return;t.exampleHttpEndpointCall?.({service:r,endpoint:n,example:i},e);let a=[...e,"headers"];if(t.exampleHeaders?.({service:r,endpoint:n,examples:i.headers},a),i.headers!=null)for(let u of Object.values(i.headers))gDr({example:u,visitor:t,nodePath:a});let o=[...e,"path-parameters"];if(t.examplePathParameters?.({service:r,endpoint:n,examples:i["path-parameters"]},o),i["path-parameters"]!=null)for(let u of Object.values(i["path-parameters"]))gDr({example:u,visitor:t,nodePath:o});let c=[...e,"query-parameters"];if(t.exampleQueryParameters?.({service:r,endpoint:n,examples:i["query-parameters"]},c),i["query-parameters"]!=null)for(let u of Object.values(i["query-parameters"]))gDr({example:u,visitor:t,nodePath:c});let d=[...e,"request"];t.exampleRequest?.({service:r,endpoint:n,example:i.request},d),i.request!=null&&gDr({example:i.request,visitor:t,nodePath:d});let s=[...e,"response"];if(t.exampleResponse?.({service:r,endpoint:n,example:i.response},s),i.response!=null&&$ua(n,i.response,{body:u=>{u.body!=null&&gDr({example:u.body,visitor:t,nodePath:s}),u.error!=null&&t.errorReference?.(u.error,[...s,"error"])},stream:u=>{for(let l of u.stream)gDr({example:l,visitor:t,nodePath:s})},events:u=>{for(let{data:l}of u.stream)gDr({example:l,visitor:t,nodePath:s})}}),i["code-samples"]!=null)for(let[u,l]of i["code-samples"].entries())t.exampleCodeSample?.({service:r,endpoint:n,example:i,sample:l},[...e,{key:"code-samples",arrayIndex:u}])}function h3u({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let n=p4r(t);for(let[i,a]of Object.entries(e)){let o=[...r,i];t.pathParameter?.({pathParameterKey:i,pathParameter:a},o),nXa(a)?typeof a=="string"?t.variableReference?.(a,o):dN(a,{docs:bL(t,o),variable:c=>t.variableReference?.(c,[...o,"variable"]),availability:Hc}):typeof a=="string"?n(a,o):dN(a,{docs:bL(t,o),type:c=>{n(c,[...o,"type"],{_default:a.default,validation:a.validation})},availability:Hc,encoding:Hc,default:Hc,validation:Hc,name:Hc,audiences:Hc})}}function BGE({headers:e,visitor:t,nodePath:r}){if(e==null)return;let n=p4r(t);for(let[i,a]of Object.entries(e)){let o=[...r,i];t.header?.({headerKey:i,header:a},o),typeof a=="string"?n(a,o):dN(a,{name:Hc,availability:Hc,type:c=>{n(c,o,{_default:a.default,validation:a.validation})},docs:bL(t,o),audiences:Hc,encoding:Hc,env:Hc,default:Hc,validation:Hc})}}function TGE({typeDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e)){let a=[...r,n];t.typeName?.(n,a),BU_({typeName:n,declaration:i,visitor:t,nodePathForType:a})}}function BU_({typeName:e,declaration:t,visitor:r,nodePathForType:n}){let i=p4r(r);r.typeDeclaration?.({typeName:{isInlined:!1,name:e},declaration:t,nodePath:n},n);let a=o=>{if(o!=null)for(let[c,d]of o.entries()){let s=[...n,{key:"examples",arrayIndex:c}];r.exampleType?.({typeName:e,typeDeclaration:t,example:d},s),gDr({example:d.value,nodePath:s,visitor:r})}};Tee(t,{alias:o=>{typeof o=="string"?i(o,n):dN(o,{type:c=>{i(c,[...n,"type"])},docs:bL(r,n),availability:Hc,audiences:Hc,examples:a,validation:Hc,encoding:Hc,source:Hc,inline:Hc})},object:o=>{dN(o,{docs:bL(r,n),extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let u=[...n,"extends",s];r.extension?.(s,u),i(s,u)}},properties:c=>{if(c!=null)for(let[d,s]of Object.entries(c)){let u=[...n,"properties",d];typeof s=="string"?i(s,u):dN(s,{name:Hc,docs:bL(r,u),availability:Hc,type:l=>{i(l,[...u,"type"],{_default:s.default,validation:s.validation})},audiences:Hc,encoding:Hc,default:Hc,validation:Hc,access:Hc})}},"extra-properties":Hc,availability:Hc,audiences:Hc,encoding:Hc,source:Hc,examples:a,inline:Hc})},discriminatedUnion:o=>{dN(o,{docs:bL(r,n),discriminant:Hc,extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let u=[...n,"extends",s];r.extension?.(s,u),i(s,u)}},union:c=>{for(let[d,s]of Object.entries(c)){let u=[...n,"union",d];typeof s=="string"?i(s,u):dN(s,{docs:bL(r,u),name:Hc,key:Hc,type:l=>{typeof l=="string"&&i(l,[...n,"type"])},"display-name":Hc,availability:Hc})}},"base-properties":Hc,availability:Hc,audiences:Hc,encoding:Hc,source:Hc,examples:a,inline:Hc})},undiscriminatedUnion:o=>{dN(o,{docs:bL(r,n),discriminated:Hc,union:c=>{for(let[d,s]of c.entries()){let u=[...n,`union[${d}]`];typeof s!="string"&&dN(s,{docs:bL(r,u),type:l=>{i(l,[...n,"type"])},"display-name":Hc,validation:Hc})}},availability:Hc,audiences:Hc,encoding:Hc,source:Hc,examples:a,inline:Hc})},enum:o=>{dN(o,{docs:bL(r,n),enum:c=>{for(let d of c){let s=[...n,typeof d=="string"?d:d.name??d.value];typeof d!="string"&&dN(d,{docs:bL(r,s),name:Hc,value:Hc,casing:Hc})}},availability:Hc,audiences:Hc,default:Hc,encoding:Hc,source:Hc,examples:a,inline:Hc})}})}function qGE({errorDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e)){let a=[...r,n];t.errorDeclaration?.({errorName:n,declaration:i},a),_iL({errorName:n,declaration:i,visitor:t,nodePathForError:a})}}function _iL({errorName:e,declaration:t,visitor:r,nodePathForError:n}){let i=p4r(r);typeof t=="string"?i(t,n):dN(t,{docs:bL(r,n),"status-code":Hc,type:a=>{if(a==null)return;let o=[...n,"type"];typeof a=="string"?i(a,o):BU_({typeName:e,declaration:a,visitor:r,nodePathForType:o})},examples:a=>{if(a!=null)for(let o of a){let c=[...n,"type"];r.exampleError?.({errorName:e,declaration:t,example:o},c)}}})}function RGE({imports:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e))t.import?.({importPath:i,importedAs:n},[...r,n])}function NGE({webhook:e,visitor:t,nodePathForWebhook:r}){let n=p4r(t);dN(e,{"display-name":Hc,method:Hc,examples:Hc,headers:i=>{hiL({headers:i,visitor:t,nodePath:[...r,"headers"]})},payload:i=>{let a=[...r,"payload"];if(typeof i=="string"){n(i,a,{location:"requestReference"});return}if(yiL(i)){n(i.type,[...a,"type"],{location:"requestReference"});return}let o=[...a];t.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:i},o),dN(i,{name:Hc,extends:c=>{if(c==null)return;let d=typeof c=="string"?[c]:c;for(let s of d){let u=[...o,"extends",s];t.extension?.(s,u),n(s,u)}},properties:c=>{if(c!=null)for(let[d,s]of Object.entries(c)){let u=[...o,"properties",d];typeof s=="string"?n(s,u,{location:Ghe.InlinedRequestProperty}):dN(s,{name:Hc,docs:bL(t,u),availability:Hc,type:l=>{n(l,[...u,"type"],{_default:s.default,validation:s.validation,location:Ghe.InlinedRequestProperty})},audiences:Hc,encoding:Hc,default:Hc,validation:Hc,access:Hc})}}})},audiences:Hc,availability:Hc,docs:bL(t,r)})}function hiL({headers:e,visitor:t,nodePath:r}){if(e==null)return;let n=p4r(t);for(let[i,a]of Object.entries(e)){let o=[...r,i];t.header?.({headerKey:i,header:a},o),typeof a=="string"?n(a,o):dN(a,{name:Hc,availability:Hc,type:c=>{n(c,o,{_default:a.default,validation:a.validation})},docs:bL(t,o),audiences:Hc,encoding:Hc,env:Hc,default:Hc,validation:Hc})}}function yiL(e){return e.type!=null}function Qme(e,t){dN(e,{docs:bL(t,[]),imports:r=>{RGE({imports:r,visitor:t,nodePath:["imports"]})},types:r=>{TGE({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:r=>{r!=null&&MGE({service:r,visitor:t,nodePath:["service"]})},webhooks:r=>{for(let[n,i]of Object.entries(r??{}))NGE({webhook:i,visitor:t,nodePathForWebhook:["webhooks",n]})},channel:Hc,errors:r=>{qGE({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}function TU_(e,t){dN(e,{docs:Hc,imports:Hc,types:Hc,service:Hc,webhooks:Hc,errors:Hc,channel:Hc,export:r=>{t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:r=>{t.navigation?.(r,["navigation"])}})}function qU_(e,t){t.file?.(e,[]),dN(e,{version:Hc,product:Hc,name:Hc,"default-url":Hc,"display-name":Hc,imports:Hc,auth:Hc,"idempotency-headers":Hc,"auth-schemes":r=>Object.entries(r??{}).map(([n,i])=>{Euf(i)&&t.oauth?.({name:n,oauth:i},["auth-scheme",n])}),pagination:Hc,"default-environment":r=>{t.defaultEnvironment?.(r,["default-environment"])},docs:Hc,headers:Hc,environments:r=>{if(r!=null)for(let[n,i]of Object.entries(r))t.environment?.({environmentId:n,environment:i},["environments",n])},"error-discrimination":r=>{t.errorDiscrimination?.(r,["error-discrimination"])},audiences:Hc,errors:r=>{if(r!=null)for(let n of r)t.errorReference?.(n,["errors",n])},"base-path":Hc,"path-parameters":r=>{h3u({pathParameters:r,visitor:t,nodePath:["path-parameters"]})},variables:r=>{if(r!=null)for(let[n,i]of Object.entries(r))t.variableDeclaration?.({variableId:n,variable:i},["variables",n])}})}var nAl=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function FGE({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let o=(c,d)=>{for(let s of r){let u=s.definitionFile?.[a];if(u!=null){let l=u(c,{relativeFilepath:e,contents:t});n(l.map(m=>({severity:m.severity,relativeFilepath:e,nodePath:d,message:m.message})))}}};return{[a]:o}}return{...i("docs"),...i("import"),...i("typeReference"),...i("typeDeclaration"),...i("typeName"),...i("httpService"),...i("httpEndpoint"),...i("pathParameter"),...i("queryParameter"),...i("streamCondition"),...i("header"),...i("errorDeclaration"),...i("errorReference"),...i("exampleType"),...i("exampleTypeReference"),...i("exampleHttpEndpointCall"),...i("exampleCodeSample"),...i("exampleHeaders"),...i("examplePathParameters"),...i("exampleQueryParameters"),...i("exampleRequest"),...i("exampleResponse"),...i("variableReference"),...i("extension"),...i("serviceBaseUrl"),...i("endpointBaseUrl"),...i("exampleError")}}function xGE({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let o=(c,d)=>{for(let s of r){let u=s.packageMarker?.[a];if(u!=null){let l=u(c,{relativeFilepath:e,contents:t});n(l.map(m=>({severity:m.severity,relativeFilepath:e,nodePath:d,message:m.message})))}}};return{[a]:o}}return{...i("export"),...i("navigation")}}function zGE({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let o=(c,d)=>{for(let s of r){let u=s.rootApiFile?.[a];if(u!=null){let l=u(c,{relativeFilepath:e,contents:t});n(l.map(m=>({severity:m.severity,relativeFilepath:e,nodePath:d,message:m.message})))}}};return{[a]:o}}return{...i("file"),...i("oauth"),...i("defaultEnvironment"),...i("environment"),...i("errorDiscrimination"),...i("errorReference"),...i("variableDeclaration"),...i("variableReference"),...i("pathParameter")}}var RU_={name:"content-type-only-for-multipart",DISABLE_RULE:!1,create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.request==null)return[];if(Kua(e.request)!=null)return[];if(typeof e.request!="string"&&e.request.body!=null&&OU(e.request.body)){let r=[];for(let[n,i]of Object.entries(e.request.body.properties??{}))typeof i!="string"&&i["content-type"]!=null&&r.push({severity:"fatal",message:`${n} has content-type, but the request is not multipart`});return r}return[]}}})};var e3=PIe({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var NU_={name:"exploded-form-data-is-array",create:({workspace:e})=>{let t=new MF(e);return{definitionFile:{httpEndpoint:({endpoint:r},{relativeFilepath:n,contents:i})=>{if(r.request==null||typeof r.request=="string"||r.request?.body==null||typeof r.request.body=="string")return[];if(!viL(r.request.body))return[];let a=[];for(let[o,c]of Object.entries(r.request.body.properties??{})){if(typeof c=="string"||c.style!=="exploded")continue;let d=eD({relativeFilepath:n,definitionFile:i,casingsGenerator:e3,rootApiFile:e.definition.rootApiFile.contents}),s=t.resolveType({type:c.type,file:d});if(s==null)return[];QGE(s)||a.push({message:`${o} is exploded and must be a list. Did you mean list<${c.type}>?`,severity:"error"})}return a}}}}};function QGE(e){return e._type!=="container"?!1:e.container._type==="list"?!0:e.container._type==="optional"||e.container._type==="nullable"?QGE(e.container.itemType):!1}function viL(e){return e?.properties!=null}var FU_={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(lwi(e.definition)),r=new Set;return t.forEach(n=>{let i=Jl(e.definition.absoluteFilePath,ys.of(n));r.add(i)}),{definitionFile:{import:({importedAs:n,importPath:i},{relativeFilepath:a})=>{let o=[],c=Jl(e.definition.absoluteFilePath,Wg(a),ys.of(i));return r.has(c)||o.push({severity:"fatal",message:`Import ${od.bold(n)} points to non-existent path ${od.bold(i)}.`}),o}}}}};function iAl(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(znt(r))for(let n of Object.keys(r.urls))t.includes(n)||t.push(n);return t},[])}var xU_={name:"matching-environment-urls",create:({workspace:e})=>{let t=iAl(e);return t.length===0?{}:{rootApiFile:{environment:({environmentId:r,environment:n})=>{let i=[],a=o=>{i.push({severity:"fatal",message:`Environment ${r} is missing URL for ${od.bold(o)}`})};return n9r(n,{singleBaseUrl:()=>{for(let o of t)a(o)},multipleBaseUrls:o=>{for(let c of t)o.urls[c]==null&&a(c)}}),i}}}}};var zU_={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=biL(e.definition.namedDefinitionFiles);return{definitionFile:{import:({importPath:r},{relativeFilepath:n})=>{let i=t[n];if(i==null)return[];let a=RQi({referencedIn:n,importPath:ys.of(r)});return i.filter(({chainWithoutStartingFilepath:c})=>c.length===0||c[0]===a).map(c=>({severity:"fatal",message:c.chainWithoutStartingFilepath.length===0?"A file cannot import itself":`Circular import detected: ${[c.startingFilepath,...c.chainWithoutStartingFilepath,c.startingFilepath].join(" -> ")}`}))}}}}};function biL(e){let t={};for(let r of uTr(e))t[r]=LGE(r,[r],e);return t}function LGE(e,t,r){let n=[],i=r[e];if(i==null)return[];if(i.contents.imports!=null)for(let a of Object.values(i.contents.imports)){let o=RQi({referencedIn:e,importPath:ys.of(a)});t.includes(o)?t[0]===o&&t[0]===giL(t)&&n.push({startingFilepath:o,chainWithoutStartingFilepath:t.slice(1)}):n.push(...LGE(o,[...t,o],r))}return n}function giL(e){return e.reduce((t,r)=>r<t?r:t)}var aAl=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new MF(t)}isTypeComplex(t,r){let n=eD({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:e3,rootApiFile:this.workspace.definition.rootApiFile.contents}),i=this.typeResolver.resolveType({type:t,file:n});if(i==null)return;let a=new Set;return this.isResolvedReferenceComplex({type:i,file:n,visited:a})}isResolvedReferenceComplex({type:t,file:r,visited:n}){switch(t._type){case"container":return this.isResolvedContainerComplex({type:t.container,file:r,visited:n});case"named":return this.isNamedTypeComplex({type:t,file:r,visited:n});case"primitive":return!1;case"unknown":return!0;default:tc(t)}}isResolvedContainerComplex({type:t,file:r,visited:n}){switch(t._type){case"literal":return!1;case"map":return(this.isResolvedReferenceComplex({type:t.keyType,file:r,visited:n})||this.isResolvedReferenceComplex({type:t.valueType,file:r,visited:n}))&&!(t.keyType._type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType._type==="unknown");case"optional":case"nullable":case"list":case"set":return this.isResolvedReferenceComplex({type:t.itemType,file:r,visited:n});default:tc(t)}}isNamedTypeComplex({type:t,file:r,visited:n}){if(n.has(t.rawName))return!1;if(n.add(t.rawName),q4i(t.declaration))return!0;if(JTr(t.declaration))return!1;if(Ix(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:n});if(iXa(t.declaration)){for(let i of t.declaration.union){let a=typeof i=="string"?i:i.type,o=this.isTypeComplex(a,{contents:r.definitionFile,relativeFilepath:r.relativeFilepath});if(o!=null&&o)return!0}return!1}tc(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:n,visited:i}){return XRr({typeName:t,objectDeclaration:r,typeResolver:this.typeResolver,definitionFile:n.definitionFile,workspace:this.workspace,filepathOfDeclaration:n.relativeFilepath,smartCasing:!1}).some(o=>this.isComplex({type:o.resolvedPropertyType,file:n,visited:i}))}isComplex({type:t,file:r,visited:n}){switch(t._type){case"named":return this.isNamedTypeComplex({type:t,file:r,visited:n});case"primitive":case"unknown":return!1;case"container":return this.isComplexContainer({type:t.container,file:r,visited:n});default:tc(t)}}isComplexContainer({type:t,file:r,visited:n}){switch(t._type){case"literal":return!1;case"map":return this.isComplex({type:t.keyType,file:r,visited:n})||this.isComplex({type:t.valueType,file:r,visited:n});case"optional":case"nullable":case"list":case"set":return this.isComplex({type:t.itemType,file:r,visited:n});default:tc(t)}}};var QU_={name:"no-complex-query-params",create:({workspace:e})=>{let t=new aAl(e);return{definitionFile:{queryParameter:({queryParameter:r},n)=>{let i=typeof r=="string"?r:r.type,a=t.isTypeComplex(i,n);return a!=null&&a?[{severity:"fatal",message:`${i} is not a valid type for a query parameter`}]:[]}}}}};var LU_={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===IWs?[{severity:"fatal",message:`Path parameter ${od.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function y3u({service:e,endpoint:t}){return e["base-path"]+t.path}var oAl=class{root=new UU_;registerEndpoint(t){this.root.insert(this.getPathPartsForEndpoint(t),t)}getConflictingEndpoints(t){return this.root.getMatchingEndpoints(this.getPathPartsForEndpoint(t)).filter(r=>!(r.relativeFilepath===t.relativeFilepath&&r.endpointId===t.endpointId)&&r.endpoint.method===t.endpoint.method)}getPathPartsForEndpoint(t){return y3u({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},UU_=class e{childPaths={};childPathParam;endpointsThatEndWithThisNode=[];insert(t,r){let[n,...i]=t;if(n==null){this.endpointsThatEndWithThisNode.push(r);return}(this.isPathParam(n)?this.childPathParam??=new e:this.childPaths[n]??=new e).insert(i,r)}getMatchingEndpoints(t){let[r,...n]=t;if(r==null)return this.endpointsThatEndWithThisNode;let i=[];if(this.isPathParam(r))i.push(...Object.values(this.childPaths).flatMap(a=>a.getMatchingEndpoints(n)));else{let a=this.childPaths[r];a!=null&&i.push(...a.getMatchingEndpoints(n))}return this.childPathParam!=null&&i.push(...this.childPathParam.getMatchingEndpoints(n)),i}isPathParam(t){return t.startsWith("{")&&t.endsWith("}")}};var VU_={name:"no-conflicting-endpoint-paths",create:({workspace:e})=>{let t=new oAl;return ete(e,(r,n)=>{Qme(n,{httpEndpoint:({service:i,endpointId:a,endpoint:o})=>{t.registerEndpoint({service:i,endpointId:a,endpoint:o,relativeFilepath:r})}})}),{definitionFile:{httpEndpoint:({service:r,endpoint:n,endpointId:i},{relativeFilepath:a})=>{let o=t.getConflictingEndpoints({service:r,endpointId:i,endpoint:n,relativeFilepath:a});return o.length===0?[]:[{severity:"warning",message:[`Endpoint path ${y3u({service:r,endpoint:n})} conflicts with other endpoints:`,...o.map(c=>` - ${c.relativeFilepath} -> ${c.endpointId} ${od.dim(y3u({service:c.service,endpoint:c.endpoint}))}`)].join(`
3045
3045
  `)}]}}}}};var WU_={name:"no-conflicting-request-wrapper-properties",create:({workspace:e})=>({definitionFile:{httpEndpoint:({endpoint:t,service:r},{contents:n,relativeFilepath:i})=>{let a=miL({endpoint:t,service:r,relativeFilepath:i,definitionFile:n,workspace:e}),o=[];for(let[c,d]of Object.entries(a))d.length<=1||o.push({severity:"fatal",message:`Multiple request properties have the name ${od.bold(c)}. This is not suitable for code generation. Use the "name" property to deconflict.
3046
3046
  `+d.map(s=>` - ${OiL(s)}`).join(`
3047
3047
  `)});return o}}})};function miL({endpoint:e,service:t,relativeFilepath:r,definitionFile:n,workspace:i}){let a={},o=(c,d)=>{(a[c]??=[]).push(d)};if(e.request!=null&&typeof e.request!="string"&&e.request.body!=null&&!OU(e.request.body)&&MWs({request:e.request,file:eD({relativeFilepath:r,definitionFile:n,casingsGenerator:e3,rootApiFile:i.definition.rootApiFile.contents}),typeResolver:new MF(i)})&&o(_au,{type:"referenced-body",propertyName:_au}),t.headers!=null)for(let[c,d]of Object.entries(t.headers))o(SHr({headerKey:c,header:d}).name,{type:"service-header",headerKey:c,header:d});if(e.request!=null&&typeof e.request!="string"){if(e.request.headers!=null)for(let[c,d]of Object.entries(e.request.headers))o(SHr({headerKey:c,header:d}).name,{type:"endpoint-header",headerKey:c,header:d});if(e.request["query-parameters"]!=null)for(let[c,d]of Object.entries(e.request["query-parameters"]))o(Xji({queryParameterKey:c,queryParameter:d}).name,{type:"endpoint-query-parameter",queryParameterKey:c,queryParameter:d});if(e.request.body!=null&&OU(e.request.body)){let c=XRr({typeName:void 0,objectDeclaration:{extends:e.request.body.extends,properties:e.request.body.properties??{}},filepathOfDeclaration:r,definitionFile:n,workspace:i,typeResolver:new MF(i),smartCasing:!1});for(let d of c)o(d.name,{type:"inlined-body",property:d})}}return a}function OiL(e){switch(e.type){case"service-header":return`Service header "${e.headerKey}"`;case"endpoint-header":return`Endpoint header "${e.headerKey}"`;case"endpoint-query-parameter":return`Query Parameter "${e.queryParameterKey}"`;case"inlined-body":return`Body property: ${vso({property:e.property,prefixBreadcrumbs:["<Request Body>"]})}`;case"referenced-body":return`Body property "${e.propertyName}"`;default:tc(e)}}var HU_=fa(require("path"),1);var GU_={name:"no-duplicate-declarations",create:({workspace:e,logger:t})=>{let r=AiL(e),n={},i=({declaredName:a,relativeFilepath:o})=>{let c=HU_.default.dirname(o),d=r[c]?.[a];if(d==null)return t.error(`Could not find declarations for name: ${a}. This is an error in the Fern validator.`),[];let s=n[c]??=new Set;if(!s.has(a))return s.add(a),[];let u=d.indexOf(o);return d.filter((m,A)=>A!==u).map(m=>({severity:"fatal",message:`${a} is already declared in ${m===o?"this file":m}`}))};return{definitionFile:{typeName:(a,{relativeFilepath:o})=>i({declaredName:a,relativeFilepath:o}),errorDeclaration:({errorName:a},{relativeFilepath:o})=>i({declaredName:a,relativeFilepath:o}),httpEndpoint:({endpoint:a},{relativeFilepath:o})=>typeof a.request!="string"&&a.request?.name!=null?i({declaredName:a.request.name,relativeFilepath:o}):[]}}}};function AiL(e){let t={};return ete(e,(r,n)=>{let i=HU_.default.dirname(r),a=t[i]??={},o=c=>{(a[c]??=[]).push(r)};Qme(n,{typeName:c=>{o(c)},errorDeclaration:({errorName:c})=>{o(c)},httpEndpoint:({endpoint:c})=>{typeof c.request!="string"&&c.request?.name!=null&&o(c.request.name)}})}),t}function v3u(e){let t=new Set,r=new Set,n=[];for(let i of e)t.has(i)&&!r.has(i)&&(r.add(i),n.push(i)),t.add(i);return n}var JU_={name:"no-duplicate-enum-values",create:()=>({definitionFile:{typeDeclaration:({declaration:e})=>JTr(e)?v3u(e.enum.map(r=>typeof r=="string"?r:r.value)).map(r=>({severity:"fatal",message:`Duplicated enum value: ${od.bold(r)}.`})):[]}})};var KU_={name:"no-duplicate-example-names",create:()=>({definitionFile:{typeDeclaration:({declaration:e})=>{if(typeof e=="string"||e.examples==null)return[];let t=e.examples.map(r=>r.name).filter(nj);return v3u(t).map(r=>({severity:"fatal",message:`Duplicate example name: ${r}`}))},httpEndpoint:({endpoint:e})=>{if(e.examples==null)return[];let t=e.examples.map(r=>r.name).filter(nj);return v3u(t).map(r=>({severity:"fatal",message:`Duplicate example name: ${r}`}))}}})};function UGE(e){if(!e.isInlined)return e.name;switch(e.location){case"inlinedRequest":return"<Inlined Request>";default:tc(e.location)}}var $U_={name:"no-duplicate-field-names",create:({workspace:e})=>{let t=new MF(e);return{definitionFile:{typeDeclaration:({typeName:r,declaration:n},{relativeFilepath:i,contents:a})=>{let o=[];return Tee(n,{alias:Ipt,enum:c=>{let d=VGE(c.enum,s=>Aso(s).name);for(let s of d)o.push({severity:"fatal",message:`Name "${s}" is used by multiple values.`})},object:c=>{let d=UGE(r),s=XRr({typeName:d,objectDeclaration:c,filepathOfDeclaration:i,definitionFile:a,workspace:e,typeResolver:t,smartCasing:!1}),u=QYl(s,l=>l.name);for(let[l,m]of Object.entries(u))if(m.length>1){let A=[`Object has multiple properties named "${l}":`,...m.map(P=>` - ${vso({property:P,prefixBreadcrumbs:[d]})}`)].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fern-api",
3
- "version": "0.94.0",
3
+ "version": "0.94.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/fern-api/fern.git",