fern-api 3.72.0 → 3.72.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.
- package/cli.cjs +4 -4
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1299,7 +1299,7 @@ ${psl.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&fGa(th
|
|
|
1299
1299
|
`+b4t.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?b4t.default.cyan(_sl(t,this.opt.mask)):b4t.default.italic(b4t.default.dim("[hidden]")):this.opt.mask?_sl(t,this.opt.mask):b4t.default.italic(b4t.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 dzn=We(jT(),1);var Aul=We(HGa(),1),pzn=require("child_process"),Zsr=require("fs"),lzn=We(require("path"),1),_ul=We(require("os"),1),vul=require("crypto"),B7a=We(gul(),1);var szn=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var v$r=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var uzn=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var czn=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function fzn(e="",t,r){let n=new D7a(e,r);n.runAsync((i,o)=>{if(i)setImmediate(t,i,void 0);else try{n.cleanup(),setImmediate(t,void 0,o)}catch(a){setImmediate(t,a,void 0)}})}function bul(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function B4b(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 D7a=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=B4b(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??_ul.default.tmpdir(),r=(0,vul.randomUUID)(),n=bul(this.fileOptions.prefix),i=bul(this.fileOptions.postfix),o=`${n}${r}${i}`,a=lzn.default.resolve(t,o),s=lzn.default.resolve(t)+lzn.default.sep;if(!a.startsWith(s))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=a;let c={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(c.mode=this.fileOptions.mode),(0,Zsr.writeFileSync)(this.tempFile,this.text,c)}catch(t){throw new szn(t)}}readTemporaryFile(){try{let t=(0,Zsr.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,Aul.detect)(t)??"utf8";B7a.default.encodingExists(r)||(r="utf8"),this.text=B7a.default.decode(t,r)}}catch(t){throw new uzn(t)}}removeTemporaryFile(){try{(0,Zsr.unlinkSync)(this.tempFile)}catch(t){throw new czn(t)}}launchEditor(){try{let t=(0,pzn.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new v$r(t)}}launchEditorAsync(t){try{(0,pzn.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new v$r(r)}}};var Oul=We(QJ(),1);var O$r=class extends CT{_run(t){this.done=t,this.editorResult=new Oul.Subject;let r=WM(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"?dzn.default.dim("Received"):dzn.default.dim("Press <enter> to launch your preferred editor."),t&&(r=dzn.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),fzn(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 xul=require("stream");var Eul=We(require("readline"),1),Iul=We(Pul(),1),O4t=class{constructor(t){this.rl||=Eul.default.createInterface(T4b(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 T4b(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 Iul.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var w$r=class extends O4t{constructor(t={}){super(t),this.log=new xul.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return a$r(this.rl,this.bottomBar.split(`
|
|
1300
1300
|
`).length),this}updateBottomBar(t){return a$r(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+`
|
|
1301
1301
|
`}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&&FMn(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var TA=We(QJ(),1),Sul=We(xHr(),1);var mzn=We(QJ(),1),jul=We(xHr(),1),hzn=function(e,t,r){return typeof e[t]!="function"?(0,mzn.of)(e):(0,mzn.from)((0,jul.default)(e[t])(r).then(n=>(e[t]=n,e)))};var Cul={set:(e,t="",r)=>{let n=e;t.split(".").forEach((i,o,a)=>{i==="__proto__"||i==="constructor"||(o===a.length-1?n[i]=r:(!(i in n)||typeof n[i]!="object")&&(n[i]={}),n=n[i])})},get:(e,t="",r)=>{let n=o=>String.prototype.split.call(t,o).filter(Boolean).reduce((a,s)=>a!=null?a[s]:a,e),i=n(/[,[\]]+?/)||n(/[,.[\]]+?/);return i===void 0||i===e?r:i}},eur=class extends O4t{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,TA.from)(t):(0,TA.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,TA.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,TA.from)([t]),this.process=n.pipe((0,TA.concatMap)(this.processQuestion.bind(this)),(0,TA.publish)()),this.process.connect(),this.process.pipe((0,TA.reduce)((i,o)=>(Cul.set(i,o.name,o.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,TA.defer)(()=>(0,TA.of)(t).pipe((0,TA.concatMap)(this.setDefaultType.bind(this)),(0,TA.concatMap)(this.filterIfRunnable.bind(this)),(0,TA.concatMap)(()=>hzn(t,"message",this.answers)),(0,TA.concatMap)(()=>hzn(t,"default",this.answers)),(0,TA.concatMap)(()=>hzn(t,"choices",this.answers)),(0,TA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,TA.defer)(()=>(0,TA.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,TA.defer)(()=>(0,TA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Cul.get(this.answers,t.name)!==void 0)return TA.EMPTY;if(t.when===!1)return TA.EMPTY;if(typeof t.when!="function")return(0,TA.of)(t);let{answers:r}=this;return(0,TA.defer)(()=>(0,TA.from)((0,Sul.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,TA.filter)(n=>n!=null)))}};function Bul(e){let t=function(r,n){let i;try{i=new eur(t.prompts,e)}catch(a){return Promise.reject(a)}let o=i.run(r,n);return o.ui=i,o};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",u$r),this.registerPrompt("input",g4t),this.registerPrompt("number",c$r),this.registerPrompt("confirm",l$r),this.registerPrompt("rawlist",p$r),this.registerPrompt("expand",f$r),this.registerPrompt("checkbox",d$r),this.registerPrompt("password",m$r),this.registerPrompt("editor",O$r)},t.restoreDefaultPrompts(),t}var R7a=Bul();function F4b(e,t){R7a.registerPrompt(e,t)}function N4b(){R7a.restoreDefaultPrompts()}var M4b={prompt:R7a,ui:{BottomBar:w$r,Prompt:eur},createPromptModule:Bul,registerPrompt:F4b,restoreDefaultPrompts:N4b,Separator:c5},d0=M4b;var tur=require("path");function Tul(){let e=z4b();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function z4b(e=process.argv[1]?(0,tur.dirname)(process.argv[1]):process.cwd(),t=tur.sep==="\\"){let r=t?Dul(e):e;return n=>{if(!n)return;let i=t?Dul(n):n,{dir:o,base:a,ext:s}=tur.posix.parse(i);(s===".js"||s===".mjs"||s===".cjs")&&(a=a.slice(0,-1*s.length));let c=decodeURIComponent(a);o||(o=".");let l=o.lastIndexOf("/node_modules");if(l>-1)return`${o.slice(l+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let u=o.slice(r.length+1).replace(/\//g,".");return u?`${u}:${c}`:c}return c}}function Dul(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var F7a=e=>{if("flags"in e){let t=Rul(e.flags),r=Ful(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,Nul(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Q4b(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function Q4b(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 Rul=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,P$r(r)]).filter(([,t])=>t!==void 0)),Ful=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?Nul(n):void 0]}))};var P$r=e=>e===void 0?void 0:e.variant??e.enabled,Nul=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var yzn="0123456789abcdef",gzn=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length===16)return new e(t);throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||t<0||r<0||n<0||i<0||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");let o=new Uint8Array(16);return o[0]=t/2**40,o[1]=t/2**32,o[2]=t/2**24,o[3]=t/2**16,o[4]=t/256,o[5]=t,o[6]=112|r>>>8,o[7]=r,o[8]=128|n>>>24,o[9]=n>>>16,o[10]=n>>>8,o[11]=n,o[12]=i>>>24,o[13]=i>>>16,o[14]=i>>>8,o[15]=i,new e(o)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;default:break}if(r){let n=new Uint8Array(16);for(let i=0;i<16;i+=4){let o=parseInt(r.substring(2*i,2*i+8),16);n[i+0]=o>>>24,n[i+1]=o>>>16,n[i+2]=o>>>8,n[i+3]=o}return new e(n)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=yzn.charAt(this.bytes[r]>>>4),t+=yzn.charAt(15&this.bytes[r]),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=yzn.charAt(this.bytes[r]>>>4),t+=yzn.charAt(15&this.bytes[r]);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},N7a=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??q4b()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let n=this.generateOrAbortCore(t,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(t,r)),n}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return gzn.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,gzn.ofInner(t)}},q4b=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),Mul,FNe=()=>V4b().toString(),V4b=()=>(Mul||(Mul=new N7a)).generate();var k4b=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],zul=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return k4b.concat(t).some(n=>{let i=n.toLowerCase();return r.indexOf(i)!==-1})};var p5=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e})({});var L4b=Array.isArray,Qul=Object.prototype,RgC=Qul.hasOwnProperty,M7a=Qul.toString,z7a=L4b||function(e){return M7a.call(e)==="[object Array]"};var qul=e=>e===Object(e)&&!z7a(e);var rur=e=>e===void 0,E$r=e=>M7a.call(e)=="[object String]",Vul=e=>E$r(e)&&e.trim().length===0;var kul=e=>M7a.call(e)=="[object Number]"&&e===e;var Q7a=e=>e instanceof Error;function I$r(e){return e===null||typeof e!="object"}function w4t(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function Uul(e){return w4t(e,"ErrorEvent")}function bzn(e){return!rur(Event)&&W4b(e,Event)}function Lul(e){return w4t(e,"Object")}function W4b(e,t){try{return e instanceof t}catch{return!1}}function x$r(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),kul(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),x$r(i||r,t,r,n))}var G4b=864e5,Azn=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=x$r(t.bucketSize,0,100,t._logger),this._refillRate=x$r(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=x$r(t.refillInterval,0,G4b,t._logger)}_applyRefill(t,r){let n=r-t.lastAccess,i=Math.floor(n/this._refillInterval);if(i>0){let o=i*this._refillRate;t.tokens=Math.min(t.tokens+o,this._bucketSize),t.lastAccess=t.lastAccess+i*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),n=String(t),i=this._buckets[n];return i?this._applyRefill(i,r):(i={tokens:this._bucketSize,lastAccess:r},this._buckets[n]=i),i.tokens===0?!0:(i.tokens--,i.tokens===0&&this._onBucketRateLimited?.(t),i.tokens===0)}stop(){this._buckets={}}};var _zn=class{add(t){let r=FNe();return this.promiseByIds[r]=t,t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds),r=t.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function H4b(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var Wul=(e,t,r)=>{function n(o,...a){t(()=>{let s=r[o];s(e,...a)})}return{info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>Wul(`${e} ${o}`,t,r)}},$4b=e=>e();function Gul(e,t=$4b){return Wul(e,t,H4b())}var iur="Mobile",Ozn="iOS",nur="Android",Hul="Tablet",GgC=nur+" "+Hul;var J4b="Apple",HgC=J4b+" Watch",$ul="Safari",wzn="BlackBerry",Jul="Samsung",K4b=Jul+"Browser",Y4b=Jul+" Internet",Pzn="Chrome",X4b=Pzn+" OS",Z4b=Pzn+" "+Ozn,Kul="Internet Explorer",e2b=Kul+" "+iur,V7a="Opera",$gC=V7a+" Mini",Yul="Edge",t2b="Microsoft "+Yul,k7a="Firefox",r2b=k7a+" "+Ozn,U7a="Nintendo",L7a="PlayStation",vzn="Xbox",n2b=nur+" "+iur,i2b=iur+" "+$ul,j$r="Windows",o2b=j$r+" Phone";var Xul="Generic",JgC=Xul+" "+iur.toLowerCase(),KgC=Xul+" "+Hul.toLowerCase(),a2b="Konqueror",vU="(\\d+(\\.\\d+)?)",q7a=new RegExp("Version/"+vU),YgC=new RegExp(vzn,"i"),XgC=new RegExp(L7a+" \\w+","i"),ZgC=new RegExp(U7a+" \\w+","i"),s2b=new RegExp(wzn+"|PlayBook|BB10","i"),u2b={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var ebC={[e2b]:[new RegExp("rv:"+vU)],[t2b]:[new RegExp(Yul+"?\\/"+vU)],[Pzn]:[new RegExp("("+Pzn+"|CrMo)\\/"+vU)],[Z4b]:[new RegExp("CriOS\\/"+vU)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+vU)],[$ul]:[q7a],[i2b]:[q7a],[V7a]:[new RegExp("("+V7a+"|OPR)\\/"+vU)],[k7a]:[new RegExp(k7a+"\\/"+vU)],[r2b]:[new RegExp("FxiOS\\/"+vU)],[a2b]:[new RegExp("Konqueror[:/]?"+vU,"i")],[wzn]:[new RegExp(wzn+" "+vU),q7a],[n2b]:[new RegExp("android\\s"+vU,"i")],[Y4b]:[new RegExp(K4b+"\\/"+vU)],[Kul]:[new RegExp("(rv:|MSIE )"+vU)],Mozilla:[new RegExp("rv:"+vU)]};var tbC=[[new RegExp(vzn+"; "+vzn+" (.*?)[);]","i"),e=>[vzn,e&&e[1]||""]],[new RegExp(U7a,"i"),[U7a,""]],[new RegExp(L7a,"i"),[L7a,""]],[s2b,[wzn,""]],[new RegExp(j$r,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[o2b,""];if(new RegExp(iur).test(t)&&!/IEMobile\b/.test(t))return[j$r+" "+iur,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=u2b[n]||"";return/arm/i.test(t)&&(i="RT"),[j$r,i]}return[j$r,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Ozn,t.join(".")]}return[Ozn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=rur(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+nur+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+nur+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[nur,t.join(".")]}return[nur,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[X4b,""]],[/Linux|debian/i,["Linux",""]]];var Zul="utf8";function ecl(e,t){if(!e||typeof e!="string"||c2b(e))throw new Error(t)}function c2b(e){return e.trim().length===0}function tcl(e){return e?.replace(/\/+$/,"")}async function rcl(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 Ezn(){return new Date().toISOString()}function P4t(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var ncl=e=>e instanceof Error;function W7a(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var Izn=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}};function icl(){return"CompressionStream"in globalThis}async function G7a(e,t=!0){try{let n=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(n).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var E4t=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()}},our=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function ocl(e){if(e instanceof E4t){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 H7a(e){return typeof e=="object"&&(e instanceof E4t||e instanceof our)}function acl(e){return typeof e=="object"&&e instanceof E4t&&e.status===413}var C$r=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new _zn,this._events=new Izn,this._isInitialized=!1,ecl(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=tcl(r.host||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:H7a},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,this._logger=Gul("[PostHog]",this.logMsgIfDebug.bind(this)),this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!icl()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(p5.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(p5.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(p5.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,a){this.wrap(()=>{let s=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...a||{}}});this.enqueue("capture",s,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._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},a=!0){await this._initPromise;let s=a?"&config=true":"",c=`${this.host}/flags/?v=2${s}`,l={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,u,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).then(p=>({success:!0,response:F7a(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(t){if(t instanceof E4t)return{type:"api_error",statusCode:t.status};if(t instanceof our){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,n={},i={},o={},a){await this._initPromise;let s=await this.getFeatureFlagDetailStateless(t,r,n,i,o,a);if(s===void 0)return{response:void 0,requestId:void 0};let c=P$r(s.response);return c===void 0&&(c=!1),{response:c,requestId:s.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},a){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(r,n,i,o,a,[t]);return s===void 0?void 0:{response:s.flags[t],requestId:s.requestId,evaluatedAt:s.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},a){await this._initPromise;let s=await this.getFeatureFlagPayloadsStateless(r,n,i,o,a,[t]);if(!s)return;let c=s[t];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,a)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,a)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,a){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,a);return s?{flags:s.featureFlags,payloads:s.featureFlagPayloads,requestId:s.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,a){await this._initPromise;let s={};(o??this.disableGeoip)&&(s.geoip_disable=!0),a&&(s.flag_keys_to_evaluate=a);let c=await this.getFlags(t,r,n,i,s);if(!c.success)return;let l=c.response;return l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r).then(o=>{if(o.status!==200||!o.json){let a=`Surveys API could not be loaded: ${o.status}`,s=new Error(a);this._logger.error(s),this._events.emit("error",new Error(a));return}return o.json()}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(p5.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(p5.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(p5.Props,this.props)})}processBeforeEnqueue(t){return t}enqueue(t,r,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o=this.getPersistedProperty(p5.Queue)||[];o.length>=this.maxQueueSize&&(o.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),o.push({message:i}),this.setPersistedProperty(p5.Queue,o),this._events.emit(t,i),o.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=P4t(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o={api_key:this.apiKey,batch:[i],sent_at:Ezn()};this.historicalMigration&&(o.historical_migration=!0);let a=JSON.stringify(o),s=`${this.host}/batch/`,c=this.disableCompression?null:await G7a(a,this.isDebug),l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||a};try{await this.fetchWithRetry(s,l)}catch(u){this._events.emit("error",u)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:Ezn(),uuid:n?.uuid?n.uuid:FNe()};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 ocl(t)})}async flush(){let t=W7a([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),W7a([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(p5.Queue)||[];if(!t.length)return;let r=[],n=t.length;for(;t.length>0&&r.length<n;){let i=t.slice(0,this.maxBatchSize),o=i.map(m=>m.message),a=()=>{let h=(this.getPersistedProperty(p5.Queue)||[]).slice(i.length);this.setPersistedProperty(p5.Queue,h),t=h},s={api_key:this.apiKey,batch:o,sent_at:Ezn()};this.historicalMigration&&(s.historical_migration=!0);let c=JSON.stringify(s),l=`${this.host}/batch/`,u=this.disableCompression?null:await G7a(c,this.isDebug),p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||c},d={retryCheck:m=>acl(m)?!1:H7a(m)};try{await this.fetchWithRetry(l,p,d)}catch(m){if(acl(m)&&o.length>1){this.maxBatchSize=Math.max(1,Math.floor(o.length/2)),this._logger.warn(`Received 413 when sending batch of size ${o.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw m instanceof our||a(),this._events.emit("error",m),m}a(),r.push(...o)}this._events.emit("flush",r)}async fetchWithRetry(t,r,n,i){AbortSignal.timeout??=function(s){let c=new AbortController;return setTimeout(()=>c.abort(),s),c.signal};let o=r.body?r.body:"",a=-1;try{a=o instanceof Blob?o.size:Buffer.byteLength(o,Zul)}catch{o instanceof Blob?a=o.size:a=new TextEncoder().encode(o).length}return await rcl(async()=>{let s=null;try{s=await this.fetch(t,{signal:AbortSignal.timeout(i??this.requestTimeout),...r})}catch(l){throw new our(l)}if(!(r.mode==="no-cors")&&(s.status<200||s.status>=400))throw new E4t(s,a);return s},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let n=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(p5.Queue)||[]).length===0||(await this.flush(),r)););}catch(i){if(!H7a(i))throw i;await ocl(i)}};return Promise.race([new Promise((i,o)=>{P4t(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,o("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),n()])}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var f5={};Q(f5,{DOMExceptionCoercer:()=>Y7a,ErrorCoercer:()=>X7a,ErrorEventCoercer:()=>Z7a,ErrorPropertiesBuilder:()=>$7a,EventCoercer:()=>rHa,ObjectCoercer:()=>tHa,PrimitiveCoercer:()=>nHa,PromiseRejectionEventCoercer:()=>iHa,ReduceableCache:()=>oHa,StringCoercer:()=>eHa,chromeStackLineParser:()=>J7a,createDefaultStackParser:()=>P2b,createStackParser:()=>gcl,geckoStackLineParser:()=>K7a,nodeStackLineParser:()=>dcl,opera10StackLineParser:()=>lcl,opera11StackLineParser:()=>pcl,reverseAndStripFrames:()=>ycl,winjsStackLineParser:()=>ccl});var xzn,scl,jzn;function ucl(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return jzn&&r.length===scl||(scl=r.length,jzn=r.reduce((n,i)=>{xzn||(xzn={});let o=xzn[i];if(o)n[o[0]]=o[1];else{let a=e(i);for(let s=a.length-1;s>=0;s--){let l=a[s]?.filename,u=t[i];if(l&&u){n[l]=u,xzn[i]=[l,u];break}}}return n},{})),jzn}var p2b=4,$7a=class{constructor(t,r,n=[]){this.coercers=t,this.stackParser=r,this.modifiers=n}buildFromUnknown(t,r={}){let i=r&&r.mechanism||{handled:!0,type:"generic"},a=this.buildCoercingContext(i,r,0).apply(t),s=this.buildParsingContext(),c=this.parseStacktrace(a,s);return{$exception_list:this.convertToExceptionList(c,i),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&z7a(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let n;t.cause!=null&&(n=this.parseStacktrace(t.cause,r));let i;return t.stack!=""&&t.stack!=null&&(i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?1:0),r.chunkIdMap)),{...t,cause:n,stack:i}}applyChunkIds(t,r){return t.map(n=>(n.filename&&r&&(n.chunk_id=r[n.filename]),n))}applyCoercers(t,r){for(let n of this.coercers)if(n.match(t))return n.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let n of this.modifiers)r=await n(r);return r}convertToExceptionList(t,r){let n={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(n.stacktrace={type:"raw",frames:t.stack});let i=[n];return t.cause!=null&&i.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),i}buildParsingContext(){return{chunkIdMap:ucl(this.stackParser)}}buildCoercingContext(t,r,n=0){let i=(a,s)=>{if(s<=p2b){let c=this.buildCoercingContext(t,r,s);return this.applyCoercers(a,c)}};return{...r,syntheticException:n==0?r.syntheticException:void 0,mechanism:t,apply:a=>i(a,n),next:a=>i(a,n+1)}}};var HM="?";function NNe(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?HM:r,in_app:!0};return rur(n)||(o.lineno=n),rur(i)||(o.colno=i),o}var Czn=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:HM,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var f2b=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,d2b=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,m2b=/\((\S*)(?::(\d+))(?::(\d+))\)/,J7a=(e,t)=>{let r=f2b.exec(e);if(r){let[,i,o,a]=r;return NNe(t,i,HM,+o,+a)}let n=d2b.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let s=m2b.exec(n[2]);s&&(n[2]=s[1],n[3]=s[2],n[4]=s[3])}let[o,a]=Czn(n[1]||HM,n[2]);return NNe(t,a,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var h2b=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,y2b=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,K7a=(e,t)=>{let r=h2b.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let a=y2b.exec(r[3]);a&&(r[1]=r[1]||"eval",r[3]=a[1],r[4]=a[2],r[5]="")}let i=r[3],o=r[1]||HM;return[o,i]=Czn(o,i),NNe(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var g2b=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ccl=(e,t)=>{let r=g2b.exec(e);return r?NNe(t,r[2],r[1]||HM,+r[3],r[4]?+r[4]:void 0):void 0};var b2b=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,lcl=(e,t)=>{let r=b2b.exec(e);return r?NNe(t,r[2],r[3]||HM,+r[1]):void 0},A2b=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,pcl=(e,t)=>{let r=A2b.exec(e);return r?NNe(t,r[5],r[3]||r[4]||HM,+r[1],+r[2]):void 0};var _2b=/^\s*[-]{4,}$/,v2b=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,dcl=(e,t)=>{let r=e.match(v2b);if(r){let n,i,o,a,s;if(r[1]){o=r[1];let u=o.lastIndexOf(".");if(o[u-1]==="."&&u--,u>0){n=o.slice(0,u),i=o.slice(u+1);let p=n.indexOf(".Module");p>0&&(o=o.slice(p+1),n=n.slice(0,p))}a=void 0}i&&(a=n,s=i),i==="<anonymous>"&&(s=void 0,o=void 0),o===void 0&&(s=s||HM,o=a?`${a}.${s}`:s);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!l&&(c=r[5]),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:fcl(r[3]),colno:fcl(r[4]),in_app:O2b(c||"",l),platform:t}}if(e.match(_2b))return{filename:e,platform:t}};function O2b(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 fcl(e){return parseInt(e||"",10)||void 0}var mcl=/\(error: (.*)\)/,hcl=50;function ycl(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,hcl).map(r=>({...r,filename:r.filename||w2b(t).filename,function:r.function||HM}))}function w2b(e){return e[e.length-1]||{}}function P2b(){return gcl("web:javascript",J7a,K7a)}function gcl(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
|
|
1302
|
-
`);for(let a=n;a<o.length;a++){let s=o[a];if(s.length>1024)continue;let c=mcl.test(s)?s.replace(mcl,"$1"):s;if(!c.match(/\S*Error: /)){for(let l of t){let u=l(c,e);if(u){i.push(u);break}}if(i.length>=hcl)break}}return ycl(i)}}var Y7a=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=E$r(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return w4t(t,"DOMException")}isDOMError(t){return w4t(t,"DOMError")}};var X7a=class{match(t){return Q7a(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){return t.stacktrace||t.stack||void 0}};var Z7a=class{constructor(){}match(t){return Uul(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var E2b=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,eHa=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(E2b);return i&&(r=i[1],n=i[2]),[r,n]}};var bcl=["fatal","error","warning","log","info","debug"];function Szn(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var tHa=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return bzn(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=Szn(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return E$r(t)&&!Vul(t)&&bcl.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(ncl(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var rHa=class{match(t){return bzn(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Szn(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var nHa=class{match(t){return I$r(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var iHa=class{match(t){return w4t(t,"PromiseRejectionEvent")}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return I$r(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){if(I$r(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var oHa=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var vcl=require("fs"),Ocl=require("readline"),Bzn=new f5.ReduceableCache(25),wcl=new f5.ReduceableCache(20),aHa=7,I2b=1e3,x2b=1e4;async function Pcl(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],a=o?.filename;if(!o||typeof a!="string"||typeof o.lineno!="number"||B2b(a)||D2b(o))continue;t[a]||(t[a]=[]),t[a].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(wcl.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,l)=>c-l);let a=R2b(o);if(a.every(c=>T2b(i,c)))continue;let s=F2b(Bzn,i,{});n.push(j2b(i,a,s))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&C2b(e,Bzn),Bzn.reduce(),e}function j2b(e,t,r){return new Promise(n=>{let i=(0,vcl.createReadStream)(e),o=(0,Ocl.createInterface)({input:i});function a(){i.destroy(),n()}let s=0,c=0,l=t[c];if(l===void 0)return void a();let u=l[0],p=l[1];function d(){wcl.set(e,1),o.close(),o.removeAllListeners(),a()}i.on("error",d),o.on("error",d),o.on("close",a),o.on("line",m=>{if(s++,!(s<u)&&(r[s]=N2b(m,0),s>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let h=t[c];if(h===void 0){o.close(),o.removeAllListeners();return}u=h[0],p=h[1]}})})}function C2b(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;S2b(r.lineno,r,n)}}function S2b(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Ecl(e);i<e;i++){let o=r[i];if(o===void 0)return void Acl(t);t.pre_context.push(o)}if(r[e]===void 0)return void Acl(t);t.context_line=r[e];let n=Icl(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function Acl(e){delete e.pre_context,delete e.context_line,delete e.post_context}function B2b(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function D2b(e){return e.lineno!==void 0&&e.lineno>x2b||e.colno!==void 0&&e.colno>I2b}function T2b(e,t){let r=Bzn.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 R2b(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=_cl(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+aHa:(i.push(n),n=_cl(o)),t++}return i}function _cl(e){return[Ecl(e),Icl(e)]}function Ecl(e){return Math.max(1,e-aHa)}function Icl(e){return e+aHa}function F2b(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function N2b(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}function M2b(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(a=>a.name!=="domainUncaughtExceptionClear"&&a._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function xcl(e,t){globalThis.process?.on("uncaughtException",M2b(e,t))}function jcl(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var z2b=2e3,dxe=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Azn({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return qul(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i};n||(o.$process_person_profile=!1);let a=this.errorPropertiesBuilder.buildFromUnknown(t,r);return a.$exception_list=await this.errorPropertiesBuilder.modifyFrames(a.$exception_list),{event:"$exception",distinctId:n||FNe(),properties:{...a,...o}}}startAutocaptureIfEnabled(){this.isEnabled()&&(xcl(this.onException.bind(this),this.onFatalError.bind(this)),jcl(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(z2b),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var Ccl="5.24.7";var S$r={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function Scl(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var Q2b=6e4,q2b=1152921504606847e3,V2b=["is_not"],aur=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},kw=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},MNe=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Dzn=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:a,...s}){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=o,this.poller=void 0,this.fetch=s.fetch||fetch,this.onError=s.onError,this.customHeaders=a,this.onLoad=s.onLoad,this.cacheProvider=s.cacheProvider,this.strictLocalEvaluation=s.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let a,s;if(!this.loadedSuccessfullyOnce)return a;if(s=this.featureFlagsByKey[t],s!==void 0)try{a=(await this.computeFlagAndPayloadLocally(s,r,n,i,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${a}`))}catch(c){c instanceof MNe||c instanceof kw?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${t}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${c}`))}return a}async getAllFlagsAndPayloads(t,r={},n={},i={},o){await this.loadFeatureFlags();let a={},s={},c=this.featureFlags.length==0,l=o?o.map(p=>this.featureFlagsByKey[p]).filter(Boolean):this.featureFlags,u={};return await Promise.all(l.map(async p=>{try{let{value:d,payload:m}=await this.computeFlagAndPayloadLocally(p,t,r,n,i,void 0,u);a[p.key]=d,m&&(s[p.key]=m)}catch(d){d instanceof MNe||d instanceof kw?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${p.key}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${p.key}: ${d}`)),c=!0}})),{response:a,payloads:s,fallbackToFlags:c}}async computeFlagAndPayloadLocally(t,r,n={},i={},o={},a,s,c=!1){if(c||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let l;l=a!==void 0?a:await this.computeFlagValueLocally(t,r,n,i,o,s);let u=this.getFeatureFlagPayload(t.key,l);return{value:l,payload:u}}async computeFlagValueLocally(t,r,n={},i={},o={},a={}){if(t.ensure_experience_continuity)throw new kw("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c==null)return await this.matchFeatureFlagProperties(t,r,i,a);{let l=this.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new kw("Flag has unknown group type index");if(!(l in n))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=o[l];return await this.matchFeatureFlagProperties(t,n[l],u,a)}}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n,i){let o=t.key;if(!this.featureFlagsByKey)throw new kw("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new kw(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let a=t.dependency_chain;if(!Array.isArray(a))throw new kw(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(a.length===0)throw new kw(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of a){if(!(c in i)){let u=this.featureFlagsByKey[c];if(u)if(u.active)try{let p=await this.matchFeatureFlagProperties(u,r,n,i);i[c]=p}catch(p){throw new kw(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new kw(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new kw(`Dependency '${c}' could not be evaluated`)}let s=i[o];return this.flagEvaluatesToExpectedValue(t.value,s)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i={}){let o=t.filters||{},a=o.groups||[],s=!1,c;for(let l of a)try{if(await this.isConditionMatch(t,r,l,n,i)){let u=l.variant,p=o.multivariate?.variants||[];c=u&&p.some(d=>d.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof MNe)throw u;if(u instanceof kw)s=!0;else throw u}if(c!==void 0)return c;if(s)throw new kw("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o={}){let a=n.rollout_percentage,s=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let l=c.type,u=!1;if(u=l==="cohort"?Fcl(c,i,this.cohorts,this.debugMode):l==="flag"?await this.evaluateFlagDependency(c,r,i,o):Rcl(c,i,s),!u)return!1}if(a==null)return!0}return!(a!=null&&await Bcl(t.key,r)>a/100)}async getMatchingVariant(t,r){let n=await Bcl(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(s=>{i=n+s.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:s.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Q2b,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new aur(`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.beginBackoff(),new aur(`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.beginBackoff(),new aur(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof aur&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=P4t(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function Bcl(e,t,r=""){let n=await Scl(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/q2b}function Rcl(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")throw new kw("Operator is_not_set is not supported")}else throw new kw(`Property ${n} not found in propertyValues`);let a=t[n];if(a==null&&!V2b.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function s(l,u){return Array.isArray(l)?l.map(p=>String(p).toLowerCase()).includes(String(u).toLowerCase()):String(l).toLowerCase()===String(u).toLowerCase()}function c(l,u,p){if(p==="gt")return l>u;if(p==="gte")return l>=u;if(p==="lt")return l<u;if(p==="lte")return l<=u;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return s(i,a);case"is_not":return!s(i,a);case"is_set":return n in t;case"icontains":return String(a).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(a).toLowerCase().includes(String(i).toLowerCase());case"regex":return Dcl(String(i))&&String(a).match(String(i))!==null;case"not_regex":return Dcl(String(i))&&String(a).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let l=typeof i=="number"?i:null;if(typeof i=="string")try{l=parseFloat(i)}catch{}return l==null||a==null?c(String(a),String(i),o):typeof a=="string"?c(a,String(i),o):c(a,l,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new kw("Date operations cannot be performed on boolean values");let l=U2b(String(i));if(l==null&&(l=Tcl(i)),l==null)throw new kw(`Invalid date: ${i}`);let u=Tcl(a);return["is_date_before"].includes(o)?u<l:u>l}default:throw new kw(`Unknown operator: ${o}`)}}function k2b(e,t){if(!(e in t))throw new MNe(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Fcl(e,t,r,n=!1){let i=String(e.value);k2b(i,r);let o=r[i];return Ncl(o,t,r,n)}function Ncl(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let a=!1;if("values"in o[0]){for(let s of o)try{let c=Ncl(s,t,r,n);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof MNe)throw c;if(c instanceof kw)n&&console.debug(`Failed to compute property ${s} locally: ${c}`),a=!0;else throw c}if(a)throw new kw("Can't match cohort without a given cohort property value");return i==="AND"}for(let s of o)try{let c;if(s.type==="cohort")c=Fcl(s,t,r,n);else if(s.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${s.key||"unknown"}'`);continue}else c=Rcl(s,t);let l=s.negation||!1;if(i==="AND"){if(!c&&!l||c&&l)return!1}else if(c&&!l||!c&&l)return!0}catch(c){if(c instanceof MNe)throw c;if(c instanceof kw)n&&console.debug(`Failed to compute property ${s} locally: ${c}`),a=!0;else throw c}if(a)throw new kw("can't match cohort without a given cohort property value");return i==="AND"}function Dcl(e){try{return new RegExp(e),!0}catch{return!1}}function Tcl(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 kw(`${e} is in an invalid date format`)}throw new kw(`The date provided ${e} must be a string, number, or date object`)}function U2b(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}var Tzn=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var L2b=100,Mcl=3e4,W2b=5e4,Rzn=class extends C$r{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Tzn,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,L2b):Mcl,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new Dzn({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new dxe(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||W2b}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return Ccl}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:a,...s}=r,u={$set:i||s,$set_once:o||{},$anon_distinct_id:a??void 0};super.identifyStateless(t,u,{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:a,...s}=r,u={$set:i||s,$set_once:o||{},$anon_distinct_id:a??void 0};super.identifyStatelessImmediate(t,u,{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=Mcl){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}async _getFeatureFlagResult(t,r,n={},i){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let v=this._flagOverrides[t];if(v===void 0)return;let P=this._payloadOverrides?.[t];return{key:t,enabled:v!==!1,variant:typeof v=="string"?v:void 0,payload:P}}let{groups:a,disableGeoip:s}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,p=this.addLocalPersonAndGroupProperties(r,a,l,u);l=p.allPersonProperties,u=p.allGroupProperties,c==null&&(c=this.options.strictLocalEvaluation??!1);let d,m=!1,h,y,g,b,_,O;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let v=this.featureFlagsPoller?.featureFlagsByKey[t];if(v)try{let P=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(v,r,a,l,u,i);if(P){m=!0;let I=P.value;b=v.id,O="Evaluated locally",d={key:t,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:P.payload??void 0}}}catch(P){if(P instanceof MNe||P instanceof kw)this._logger?.info(`${P.name} when computing flag locally: ${t}: ${P.message}`);else throw P}}if(!m&&!c){let v=await super.getFeatureFlagDetailsStateless(r,a,l,u,s,[t]);if(v===void 0)g=S$r.UNKNOWN_ERROR;else{h=v.requestId,y=v.evaluatedAt;let P=[];v.errorsWhileComputingFlags&&P.push(S$r.ERRORS_WHILE_COMPUTING),v.quotaLimited?.includes("feature_flags")&&P.push(S$r.QUOTA_LIMITED);let I=v.flags[t];if(I===void 0)P.push(S$r.FLAG_MISSING);else{b=I.metadata?.id,_=I.metadata?.version,O=I.reason?.description??I.reason?.code;let E;if(I.metadata?.payload!==void 0)try{E=JSON.parse(I.metadata.payload)}catch{E=I.metadata.payload}d={key:t,enabled:I.enabled,variant:I.variant,payload:E}}P.length>0&&(g=P.join(","))}}if(o){let v=d===void 0?void 0:d.enabled===!1?!1:d.variant??!0,P=`${t}_${v}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(P)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(P):this.distinctIdHasSentFlagCalls[r]=[P];let I={$feature_flag:t,$feature_flag_response:v,$feature_flag_id:b,$feature_flag_version:_,$feature_flag_reason:O,locally_evaluated:m,[`$feature/${t}`]:v,$feature_flag_request_id:h,$feature_flag_evaluated_at:y};g&&(I.$feature_flag_error=g),this.capture({distinctId:r,event:"$feature_flag_called",properties:I,groups:a,disableGeoip:s})}}return d!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(d={...d,payload:this._payloadOverrides[t]}),d}async getFeatureFlag(t,r,n){let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){return this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}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,flagKeys:o}=r||{},{onlyEvaluateLocally:a,personProperties:s,groupProperties:c}=r||{},l=this.addLocalPersonAndGroupProperties(t,n,s,c);s=l.allPersonProperties,c=l.allGroupProperties,a==null&&(a=this.options.strictLocalEvaluation??!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,n,s,c,o),p={},d={},m=!0;if(u&&(p=u.response,d=u.payloads,m=u.fallbackToFlags),m&&!a){let h=await super.getFeatureFlagsAndPayloadsStateless(t,n,s,c,i,o);p={...p,...h.flags||{}},d={...d,...h.payloads||{}}}return this._flagOverrides!==void 0&&(p={...p,...this._flagOverrides}),this._payloadOverrides!==void 0&&(d={...d,...this._payloadOverrides}),{featureFlags:p,featureFlagPayloads:d}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=P4t(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,a]of Object.entries(t))if(Lul(a)&&r&&o in r){let s={};for(let[c,l]of Object.entries(a))s[String(c)]=String(l);i[String(o)]=s}else n[String(o)]=String(a);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},a=i?.groupProperties||{},s=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:a,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:s})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:a,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:s})}return(await super.getFeatureFlagsStateless(t,r,o,a,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},a={};if(r)for(let s of Object.keys(r))a[s]={$group_key:r[s],...i?.[s]||{}};return{allPersonProperties:o,allGroupProperties:a}}captureException(t,r,n,i){if(!dxe.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(dxe.buildEventMessage(t,{syntheticException:o},r,n).then(a=>this.capture({...a,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!dxe.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");this.addPendingPromise(dxe.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:a,timestamp:s,disableGeoip:c,uuid:l}=t,u=this.context?.get(),p=r||u?.distinctId,d={...u?.properties||{},...i||{}};p||(p=FNe(),d.$process_person_profile=!1),u?.sessionId&&!d.$session_id&&(d.$session_id=u.sessionId);let m=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:a,timestamp:s,disableGeoip:c,uuid:l});if(!m)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(a){let y=typeof a=="object"?a:void 0;return await this.getFeatureFlagsForEvent(m.distinctId,o,c,y)}return m.event,{}}).then(y=>{let g={};if(y)for(let[_,O]of Object.entries(y))g[`$feature/${_}`]=O;let b=Object.keys(y||{}).filter(_=>y?.[_]!==!1).sort();return b.length>0&&(g.$active_feature_flags=b),g}).catch(()=>({})).then(y=>({...y,...m.properties||{},$groups:m.groups||o}));return m.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&zul(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",h.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:h,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let a=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(a)}}return i}};var zcl=require("async_hooks"),Fzn=class{constructor(){this.storage=new zcl.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){if(n?.fresh===!0)return this.storage.run(t,r);{let o=this.get()||{},a={distinctId:t.distinctId??o.distinctId,sessionId:t.sessionId??o.sessionId,properties:{...o.properties||{},...t.properties||{}}};return this.storage.run(a,r)}}};var Qcl="posthog-node";function G2b(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return a=>{if(!(i==="*"||i.includes(a.level)))return a;a.tags||(a.tags={});let c=a.tags[sHa.POSTHOG_ID_TAG];if(c===void 0)return a;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,l).toString();a.tags["PostHog Person URL"]=u;let p=a.exception?.values||[],d=p.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),m={$exception_message:p[0]?.value||a.message,$exception_type:p[0]?.type,$exception_level:a.level,$exception_list:d,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:p[0]?.value||a.message,$sentry_exception_type:p[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),o&&e.capture({event:"$exception",distinctId:c,properties:m}),a}}var sHa=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=Qcl,this.name=Qcl,this.setupOnce=function(a,s){let c=s()?.getClient()?.getDsn()?.projectId;a(G2b(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};dxe.errorPropertiesBuilder=new f5.ErrorPropertiesBuilder([new f5.EventCoercer,new f5.ErrorCoercer,new f5.ObjectCoercer,new f5.StringCoercer,new f5.PrimitiveCoercer],f5.createStackParser("node:javascript",f5.nodeStackLineParser),[Tul(),Pcl]);var sur=class extends Rzn{getLibraryId(){return"posthog-node"}initializeContext(){return new Fzn}};var Nzn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new sur(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.72.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var B$r=class{async sendEvent(){}async identify(){}async flush(){}};var uur=require("fs/promises"),Ucl=require("os"),Lcl=require("path");var qcl=We(require("crypto")),zzn=new Uint8Array(256),Mzn=zzn.length;function uHa(){return Mzn>zzn.length-16&&(qcl.default.randomFillSync(zzn),Mzn=0),zzn.slice(Mzn,Mzn+=16)}var $M=[];for(let e=0;e<256;++e)$M.push((e+256).toString(16).slice(1));function Vcl(e,t=0){return $M[e[t+0]]+$M[e[t+1]]+$M[e[t+2]]+$M[e[t+3]]+"-"+$M[e[t+4]]+$M[e[t+5]]+"-"+$M[e[t+6]]+$M[e[t+7]]+"-"+$M[e[t+8]]+$M[e[t+9]]+"-"+$M[e[t+10]]+$M[e[t+11]]+$M[e[t+12]]+$M[e[t+13]]+$M[e[t+14]]+$M[e[t+15]]}var kcl=We(require("crypto")),cHa={randomUUID:kcl.default.randomUUID};function H2b(e,t,r){if(cHa.randomUUID&&!t&&!e)return cHa.randomUUID();e=e||{};let n=e.random||(e.rng||uHa)();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 Vcl(n)}var VJ=H2b;var $2b="id",J2b=".fern",D$r=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new sur(r),this.userId=t==null?void 0:G3a(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.72.0",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await jx({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=vt(xr.of((0,Ucl.homedir)()),Xe.of(J2b),Xe.of($2b));await un(t)||(await(0,uur.mkdir)((0,Lcl.dirname)(t),{recursive:!0}),await(0,uur.writeFile)(t,VJ())),this.persistedDistinctId=(await(0,uur.readFile)(t)).toString()}return this.persistedDistinctId}};var lHa;async function cur(){return lHa==null&&(lHa=await K2b()),lHa}async function K2b(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new B$r;let r=await tTn();return r!=null?new D$r({token:r,posthogApiKey:e}):await yNe()!=null?new Nzn({posthogApiKey:e}):new D$r({token:void 0,posthogApiKey:e})}catch{return new B$r}}function T$r(e,t){return function(){return e.apply(t,arguments)}}var{toString:Y2b}=Object.prototype,{getPrototypeOf:fHa}=Object,{iterator:qzn,toStringTag:Gcl}=Symbol,Vzn=(e=>t=>{let r=Y2b.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),mxe=e=>(e=e.toLowerCase(),t=>Vzn(t)===e),kzn=e=>t=>typeof t===e,{isArray:pur}=Array,lur=kzn("undefined");function R$r(e){return e!==null&&!lur(e)&&e.constructor!==null&&!lur(e.constructor)&&d5(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Hcl=mxe("ArrayBuffer");function X2b(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Hcl(e.buffer),t}var Z2b=kzn("string"),d5=kzn("function"),$cl=kzn("number"),F$r=e=>e!==null&&typeof e=="object",eLb=e=>e===!0||e===!1,Qzn=e=>{if(Vzn(e)!=="object")return!1;let t=fHa(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Gcl in e)&&!(qzn in e)},tLb=e=>{if(!F$r(e)||R$r(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},rLb=mxe("Date"),nLb=mxe("File"),iLb=mxe("Blob"),oLb=mxe("FileList"),aLb=e=>F$r(e)&&d5(e.pipe),sLb=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||d5(e.append)&&((t=Vzn(e))==="formdata"||t==="object"&&d5(e.toString)&&e.toString()==="[object FormData]"))},uLb=mxe("URLSearchParams"),[cLb,lLb,pLb,fLb]=["ReadableStream","Request","Response","Headers"].map(mxe),dLb=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function N$r(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),pur(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(R$r(e))return;let o=r?Object.getOwnPropertyNames(e):Object.keys(e),a=o.length,s;for(n=0;n<a;n++)s=o[n],t.call(null,e[s],s,e)}}function Jcl(e,t){if(R$r(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 I4t=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Kcl=e=>!lur(e)&&e!==I4t;function pHa(){let{caseless:e,skipUndefined:t}=Kcl(this)&&this||{},r={},n=(i,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;let a=e&&Jcl(r,o)||o;Qzn(r[a])&&Qzn(i)?r[a]=pHa(r[a],i):Qzn(i)?r[a]=pHa({},i):pur(i)?r[a]=i.slice():(!t||!lur(i))&&(r[a]=i)};for(let i=0,o=arguments.length;i<o;i++)arguments[i]&&N$r(arguments[i],n);return r}var mLb=(e,t,r,{allOwnKeys:n}={})=>(N$r(t,(i,o)=>{r&&d5(i)?Object.defineProperty(e,o,{value:T$r(i,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,o,{value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),e),hLb=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),yLb=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},gLb=(e,t,r,n)=>{let i,o,a,s={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),o=i.length;o-- >0;)a=i[o],(!n||n(a,e,t))&&!s[a]&&(t[a]=e[a],s[a]=!0);e=r!==!1&&fHa(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},bLb=(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},ALb=e=>{if(!e)return null;if(pur(e))return e;let t=e.length;if(!$cl(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},_Lb=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&fHa(Uint8Array)),vLb=(e,t)=>{let n=(e&&e[qzn]).call(e),i;for(;(i=n.next())&&!i.done;){let o=i.value;t.call(e,o[0],o[1])}},OLb=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},wLb=mxe("HTMLFormElement"),PLb=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),Wcl=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),ELb=mxe("RegExp"),Ycl=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};N$r(r,(i,o)=>{let a;(a=t(i,o,e))!==!1&&(n[o]=a||i)}),Object.defineProperties(e,n)},ILb=e=>{Ycl(e,(t,r)=>{if(d5(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(d5(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+"'")})}})},xLb=(e,t)=>{let r={},n=i=>{i.forEach(o=>{r[o]=!0})};return pur(e)?n(e):n(String(e).split(t)),r},jLb=()=>{},CLb=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function SLb(e){return!!(e&&d5(e.append)&&e[Gcl]==="FormData"&&e[qzn])}var BLb=e=>{let t=new Array(10),r=(n,i)=>{if(F$r(n)){if(t.indexOf(n)>=0)return;if(R$r(n))return n;if(!("toJSON"in n)){t[i]=n;let o=pur(n)?[]:{};return N$r(n,(a,s)=>{let c=r(a,i+1);!lur(c)&&(o[s]=c)}),t[i]=void 0,o}}return n};return r(e,0)},DLb=mxe("AsyncFunction"),TLb=e=>e&&(F$r(e)||d5(e))&&d5(e.then)&&d5(e.catch),Xcl=((e,t)=>e?setImmediate:t?((r,n)=>(I4t.addEventListener("message",({source:i,data:o})=>{i===I4t&&o===r&&n.length&&n.shift()()},!1),i=>{n.push(i),I4t.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",d5(I4t.postMessage)),RLb=typeof queueMicrotask<"u"?queueMicrotask.bind(I4t):typeof process<"u"&&process.nextTick||Xcl,FLb=e=>e!=null&&d5(e[qzn]),Ar={isArray:pur,isArrayBuffer:Hcl,isBuffer:R$r,isFormData:sLb,isArrayBufferView:X2b,isString:Z2b,isNumber:$cl,isBoolean:eLb,isObject:F$r,isPlainObject:Qzn,isEmptyObject:tLb,isReadableStream:cLb,isRequest:lLb,isResponse:pLb,isHeaders:fLb,isUndefined:lur,isDate:rLb,isFile:nLb,isBlob:iLb,isRegExp:ELb,isFunction:d5,isStream:aLb,isURLSearchParams:uLb,isTypedArray:_Lb,isFileList:oLb,forEach:N$r,merge:pHa,extend:mLb,trim:dLb,stripBOM:hLb,inherits:yLb,toFlatObject:gLb,kindOf:Vzn,kindOfTest:mxe,endsWith:bLb,toArray:ALb,forEachEntry:vLb,matchAll:OLb,isHTMLForm:wLb,hasOwnProperty:Wcl,hasOwnProp:Wcl,reduceDescriptors:Ycl,freezeMethods:ILb,toObjectSet:xLb,toCamelCase:PLb,noop:jLb,toFiniteNumber:CLb,findKey:Jcl,global:I4t,isContextDefined:Kcl,isSpecCompliantForm:SLb,toJSONObject:BLb,isAsyncFn:DLb,isThenable:TLb,setImmediate:Xcl,asap:RLb,isIterable:FLb};var OU=class e extends Error{static from(t,r,n,i,o,a){let s=new e(t.message,r||t.code,n,i,o);return s.cause=t,s.name=t.name,a&&Object.assign(s,a),s}constructor(t,r,n,i,o){super(t),this.name="AxiosError",this.isAxiosError=!0,r&&(this.code=r),n&&(this.config=n),i&&(this.request=i),o&&(this.response=o,this.status=o.status)}toJSON(){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:Ar.toJSONObject(this.config),code:this.code,status:this.status}}};OU.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";OU.ERR_BAD_OPTION="ERR_BAD_OPTION";OU.ECONNABORTED="ECONNABORTED";OU.ETIMEDOUT="ETIMEDOUT";OU.ERR_NETWORK="ERR_NETWORK";OU.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";OU.ERR_DEPRECATED="ERR_DEPRECATED";OU.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";OU.ERR_BAD_REQUEST="ERR_BAD_REQUEST";OU.ERR_CANCELED="ERR_CANCELED";OU.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";OU.ERR_INVALID_URL="ERR_INVALID_URL";var ca=OU;var Zcl=We(Jnr(),1),Uzn=Zcl.default;function dHa(e){return Ar.isPlainObject(e)||Ar.isArray(e)}function tll(e){return Ar.endsWith(e,"[]")?e.slice(0,-2):e}function ell(e,t,r){return e?e.concat(t).map(function(i,o){return i=tll(i),!r&&o?"["+i+"]":i}).join(r?".":""):t}function NLb(e){return Ar.isArray(e)&&!e.some(dHa)}var MLb=Ar.toFlatObject(Ar,{},null,function(t){return/^is[A-Z]/.test(t)});function zLb(e,t,r){if(!Ar.isObject(e))throw new TypeError("target must be an object");t=t||new(Uzn||FormData),r=Ar.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,g){return!Ar.isUndefined(g[y])});let n=r.metaTokens,i=r.visitor||u,o=r.dots,a=r.indexes,c=(r.Blob||typeof Blob<"u"&&Blob)&&Ar.isSpecCompliantForm(t);if(!Ar.isFunction(i))throw new TypeError("visitor must be a function");function l(h){if(h===null)return"";if(Ar.isDate(h))return h.toISOString();if(Ar.isBoolean(h))return h.toString();if(!c&&Ar.isBlob(h))throw new ca("Blob is not supported. Use a Buffer instead.");return Ar.isArrayBuffer(h)||Ar.isTypedArray(h)?c&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,g){let b=h;if(h&&!g&&typeof h=="object"){if(Ar.endsWith(y,"{}"))y=n?y:y.slice(0,-2),h=JSON.stringify(h);else if(Ar.isArray(h)&&NLb(h)||(Ar.isFileList(h)||Ar.endsWith(y,"[]"))&&(b=Ar.toArray(h)))return y=tll(y),b.forEach(function(O,A){!(Ar.isUndefined(O)||O===null)&&t.append(a===!0?ell([y],A,o):a===null?y:y+"[]",l(O))}),!1}return dHa(h)?!0:(t.append(ell(g,y,o),l(h)),!1)}let p=[],d=Object.assign(MLb,{defaultVisitor:u,convertValue:l,isVisitable:dHa});function m(h,y){if(!Ar.isUndefined(h)){if(p.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));p.push(h),Ar.forEach(h,function(b,_){(!(Ar.isUndefined(b)||b===null)&&i.call(t,b,Ar.isString(_)?_.trim():_,y,d))===!0&&m(b,y?y.concat(_):[_])}),p.pop()}}if(!Ar.isObject(e))throw new TypeError("data must be an object");return m(e),t}var Jht=zLb;function rll(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function nll(e,t){this._pairs=[],e&&Jht(e,this,t)}var ill=nll.prototype;ill.append=function(t,r){this._pairs.push([t,r])};ill.toString=function(t){let r=t?function(n){return t.call(this,n,rll)}:rll;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var oll=nll;function QLb(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function x4t(e,t,r){if(!t)return e;let n=r&&r.encode||QLb,i=Ar.isFunction(r)?{serialize:r}:r,o=i&&i.serialize,a;if(o?a=o(t,i):a=Ar.isURLSearchParams(t)?t.toString():new oll(t,i).toString(n),a){let s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var mHa=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){Ar.forEach(this.handlers,function(n){n!==null&&t(n)})}},hHa=mHa;var Kht={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0};var cll=We(require("crypto"),1);var all=We(require("url"),1),sll=all.default.URLSearchParams;var yHa="abcdefghijklmnopqrstuvwxyz",ull="0123456789",lll={DIGIT:ull,ALPHA:yHa,ALPHA_DIGIT:yHa+yHa.toUpperCase()+ull},qLb=(e=16,t=lll.ALPHA_DIGIT)=>{let r="",{length:n}=t,i=new Uint32Array(e);cll.default.randomFillSync(i);for(let o=0;o<e;o++)r+=t[i[o]%n];return r},pll={isNode:!0,classes:{URLSearchParams:sll,FormData:Uzn,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:lll,generateString:qLb,protocols:["http","https","file","data"]};var AHa={};Q(AHa,{hasBrowserEnv:()=>bHa,hasStandardBrowserEnv:()=>VLb,hasStandardBrowserWebWorkerEnv:()=>kLb,navigator:()=>gHa,origin:()=>ULb});var bHa=typeof window<"u"&&typeof document<"u",gHa=typeof navigator=="object"&&navigator||void 0,VLb=bHa&&(!gHa||["ReactNative","NativeScript","NS"].indexOf(gHa.product)<0),kLb=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",ULb=bHa&&window.location.href||"http://localhost";var jv={...AHa,...pll};function _Ha(e,t){return Jht(e,new jv.classes.URLSearchParams,{visitor:function(r,n,i,o){return jv.isNode&&Ar.isBuffer(r)?(this.append(n,r.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...t})}function LLb(e){return Ar.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function WLb(e){let t={},r=Object.keys(e),n,i=r.length,o;for(n=0;n<i;n++)o=r[n],t[o]=e[o];return t}function GLb(e){function t(r,n,i,o){let a=r[o++];if(a==="__proto__")return!0;let s=Number.isFinite(+a),c=o>=r.length;return a=!a&&Ar.isArray(i)?i.length:a,c?(Ar.hasOwnProp(i,a)?i[a]=[i[a],n]:i[a]=n,!s):((!i[a]||!Ar.isObject(i[a]))&&(i[a]=[]),t(r,n,i[a],o)&&Ar.isArray(i[a])&&(i[a]=WLb(i[a])),!s)}if(Ar.isFormData(e)&&Ar.isFunction(e.entries)){let r={};return Ar.forEachEntry(e,(n,i)=>{t(LLb(n),i,r,0)}),r}return null}var Lzn=GLb;function HLb(e,t,r){if(Ar.isString(e))try{return(t||JSON.parse)(e),Ar.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var vHa={transitional:Kht,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,o=Ar.isObject(t);if(o&&Ar.isHTMLForm(t)&&(t=new FormData(t)),Ar.isFormData(t))return i?JSON.stringify(Lzn(t)):t;if(Ar.isArrayBuffer(t)||Ar.isBuffer(t)||Ar.isStream(t)||Ar.isFile(t)||Ar.isBlob(t)||Ar.isReadableStream(t))return t;if(Ar.isArrayBufferView(t))return t.buffer;if(Ar.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let s;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return _Ha(t,this.formSerializer).toString();if((s=Ar.isFileList(t))||n.indexOf("multipart/form-data")>-1){let c=this.env&&this.env.FormData;return Jht(s?{"files[]":t}:t,c&&new c,this.formSerializer)}}return o||i?(r.setContentType("application/json",!1),HLb(t)):t}],transformResponse:[function(t){let r=this.transitional||vHa.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Ar.isResponse(t)||Ar.isReadableStream(t))return t;if(t&&Ar.isString(t)&&(n&&!this.responseType||i)){let a=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(s){if(a)throw s.name==="SyntaxError"?ca.from(s,ca.ERR_BAD_RESPONSE,this,null,this.response):s}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:jv.classes.FormData,Blob:jv.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Ar.forEach(["delete","get","head","post","put","patch"],e=>{vHa.headers[e]={}});var fur=vHa;var $Lb=Ar.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"]),fll=e=>{let t={},r,n,i;return e&&e.split(`
|
|
1302
|
+
`);for(let a=n;a<o.length;a++){let s=o[a];if(s.length>1024)continue;let c=mcl.test(s)?s.replace(mcl,"$1"):s;if(!c.match(/\S*Error: /)){for(let l of t){let u=l(c,e);if(u){i.push(u);break}}if(i.length>=hcl)break}}return ycl(i)}}var Y7a=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=E$r(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return w4t(t,"DOMException")}isDOMError(t){return w4t(t,"DOMError")}};var X7a=class{match(t){return Q7a(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){return t.stacktrace||t.stack||void 0}};var Z7a=class{constructor(){}match(t){return Uul(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var E2b=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,eHa=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(E2b);return i&&(r=i[1],n=i[2]),[r,n]}};var bcl=["fatal","error","warning","log","info","debug"];function Szn(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var tHa=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return bzn(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=Szn(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return E$r(t)&&!Vul(t)&&bcl.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(ncl(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var rHa=class{match(t){return bzn(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Szn(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var nHa=class{match(t){return I$r(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var iHa=class{match(t){return w4t(t,"PromiseRejectionEvent")}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return I$r(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){if(I$r(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var oHa=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var vcl=require("fs"),Ocl=require("readline"),Bzn=new f5.ReduceableCache(25),wcl=new f5.ReduceableCache(20),aHa=7,I2b=1e3,x2b=1e4;async function Pcl(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],a=o?.filename;if(!o||typeof a!="string"||typeof o.lineno!="number"||B2b(a)||D2b(o))continue;t[a]||(t[a]=[]),t[a].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(wcl.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,l)=>c-l);let a=R2b(o);if(a.every(c=>T2b(i,c)))continue;let s=F2b(Bzn,i,{});n.push(j2b(i,a,s))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&C2b(e,Bzn),Bzn.reduce(),e}function j2b(e,t,r){return new Promise(n=>{let i=(0,vcl.createReadStream)(e),o=(0,Ocl.createInterface)({input:i});function a(){i.destroy(),n()}let s=0,c=0,l=t[c];if(l===void 0)return void a();let u=l[0],p=l[1];function d(){wcl.set(e,1),o.close(),o.removeAllListeners(),a()}i.on("error",d),o.on("error",d),o.on("close",a),o.on("line",m=>{if(s++,!(s<u)&&(r[s]=N2b(m,0),s>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let h=t[c];if(h===void 0){o.close(),o.removeAllListeners();return}u=h[0],p=h[1]}})})}function C2b(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;S2b(r.lineno,r,n)}}function S2b(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Ecl(e);i<e;i++){let o=r[i];if(o===void 0)return void Acl(t);t.pre_context.push(o)}if(r[e]===void 0)return void Acl(t);t.context_line=r[e];let n=Icl(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function Acl(e){delete e.pre_context,delete e.context_line,delete e.post_context}function B2b(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function D2b(e){return e.lineno!==void 0&&e.lineno>x2b||e.colno!==void 0&&e.colno>I2b}function T2b(e,t){let r=Bzn.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 R2b(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=_cl(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+aHa:(i.push(n),n=_cl(o)),t++}return i}function _cl(e){return[Ecl(e),Icl(e)]}function Ecl(e){return Math.max(1,e-aHa)}function Icl(e){return e+aHa}function F2b(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function N2b(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}function M2b(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(a=>a.name!=="domainUncaughtExceptionClear"&&a._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function xcl(e,t){globalThis.process?.on("uncaughtException",M2b(e,t))}function jcl(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var z2b=2e3,dxe=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Azn({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return qul(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i};n||(o.$process_person_profile=!1);let a=this.errorPropertiesBuilder.buildFromUnknown(t,r);return a.$exception_list=await this.errorPropertiesBuilder.modifyFrames(a.$exception_list),{event:"$exception",distinctId:n||FNe(),properties:{...a,...o}}}startAutocaptureIfEnabled(){this.isEnabled()&&(xcl(this.onException.bind(this),this.onFatalError.bind(this)),jcl(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(z2b),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var Ccl="5.24.7";var S$r={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function Scl(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var Q2b=6e4,q2b=1152921504606847e3,V2b=["is_not"],aur=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},kw=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},MNe=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Dzn=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:a,...s}){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=o,this.poller=void 0,this.fetch=s.fetch||fetch,this.onError=s.onError,this.customHeaders=a,this.onLoad=s.onLoad,this.cacheProvider=s.cacheProvider,this.strictLocalEvaluation=s.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let a,s;if(!this.loadedSuccessfullyOnce)return a;if(s=this.featureFlagsByKey[t],s!==void 0)try{a=(await this.computeFlagAndPayloadLocally(s,r,n,i,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${a}`))}catch(c){c instanceof MNe||c instanceof kw?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${t}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${c}`))}return a}async getAllFlagsAndPayloads(t,r={},n={},i={},o){await this.loadFeatureFlags();let a={},s={},c=this.featureFlags.length==0,l=o?o.map(p=>this.featureFlagsByKey[p]).filter(Boolean):this.featureFlags,u={};return await Promise.all(l.map(async p=>{try{let{value:d,payload:m}=await this.computeFlagAndPayloadLocally(p,t,r,n,i,void 0,u);a[p.key]=d,m&&(s[p.key]=m)}catch(d){d instanceof MNe||d instanceof kw?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${p.key}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${p.key}: ${d}`)),c=!0}})),{response:a,payloads:s,fallbackToFlags:c}}async computeFlagAndPayloadLocally(t,r,n={},i={},o={},a,s,c=!1){if(c||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let l;l=a!==void 0?a:await this.computeFlagValueLocally(t,r,n,i,o,s);let u=this.getFeatureFlagPayload(t.key,l);return{value:l,payload:u}}async computeFlagValueLocally(t,r,n={},i={},o={},a={}){if(t.ensure_experience_continuity)throw new kw("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c==null)return await this.matchFeatureFlagProperties(t,r,i,a);{let l=this.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new kw("Flag has unknown group type index");if(!(l in n))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=o[l];return await this.matchFeatureFlagProperties(t,n[l],u,a)}}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n,i){let o=t.key;if(!this.featureFlagsByKey)throw new kw("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new kw(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let a=t.dependency_chain;if(!Array.isArray(a))throw new kw(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(a.length===0)throw new kw(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of a){if(!(c in i)){let u=this.featureFlagsByKey[c];if(u)if(u.active)try{let p=await this.matchFeatureFlagProperties(u,r,n,i);i[c]=p}catch(p){throw new kw(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new kw(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new kw(`Dependency '${c}' could not be evaluated`)}let s=i[o];return this.flagEvaluatesToExpectedValue(t.value,s)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i={}){let o=t.filters||{},a=o.groups||[],s=!1,c;for(let l of a)try{if(await this.isConditionMatch(t,r,l,n,i)){let u=l.variant,p=o.multivariate?.variants||[];c=u&&p.some(d=>d.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof MNe)throw u;if(u instanceof kw)s=!0;else throw u}if(c!==void 0)return c;if(s)throw new kw("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o={}){let a=n.rollout_percentage,s=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let l=c.type,u=!1;if(u=l==="cohort"?Fcl(c,i,this.cohorts,this.debugMode):l==="flag"?await this.evaluateFlagDependency(c,r,i,o):Rcl(c,i,s),!u)return!1}if(a==null)return!0}return!(a!=null&&await Bcl(t.key,r)>a/100)}async getMatchingVariant(t,r){let n=await Bcl(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(s=>{i=n+s.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:s.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Q2b,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new aur(`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.beginBackoff(),new aur(`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.beginBackoff(),new aur(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof aur&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=P4t(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function Bcl(e,t,r=""){let n=await Scl(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/q2b}function Rcl(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")throw new kw("Operator is_not_set is not supported")}else throw new kw(`Property ${n} not found in propertyValues`);let a=t[n];if(a==null&&!V2b.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function s(l,u){return Array.isArray(l)?l.map(p=>String(p).toLowerCase()).includes(String(u).toLowerCase()):String(l).toLowerCase()===String(u).toLowerCase()}function c(l,u,p){if(p==="gt")return l>u;if(p==="gte")return l>=u;if(p==="lt")return l<u;if(p==="lte")return l<=u;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return s(i,a);case"is_not":return!s(i,a);case"is_set":return n in t;case"icontains":return String(a).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(a).toLowerCase().includes(String(i).toLowerCase());case"regex":return Dcl(String(i))&&String(a).match(String(i))!==null;case"not_regex":return Dcl(String(i))&&String(a).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let l=typeof i=="number"?i:null;if(typeof i=="string")try{l=parseFloat(i)}catch{}return l==null||a==null?c(String(a),String(i),o):typeof a=="string"?c(a,String(i),o):c(a,l,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new kw("Date operations cannot be performed on boolean values");let l=U2b(String(i));if(l==null&&(l=Tcl(i)),l==null)throw new kw(`Invalid date: ${i}`);let u=Tcl(a);return["is_date_before"].includes(o)?u<l:u>l}default:throw new kw(`Unknown operator: ${o}`)}}function k2b(e,t){if(!(e in t))throw new MNe(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Fcl(e,t,r,n=!1){let i=String(e.value);k2b(i,r);let o=r[i];return Ncl(o,t,r,n)}function Ncl(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let a=!1;if("values"in o[0]){for(let s of o)try{let c=Ncl(s,t,r,n);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof MNe)throw c;if(c instanceof kw)n&&console.debug(`Failed to compute property ${s} locally: ${c}`),a=!0;else throw c}if(a)throw new kw("Can't match cohort without a given cohort property value");return i==="AND"}for(let s of o)try{let c;if(s.type==="cohort")c=Fcl(s,t,r,n);else if(s.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${s.key||"unknown"}'`);continue}else c=Rcl(s,t);let l=s.negation||!1;if(i==="AND"){if(!c&&!l||c&&l)return!1}else if(c&&!l||!c&&l)return!0}catch(c){if(c instanceof MNe)throw c;if(c instanceof kw)n&&console.debug(`Failed to compute property ${s} locally: ${c}`),a=!0;else throw c}if(a)throw new kw("can't match cohort without a given cohort property value");return i==="AND"}function Dcl(e){try{return new RegExp(e),!0}catch{return!1}}function Tcl(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 kw(`${e} is in an invalid date format`)}throw new kw(`The date provided ${e} must be a string, number, or date object`)}function U2b(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}var Tzn=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var L2b=100,Mcl=3e4,W2b=5e4,Rzn=class extends C$r{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Tzn,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,L2b):Mcl,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new Dzn({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new dxe(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||W2b}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return Ccl}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:a,...s}=r,u={$set:i||s,$set_once:o||{},$anon_distinct_id:a??void 0};super.identifyStateless(t,u,{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:a,...s}=r,u={$set:i||s,$set_once:o||{},$anon_distinct_id:a??void 0};super.identifyStatelessImmediate(t,u,{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=Mcl){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}async _getFeatureFlagResult(t,r,n={},i){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let v=this._flagOverrides[t];if(v===void 0)return;let P=this._payloadOverrides?.[t];return{key:t,enabled:v!==!1,variant:typeof v=="string"?v:void 0,payload:P}}let{groups:a,disableGeoip:s}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,p=this.addLocalPersonAndGroupProperties(r,a,l,u);l=p.allPersonProperties,u=p.allGroupProperties,c==null&&(c=this.options.strictLocalEvaluation??!1);let d,m=!1,h,y,g,b,_,O;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let v=this.featureFlagsPoller?.featureFlagsByKey[t];if(v)try{let P=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(v,r,a,l,u,i);if(P){m=!0;let I=P.value;b=v.id,O="Evaluated locally",d={key:t,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:P.payload??void 0}}}catch(P){if(P instanceof MNe||P instanceof kw)this._logger?.info(`${P.name} when computing flag locally: ${t}: ${P.message}`);else throw P}}if(!m&&!c){let v=await super.getFeatureFlagDetailsStateless(r,a,l,u,s,[t]);if(v===void 0)g=S$r.UNKNOWN_ERROR;else{h=v.requestId,y=v.evaluatedAt;let P=[];v.errorsWhileComputingFlags&&P.push(S$r.ERRORS_WHILE_COMPUTING),v.quotaLimited?.includes("feature_flags")&&P.push(S$r.QUOTA_LIMITED);let I=v.flags[t];if(I===void 0)P.push(S$r.FLAG_MISSING);else{b=I.metadata?.id,_=I.metadata?.version,O=I.reason?.description??I.reason?.code;let E;if(I.metadata?.payload!==void 0)try{E=JSON.parse(I.metadata.payload)}catch{E=I.metadata.payload}d={key:t,enabled:I.enabled,variant:I.variant,payload:E}}P.length>0&&(g=P.join(","))}}if(o){let v=d===void 0?void 0:d.enabled===!1?!1:d.variant??!0,P=`${t}_${v}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(P)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(P):this.distinctIdHasSentFlagCalls[r]=[P];let I={$feature_flag:t,$feature_flag_response:v,$feature_flag_id:b,$feature_flag_version:_,$feature_flag_reason:O,locally_evaluated:m,[`$feature/${t}`]:v,$feature_flag_request_id:h,$feature_flag_evaluated_at:y};g&&(I.$feature_flag_error=g),this.capture({distinctId:r,event:"$feature_flag_called",properties:I,groups:a,disableGeoip:s})}}return d!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(d={...d,payload:this._payloadOverrides[t]}),d}async getFeatureFlag(t,r,n){let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){return this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}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,flagKeys:o}=r||{},{onlyEvaluateLocally:a,personProperties:s,groupProperties:c}=r||{},l=this.addLocalPersonAndGroupProperties(t,n,s,c);s=l.allPersonProperties,c=l.allGroupProperties,a==null&&(a=this.options.strictLocalEvaluation??!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,n,s,c,o),p={},d={},m=!0;if(u&&(p=u.response,d=u.payloads,m=u.fallbackToFlags),m&&!a){let h=await super.getFeatureFlagsAndPayloadsStateless(t,n,s,c,i,o);p={...p,...h.flags||{}},d={...d,...h.payloads||{}}}return this._flagOverrides!==void 0&&(p={...p,...this._flagOverrides}),this._payloadOverrides!==void 0&&(d={...d,...this._payloadOverrides}),{featureFlags:p,featureFlagPayloads:d}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=P4t(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,a]of Object.entries(t))if(Lul(a)&&r&&o in r){let s={};for(let[c,l]of Object.entries(a))s[String(c)]=String(l);i[String(o)]=s}else n[String(o)]=String(a);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},a=i?.groupProperties||{},s=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:a,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:s})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:a,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:s})}return(await super.getFeatureFlagsStateless(t,r,o,a,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},a={};if(r)for(let s of Object.keys(r))a[s]={$group_key:r[s],...i?.[s]||{}};return{allPersonProperties:o,allGroupProperties:a}}captureException(t,r,n,i){if(!dxe.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(dxe.buildEventMessage(t,{syntheticException:o},r,n).then(a=>this.capture({...a,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!dxe.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");this.addPendingPromise(dxe.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:a,timestamp:s,disableGeoip:c,uuid:l}=t,u=this.context?.get(),p=r||u?.distinctId,d={...u?.properties||{},...i||{}};p||(p=FNe(),d.$process_person_profile=!1),u?.sessionId&&!d.$session_id&&(d.$session_id=u.sessionId);let m=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:a,timestamp:s,disableGeoip:c,uuid:l});if(!m)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(a){let y=typeof a=="object"?a:void 0;return await this.getFeatureFlagsForEvent(m.distinctId,o,c,y)}return m.event,{}}).then(y=>{let g={};if(y)for(let[_,O]of Object.entries(y))g[`$feature/${_}`]=O;let b=Object.keys(y||{}).filter(_=>y?.[_]!==!1).sort();return b.length>0&&(g.$active_feature_flags=b),g}).catch(()=>({})).then(y=>({...y,...m.properties||{},$groups:m.groups||o}));return m.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&zul(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",h.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:h,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let a=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(a)}}return i}};var zcl=require("async_hooks"),Fzn=class{constructor(){this.storage=new zcl.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){if(n?.fresh===!0)return this.storage.run(t,r);{let o=this.get()||{},a={distinctId:t.distinctId??o.distinctId,sessionId:t.sessionId??o.sessionId,properties:{...o.properties||{},...t.properties||{}}};return this.storage.run(a,r)}}};var Qcl="posthog-node";function G2b(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return a=>{if(!(i==="*"||i.includes(a.level)))return a;a.tags||(a.tags={});let c=a.tags[sHa.POSTHOG_ID_TAG];if(c===void 0)return a;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,l).toString();a.tags["PostHog Person URL"]=u;let p=a.exception?.values||[],d=p.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),m={$exception_message:p[0]?.value||a.message,$exception_type:p[0]?.type,$exception_level:a.level,$exception_list:d,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:p[0]?.value||a.message,$sentry_exception_type:p[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),o&&e.capture({event:"$exception",distinctId:c,properties:m}),a}}var sHa=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=Qcl,this.name=Qcl,this.setupOnce=function(a,s){let c=s()?.getClient()?.getDsn()?.projectId;a(G2b(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};dxe.errorPropertiesBuilder=new f5.ErrorPropertiesBuilder([new f5.EventCoercer,new f5.ErrorCoercer,new f5.ObjectCoercer,new f5.StringCoercer,new f5.PrimitiveCoercer],f5.createStackParser("node:javascript",f5.nodeStackLineParser),[Tul(),Pcl]);var sur=class extends Rzn{getLibraryId(){return"posthog-node"}initializeContext(){return new Fzn}};var Nzn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new sur(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.72.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var B$r=class{async sendEvent(){}async identify(){}async flush(){}};var uur=require("fs/promises"),Ucl=require("os"),Lcl=require("path");var qcl=We(require("crypto")),zzn=new Uint8Array(256),Mzn=zzn.length;function uHa(){return Mzn>zzn.length-16&&(qcl.default.randomFillSync(zzn),Mzn=0),zzn.slice(Mzn,Mzn+=16)}var $M=[];for(let e=0;e<256;++e)$M.push((e+256).toString(16).slice(1));function Vcl(e,t=0){return $M[e[t+0]]+$M[e[t+1]]+$M[e[t+2]]+$M[e[t+3]]+"-"+$M[e[t+4]]+$M[e[t+5]]+"-"+$M[e[t+6]]+$M[e[t+7]]+"-"+$M[e[t+8]]+$M[e[t+9]]+"-"+$M[e[t+10]]+$M[e[t+11]]+$M[e[t+12]]+$M[e[t+13]]+$M[e[t+14]]+$M[e[t+15]]}var kcl=We(require("crypto")),cHa={randomUUID:kcl.default.randomUUID};function H2b(e,t,r){if(cHa.randomUUID&&!t&&!e)return cHa.randomUUID();e=e||{};let n=e.random||(e.rng||uHa)();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 Vcl(n)}var VJ=H2b;var $2b="id",J2b=".fern",D$r=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new sur(r),this.userId=t==null?void 0:G3a(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.72.1",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await jx({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=vt(xr.of((0,Ucl.homedir)()),Xe.of(J2b),Xe.of($2b));await un(t)||(await(0,uur.mkdir)((0,Lcl.dirname)(t),{recursive:!0}),await(0,uur.writeFile)(t,VJ())),this.persistedDistinctId=(await(0,uur.readFile)(t)).toString()}return this.persistedDistinctId}};var lHa;async function cur(){return lHa==null&&(lHa=await K2b()),lHa}async function K2b(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new B$r;let r=await tTn();return r!=null?new D$r({token:r,posthogApiKey:e}):await yNe()!=null?new Nzn({posthogApiKey:e}):new D$r({token:void 0,posthogApiKey:e})}catch{return new B$r}}function T$r(e,t){return function(){return e.apply(t,arguments)}}var{toString:Y2b}=Object.prototype,{getPrototypeOf:fHa}=Object,{iterator:qzn,toStringTag:Gcl}=Symbol,Vzn=(e=>t=>{let r=Y2b.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),mxe=e=>(e=e.toLowerCase(),t=>Vzn(t)===e),kzn=e=>t=>typeof t===e,{isArray:pur}=Array,lur=kzn("undefined");function R$r(e){return e!==null&&!lur(e)&&e.constructor!==null&&!lur(e.constructor)&&d5(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Hcl=mxe("ArrayBuffer");function X2b(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Hcl(e.buffer),t}var Z2b=kzn("string"),d5=kzn("function"),$cl=kzn("number"),F$r=e=>e!==null&&typeof e=="object",eLb=e=>e===!0||e===!1,Qzn=e=>{if(Vzn(e)!=="object")return!1;let t=fHa(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Gcl in e)&&!(qzn in e)},tLb=e=>{if(!F$r(e)||R$r(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},rLb=mxe("Date"),nLb=mxe("File"),iLb=mxe("Blob"),oLb=mxe("FileList"),aLb=e=>F$r(e)&&d5(e.pipe),sLb=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||d5(e.append)&&((t=Vzn(e))==="formdata"||t==="object"&&d5(e.toString)&&e.toString()==="[object FormData]"))},uLb=mxe("URLSearchParams"),[cLb,lLb,pLb,fLb]=["ReadableStream","Request","Response","Headers"].map(mxe),dLb=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function N$r(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),pur(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(R$r(e))return;let o=r?Object.getOwnPropertyNames(e):Object.keys(e),a=o.length,s;for(n=0;n<a;n++)s=o[n],t.call(null,e[s],s,e)}}function Jcl(e,t){if(R$r(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 I4t=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Kcl=e=>!lur(e)&&e!==I4t;function pHa(){let{caseless:e,skipUndefined:t}=Kcl(this)&&this||{},r={},n=(i,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;let a=e&&Jcl(r,o)||o;Qzn(r[a])&&Qzn(i)?r[a]=pHa(r[a],i):Qzn(i)?r[a]=pHa({},i):pur(i)?r[a]=i.slice():(!t||!lur(i))&&(r[a]=i)};for(let i=0,o=arguments.length;i<o;i++)arguments[i]&&N$r(arguments[i],n);return r}var mLb=(e,t,r,{allOwnKeys:n}={})=>(N$r(t,(i,o)=>{r&&d5(i)?Object.defineProperty(e,o,{value:T$r(i,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,o,{value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),e),hLb=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),yLb=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},gLb=(e,t,r,n)=>{let i,o,a,s={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),o=i.length;o-- >0;)a=i[o],(!n||n(a,e,t))&&!s[a]&&(t[a]=e[a],s[a]=!0);e=r!==!1&&fHa(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},bLb=(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},ALb=e=>{if(!e)return null;if(pur(e))return e;let t=e.length;if(!$cl(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},_Lb=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&fHa(Uint8Array)),vLb=(e,t)=>{let n=(e&&e[qzn]).call(e),i;for(;(i=n.next())&&!i.done;){let o=i.value;t.call(e,o[0],o[1])}},OLb=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},wLb=mxe("HTMLFormElement"),PLb=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),Wcl=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),ELb=mxe("RegExp"),Ycl=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};N$r(r,(i,o)=>{let a;(a=t(i,o,e))!==!1&&(n[o]=a||i)}),Object.defineProperties(e,n)},ILb=e=>{Ycl(e,(t,r)=>{if(d5(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(d5(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+"'")})}})},xLb=(e,t)=>{let r={},n=i=>{i.forEach(o=>{r[o]=!0})};return pur(e)?n(e):n(String(e).split(t)),r},jLb=()=>{},CLb=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function SLb(e){return!!(e&&d5(e.append)&&e[Gcl]==="FormData"&&e[qzn])}var BLb=e=>{let t=new Array(10),r=(n,i)=>{if(F$r(n)){if(t.indexOf(n)>=0)return;if(R$r(n))return n;if(!("toJSON"in n)){t[i]=n;let o=pur(n)?[]:{};return N$r(n,(a,s)=>{let c=r(a,i+1);!lur(c)&&(o[s]=c)}),t[i]=void 0,o}}return n};return r(e,0)},DLb=mxe("AsyncFunction"),TLb=e=>e&&(F$r(e)||d5(e))&&d5(e.then)&&d5(e.catch),Xcl=((e,t)=>e?setImmediate:t?((r,n)=>(I4t.addEventListener("message",({source:i,data:o})=>{i===I4t&&o===r&&n.length&&n.shift()()},!1),i=>{n.push(i),I4t.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",d5(I4t.postMessage)),RLb=typeof queueMicrotask<"u"?queueMicrotask.bind(I4t):typeof process<"u"&&process.nextTick||Xcl,FLb=e=>e!=null&&d5(e[qzn]),Ar={isArray:pur,isArrayBuffer:Hcl,isBuffer:R$r,isFormData:sLb,isArrayBufferView:X2b,isString:Z2b,isNumber:$cl,isBoolean:eLb,isObject:F$r,isPlainObject:Qzn,isEmptyObject:tLb,isReadableStream:cLb,isRequest:lLb,isResponse:pLb,isHeaders:fLb,isUndefined:lur,isDate:rLb,isFile:nLb,isBlob:iLb,isRegExp:ELb,isFunction:d5,isStream:aLb,isURLSearchParams:uLb,isTypedArray:_Lb,isFileList:oLb,forEach:N$r,merge:pHa,extend:mLb,trim:dLb,stripBOM:hLb,inherits:yLb,toFlatObject:gLb,kindOf:Vzn,kindOfTest:mxe,endsWith:bLb,toArray:ALb,forEachEntry:vLb,matchAll:OLb,isHTMLForm:wLb,hasOwnProperty:Wcl,hasOwnProp:Wcl,reduceDescriptors:Ycl,freezeMethods:ILb,toObjectSet:xLb,toCamelCase:PLb,noop:jLb,toFiniteNumber:CLb,findKey:Jcl,global:I4t,isContextDefined:Kcl,isSpecCompliantForm:SLb,toJSONObject:BLb,isAsyncFn:DLb,isThenable:TLb,setImmediate:Xcl,asap:RLb,isIterable:FLb};var OU=class e extends Error{static from(t,r,n,i,o,a){let s=new e(t.message,r||t.code,n,i,o);return s.cause=t,s.name=t.name,a&&Object.assign(s,a),s}constructor(t,r,n,i,o){super(t),this.name="AxiosError",this.isAxiosError=!0,r&&(this.code=r),n&&(this.config=n),i&&(this.request=i),o&&(this.response=o,this.status=o.status)}toJSON(){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:Ar.toJSONObject(this.config),code:this.code,status:this.status}}};OU.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";OU.ERR_BAD_OPTION="ERR_BAD_OPTION";OU.ECONNABORTED="ECONNABORTED";OU.ETIMEDOUT="ETIMEDOUT";OU.ERR_NETWORK="ERR_NETWORK";OU.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";OU.ERR_DEPRECATED="ERR_DEPRECATED";OU.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";OU.ERR_BAD_REQUEST="ERR_BAD_REQUEST";OU.ERR_CANCELED="ERR_CANCELED";OU.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";OU.ERR_INVALID_URL="ERR_INVALID_URL";var ca=OU;var Zcl=We(Jnr(),1),Uzn=Zcl.default;function dHa(e){return Ar.isPlainObject(e)||Ar.isArray(e)}function tll(e){return Ar.endsWith(e,"[]")?e.slice(0,-2):e}function ell(e,t,r){return e?e.concat(t).map(function(i,o){return i=tll(i),!r&&o?"["+i+"]":i}).join(r?".":""):t}function NLb(e){return Ar.isArray(e)&&!e.some(dHa)}var MLb=Ar.toFlatObject(Ar,{},null,function(t){return/^is[A-Z]/.test(t)});function zLb(e,t,r){if(!Ar.isObject(e))throw new TypeError("target must be an object");t=t||new(Uzn||FormData),r=Ar.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,g){return!Ar.isUndefined(g[y])});let n=r.metaTokens,i=r.visitor||u,o=r.dots,a=r.indexes,c=(r.Blob||typeof Blob<"u"&&Blob)&&Ar.isSpecCompliantForm(t);if(!Ar.isFunction(i))throw new TypeError("visitor must be a function");function l(h){if(h===null)return"";if(Ar.isDate(h))return h.toISOString();if(Ar.isBoolean(h))return h.toString();if(!c&&Ar.isBlob(h))throw new ca("Blob is not supported. Use a Buffer instead.");return Ar.isArrayBuffer(h)||Ar.isTypedArray(h)?c&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,g){let b=h;if(h&&!g&&typeof h=="object"){if(Ar.endsWith(y,"{}"))y=n?y:y.slice(0,-2),h=JSON.stringify(h);else if(Ar.isArray(h)&&NLb(h)||(Ar.isFileList(h)||Ar.endsWith(y,"[]"))&&(b=Ar.toArray(h)))return y=tll(y),b.forEach(function(O,A){!(Ar.isUndefined(O)||O===null)&&t.append(a===!0?ell([y],A,o):a===null?y:y+"[]",l(O))}),!1}return dHa(h)?!0:(t.append(ell(g,y,o),l(h)),!1)}let p=[],d=Object.assign(MLb,{defaultVisitor:u,convertValue:l,isVisitable:dHa});function m(h,y){if(!Ar.isUndefined(h)){if(p.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));p.push(h),Ar.forEach(h,function(b,_){(!(Ar.isUndefined(b)||b===null)&&i.call(t,b,Ar.isString(_)?_.trim():_,y,d))===!0&&m(b,y?y.concat(_):[_])}),p.pop()}}if(!Ar.isObject(e))throw new TypeError("data must be an object");return m(e),t}var Jht=zLb;function rll(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function nll(e,t){this._pairs=[],e&&Jht(e,this,t)}var ill=nll.prototype;ill.append=function(t,r){this._pairs.push([t,r])};ill.toString=function(t){let r=t?function(n){return t.call(this,n,rll)}:rll;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var oll=nll;function QLb(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function x4t(e,t,r){if(!t)return e;let n=r&&r.encode||QLb,i=Ar.isFunction(r)?{serialize:r}:r,o=i&&i.serialize,a;if(o?a=o(t,i):a=Ar.isURLSearchParams(t)?t.toString():new oll(t,i).toString(n),a){let s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var mHa=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){Ar.forEach(this.handlers,function(n){n!==null&&t(n)})}},hHa=mHa;var Kht={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0};var cll=We(require("crypto"),1);var all=We(require("url"),1),sll=all.default.URLSearchParams;var yHa="abcdefghijklmnopqrstuvwxyz",ull="0123456789",lll={DIGIT:ull,ALPHA:yHa,ALPHA_DIGIT:yHa+yHa.toUpperCase()+ull},qLb=(e=16,t=lll.ALPHA_DIGIT)=>{let r="",{length:n}=t,i=new Uint32Array(e);cll.default.randomFillSync(i);for(let o=0;o<e;o++)r+=t[i[o]%n];return r},pll={isNode:!0,classes:{URLSearchParams:sll,FormData:Uzn,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:lll,generateString:qLb,protocols:["http","https","file","data"]};var AHa={};Q(AHa,{hasBrowserEnv:()=>bHa,hasStandardBrowserEnv:()=>VLb,hasStandardBrowserWebWorkerEnv:()=>kLb,navigator:()=>gHa,origin:()=>ULb});var bHa=typeof window<"u"&&typeof document<"u",gHa=typeof navigator=="object"&&navigator||void 0,VLb=bHa&&(!gHa||["ReactNative","NativeScript","NS"].indexOf(gHa.product)<0),kLb=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",ULb=bHa&&window.location.href||"http://localhost";var jv={...AHa,...pll};function _Ha(e,t){return Jht(e,new jv.classes.URLSearchParams,{visitor:function(r,n,i,o){return jv.isNode&&Ar.isBuffer(r)?(this.append(n,r.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...t})}function LLb(e){return Ar.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function WLb(e){let t={},r=Object.keys(e),n,i=r.length,o;for(n=0;n<i;n++)o=r[n],t[o]=e[o];return t}function GLb(e){function t(r,n,i,o){let a=r[o++];if(a==="__proto__")return!0;let s=Number.isFinite(+a),c=o>=r.length;return a=!a&&Ar.isArray(i)?i.length:a,c?(Ar.hasOwnProp(i,a)?i[a]=[i[a],n]:i[a]=n,!s):((!i[a]||!Ar.isObject(i[a]))&&(i[a]=[]),t(r,n,i[a],o)&&Ar.isArray(i[a])&&(i[a]=WLb(i[a])),!s)}if(Ar.isFormData(e)&&Ar.isFunction(e.entries)){let r={};return Ar.forEachEntry(e,(n,i)=>{t(LLb(n),i,r,0)}),r}return null}var Lzn=GLb;function HLb(e,t,r){if(Ar.isString(e))try{return(t||JSON.parse)(e),Ar.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var vHa={transitional:Kht,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,o=Ar.isObject(t);if(o&&Ar.isHTMLForm(t)&&(t=new FormData(t)),Ar.isFormData(t))return i?JSON.stringify(Lzn(t)):t;if(Ar.isArrayBuffer(t)||Ar.isBuffer(t)||Ar.isStream(t)||Ar.isFile(t)||Ar.isBlob(t)||Ar.isReadableStream(t))return t;if(Ar.isArrayBufferView(t))return t.buffer;if(Ar.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let s;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return _Ha(t,this.formSerializer).toString();if((s=Ar.isFileList(t))||n.indexOf("multipart/form-data")>-1){let c=this.env&&this.env.FormData;return Jht(s?{"files[]":t}:t,c&&new c,this.formSerializer)}}return o||i?(r.setContentType("application/json",!1),HLb(t)):t}],transformResponse:[function(t){let r=this.transitional||vHa.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Ar.isResponse(t)||Ar.isReadableStream(t))return t;if(t&&Ar.isString(t)&&(n&&!this.responseType||i)){let a=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(s){if(a)throw s.name==="SyntaxError"?ca.from(s,ca.ERR_BAD_RESPONSE,this,null,this.response):s}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:jv.classes.FormData,Blob:jv.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Ar.forEach(["delete","get","head","post","put","patch"],e=>{vHa.headers[e]={}});var fur=vHa;var $Lb=Ar.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"]),fll=e=>{let t={},r,n,i;return e&&e.split(`
|
|
1303
1303
|
`).forEach(function(a){i=a.indexOf(":"),r=a.substring(0,i).trim().toLowerCase(),n=a.substring(i+1).trim(),!(!r||t[r]&&$Lb[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};var dll=Symbol("internals");function M$r(e){return e&&String(e).trim().toLowerCase()}function Wzn(e){return e===!1||e==null?e:Ar.isArray(e)?e.map(Wzn):String(e)}function JLb(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 KLb=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function OHa(e,t,r,n,i){if(Ar.isFunction(n))return n.call(this,t,r);if(i&&(t=r),!!Ar.isString(t)){if(Ar.isString(n))return t.indexOf(n)!==-1;if(Ar.isRegExp(n))return n.test(t)}}function YLb(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function XLb(e,t){let r=Ar.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(i,o,a){return this[n].call(this,t,i,o,a)},configurable:!0})})}var dur=class{constructor(t){t&&this.set(t)}set(t,r,n){let i=this;function o(s,c,l){let u=M$r(c);if(!u)throw new Error("header name must be a non-empty string");let p=Ar.findKey(i,u);(!p||i[p]===void 0||l===!0||l===void 0&&i[p]!==!1)&&(i[p||c]=Wzn(s))}let a=(s,c)=>Ar.forEach(s,(l,u)=>o(l,u,c));if(Ar.isPlainObject(t)||t instanceof this.constructor)a(t,r);else if(Ar.isString(t)&&(t=t.trim())&&!KLb(t))a(fll(t),r);else if(Ar.isObject(t)&&Ar.isIterable(t)){let s={},c,l;for(let u of t){if(!Ar.isArray(u))throw TypeError("Object iterator must return a key-value pair");s[l=u[0]]=(c=s[l])?Ar.isArray(c)?[...c,u[1]]:[c,u[1]]:u[1]}a(s,r)}else t!=null&&o(r,t,n);return this}get(t,r){if(t=M$r(t),t){let n=Ar.findKey(this,t);if(n){let i=this[n];if(!r)return i;if(r===!0)return JLb(i);if(Ar.isFunction(r))return r.call(this,i,n);if(Ar.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=M$r(t),t){let n=Ar.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||OHa(this,this[n],n,r)))}return!1}delete(t,r){let n=this,i=!1;function o(a){if(a=M$r(a),a){let s=Ar.findKey(n,a);s&&(!r||OHa(n,n[s],s,r))&&(delete n[s],i=!0)}}return Ar.isArray(t)?t.forEach(o):o(t),i}clear(t){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let o=r[n];(!t||OHa(this,this[o],o,t,!0))&&(delete this[o],i=!0)}return i}normalize(t){let r=this,n={};return Ar.forEach(this,(i,o)=>{let a=Ar.findKey(n,o);if(a){r[a]=Wzn(i),delete r[o];return}let s=t?YLb(o):String(o).trim();s!==o&&delete r[o],r[s]=Wzn(i),n[s]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return Ar.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=t&&Ar.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(`
|
|
1304
1304
|
`)}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[dll]=this[dll]={accessors:{}}).accessors,i=this.prototype;function o(a){let s=M$r(a);n[s]||(XLb(i,a),n[s]=!0)}return Ar.isArray(t)?t.forEach(o):o(t),this}};dur.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Ar.reduceDescriptors(dur.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});Ar.freezeMethods(dur);var Bx=dur;function z$r(e,t){let r=this||fur,n=t||r,i=Bx.from(n.headers),o=n.data;return Ar.forEach(e,function(s){o=s.call(r,o,i.normalize(),t?t.status:void 0)}),i.normalize(),o}function Q$r(e){return!!(e&&e.__CANCEL__)}var wHa=class extends ca{constructor(t,r,n){super(t??"canceled",ca.ERR_CANCELED,r,n),this.name="CanceledError",this.__CANCEL__=!0}},kJ=wHa;function zNe(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new ca("Request failed with status code "+r.status,[ca.ERR_BAD_REQUEST,ca.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function PHa(e){return typeof e!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function EHa(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function j4t(e,t,r){let n=!PHa(t);return e&&(n||r==!1)?EHa(e,t):t}var Mll=We(IHa(),1),zll=We(require("http"),1),Qll=We(require("https"),1),HHa=We(require("http2"),1),$Ha=We(require("util"),1),qll=We(vll(),1),Bot=We(require("zlib"),1);var B4t="1.13.5";function L$r(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var h3b=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function QHa(e,t,r){let n=r&&r.Blob||jv.classes.Blob,i=L$r(e);if(t===void 0&&n&&(t=!0),i==="data"){e=i.length?e.slice(i.length+1):e;let o=h3b.exec(e);if(!o)throw new ca("Invalid URL",ca.ERR_INVALID_URL);let a=o[1],s=o[2],c=o[3],l=Buffer.from(decodeURIComponent(c),s?"base64":"utf8");if(t){if(!n)throw new ca("Blob is not supported",ca.ERR_NOT_SUPPORT);return new n([l],{type:a})}return l}throw new ca("Unsupported protocol "+i,ca.ERR_NOT_SUPPORT)}var Sot=We(require("stream"),1);var Oll=We(require("stream"),1);var qHa=Symbol("internals"),VHa=class extends Oll.default.Transform{constructor(t){t=Ar.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(n,i)=>!Ar.isUndefined(i[n])),super({readableHighWaterMark:t.chunkSize});let r=this[qHa]={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[qHa];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,n){let i=this[qHa],o=i.maxRate,a=this.readableHighWaterMark,s=i.timeWindow,c=1e3/s,l=o/c,u=i.minChunkSize!==!1?Math.max(i.minChunkSize,l*.01):0,p=(m,h)=>{let y=Buffer.byteLength(m);i.bytesSeen+=y,i.bytes+=y,i.isCaptured&&this.emit("progress",i.bytesSeen),this.push(m)?process.nextTick(h):i.onReadCallback=()=>{i.onReadCallback=null,process.nextTick(h)}},d=(m,h)=>{let y=Buffer.byteLength(m),g=null,b=a,_,O=0;if(o){let A=Date.now();(!i.ts||(O=A-i.ts)>=s)&&(i.ts=A,_=l-i.bytes,i.bytes=_<0?-_:0,O=0),_=l-i.bytes}if(o){if(_<=0)return setTimeout(()=>{h(null,m)},s-O);_<b&&(b=_)}b&&y>b&&y-b>u&&(g=m.subarray(b),m=m.subarray(0,b)),p(m,g?()=>{process.nextTick(h,null,g)}:h)};d(t,function m(h,y){if(h)return n(h);y?d(y,m):n(null)})}},kHa=VHa;var Vll=require("events");var Pll=We(require("util"),1),Ell=require("stream");var{asyncIterator:wll}=Symbol,y3b=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[wll]?yield*e[wll]():yield e},Gzn=y3b;var g3b=jv.ALPHABET.ALPHA_DIGIT+"-_",W$r=typeof TextEncoder=="function"?new TextEncoder:new Pll.default.TextEncoder,D4t=`\r
|
|
1305
1305
|
`,b3b=W$r.encode(D4t),A3b=2,UHa=class{constructor(t,r){let{escapeName:n}=this.constructor,i=Ar.isString(r),o=`Content-Disposition: form-data; name="${n(t)}"${!i&&r.name?`; filename="${n(r.name)}"`:""}${D4t}`;i?r=W$r.encode(String(r).replace(/\r?\n|\r\n?/g,D4t)):o+=`Content-Type: ${r.type||"application/octet-stream"}${D4t}`,this.headers=W$r.encode(o+D4t),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+A3b,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;Ar.isTypedArray(t)?yield t:yield*Gzn(t),yield b3b}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},_3b=(e,t,r)=>{let{tag:n="form-data-boundary",size:i=25,boundary:o=n+"-"+jv.generateString(i,g3b)}=r||{};if(!Ar.isFormData(e))throw TypeError("FormData instance required");if(o.length<1||o.length>70)throw Error("boundary must be 10-70 characters long");let a=W$r.encode("--"+o+D4t),s=W$r.encode("--"+o+"--"+D4t),c=s.byteLength,l=Array.from(e.entries()).map(([p,d])=>{let m=new UHa(p,d);return c+=m.size,m});c+=a.byteLength*l.length,c=Ar.toFiniteNumber(c);let u={"Content-Type":`multipart/form-data; boundary=${o}`};return Number.isFinite(c)&&(u["Content-Length"]=c),t&&t(u),Ell.Readable.from((async function*(){for(let p of l)yield a,yield*p.encode();yield s})())},Ill=_3b;var xll=We(require("stream"),1),LHa=class extends xll.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)}},jll=LHa;var v3b=(e,t)=>Ar.isAsyncFn(e)?function(...r){let n=r.pop();e.apply(this,r).then(i=>{try{t?n(null,...t(i)):n(null,i)}catch(o){n(o)}},n)}:e,Cll=v3b;function O3b(e,t){e=e||10;let r=new Array(e),n=new Array(e),i=0,o=0,a;return t=t!==void 0?t:1e3,function(c){let l=Date.now(),u=n[o];a||(a=l),r[i]=c,n[i]=l;let p=o,d=0;for(;p!==i;)d+=r[p++],p=p%e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),l-a<t)return;let m=u&&l-u;return m?Math.round(d*1e3/m):void 0}}var Sll=O3b;function w3b(e,t){let r=0,n=1e3/t,i,o,a=(l,u=Date.now())=>{r=u,i=null,o&&(clearTimeout(o),o=null),e(...l)};return[(...l)=>{let u=Date.now(),p=u-r;p>=n?a(l,u):(i=l,o||(o=setTimeout(()=>{o=null,a(i)},n-p)))},()=>i&&a(i)]}var Bll=w3b;var Cot=(e,t,r=3)=>{let n=0,i=Sll(50,250);return Bll(o=>{let a=o.loaded,s=o.lengthComputable?o.total:void 0,c=a-n,l=i(c),u=a<=s;n=a;let p={loaded:a,total:s,progress:s?a/s:void 0,bytes:c,rate:l||void 0,estimated:l&&s&&u?(s-a)/l:void 0,event:o,lengthComputable:s!=null,[t?"download":"upload"]:!0};e(p)},r)},hur=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},yur=e=>(...t)=>Ar.asap(()=>e(...t));function WHa(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 o=n.length,a=n.length;for(let d=0;d<a;d++)if(n.charCodeAt(d)===37&&d+2<a){let m=n.charCodeAt(d+1),h=n.charCodeAt(d+2);(m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102)&&(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102)&&(o-=2,d+=2)}let s=0,c=a-1,l=d=>d>=2&&n.charCodeAt(d-2)===37&&n.charCodeAt(d-1)===51&&(n.charCodeAt(d)===68||n.charCodeAt(d)===100);c>=0&&(n.charCodeAt(c)===61?(s++,c--):l(c)&&(s++,c-=3)),s===1&&c>=0&&(n.charCodeAt(c)===61||l(c))&&s++;let p=Math.floor(o/4)*3-(s||0);return p>0?p:0}return Buffer.byteLength(n,"utf8")}var Dll={flush:Bot.default.constants.Z_SYNC_FLUSH,finishFlush:Bot.default.constants.Z_SYNC_FLUSH},P3b={flush:Bot.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:Bot.default.constants.BROTLI_OPERATION_FLUSH},Tll=Ar.isFunction(Bot.default.createBrotliDecompress),{http:E3b,https:I3b}=qll.default,x3b=/https:?/,Rll=jv.protocols.map(e=>e+":"),Fll=(e,[t,r])=>(e.on("end",r).on("error",r),t),GHa=class{constructor(){this.sessions=Object.create(null)}getSession(t,r){r=Object.assign({sessionTimeout:1e3},r);let n=this.sessions[t];if(n){let u=n.length;for(let p=0;p<u;p++){let[d,m]=n[p];if(!d.destroyed&&!d.closed&&$Ha.default.isDeepStrictEqual(m,r))return d}}let i=HHa.default.connect(t,r),o,a=()=>{if(o)return;o=!0;let u=n,p=u.length,d=p;for(;d--;)if(u[d][0]===i){p===1?delete this.sessions[t]:u.splice(d,1);return}},s=i.request,{sessionTimeout:c}=r;if(c!=null){let u,p=0;i.request=function(){let d=s.apply(this,arguments);return p++,u&&(clearTimeout(u),u=null),d.once("close",()=>{--p||(u=setTimeout(()=>{u=null,a()},c))}),d}}i.once("close",a);let l=[i,r];return n?n.push(l):n=this.sessions[t]=[l],i}},j3b=new GHa;function C3b(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function kll(e,t,r){let n=t;if(!n&&n!==!1){let i=Mll.default.getProxyForUrl(r);i&&(n=new URL(i))}if(n){if(n.username&&(n.auth=(n.username||"")+":"+(n.password||"")),n.auth){if(!!(n.auth.username||n.auth.password))n.auth=(n.auth.username||"")+":"+(n.auth.password||"");else if(typeof n.auth=="object")throw new ca("Invalid proxy authorization",ca.ERR_BAD_OPTION,{proxy:n});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(o){kll(o,t,o.href)}}var S3b=typeof process<"u"&&Ar.kindOf(process)==="process",B3b=e=>new Promise((t,r)=>{let n,i,o=(c,l)=>{i||(i=!0,n&&n(c,l))},a=c=>{o(c),t(c)},s=c=>{o(c,!0),r(c)};e(a,s,c=>n=c).catch(s)}),D3b=({address:e,family:t})=>{if(!Ar.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},Nll=(e,t)=>D3b(Ar.isObject(e)?e:{address:e,family:t}),T3b={request(e,t){let r=e.protocol+"//"+e.hostname+":"+(e.port||(e.protocol==="https:"?443:80)),{http2Options:n,headers:i}=e,o=j3b.getSession(r,n),{HTTP2_HEADER_SCHEME:a,HTTP2_HEADER_METHOD:s,HTTP2_HEADER_PATH:c,HTTP2_HEADER_STATUS:l}=HHa.default.constants,u={[a]:e.protocol.replace(":",""),[s]:e.method,[c]:e.path};Ar.forEach(i,(d,m)=>{m.charAt(0)!==":"&&(u[m]=d)});let p=o.request(u);return p.once("response",d=>{let m=p;d=Object.assign({},d);let h=d[l];delete d[l],m.headers=d,m.statusCode=+h,t(m)}),p}},Ull=S3b&&function(t){return B3b(async function(n,i,o){let{data:a,lookup:s,family:c,httpVersion:l=1,http2Options:u}=t,{responseType:p,responseEncoding:d}=t,m=t.method.toUpperCase(),h,y=!1,g;if(l=+l,Number.isNaN(l))throw TypeError(`Invalid protocol version: '${t.httpVersion}' is not a number`);if(l!==1&&l!==2)throw TypeError(`Unsupported protocol version '${l}'`);let b=l===2;if(s){let Z=Cll(s,Y=>Ar.isArray(Y)?Y:[Y]);s=(Y,Be,Pe)=>{Z(Y,Be,(ke,Ye,Oe)=>{if(ke)return Pe(ke);let he=Ar.isArray(Ye)?Ye.map(pt=>Nll(pt)):[Nll(Ye,Oe)];Be.all?Pe(ke,he):Pe(ke,he[0].address,he[0].family)})}}let _=new Vll.EventEmitter;function O(Z){try{_.emit("abort",!Z||Z.type?new kJ(null,t,g):Z)}catch(Y){console.warn("emit error",Y)}}_.once("abort",i);let A=()=>{t.cancelToken&&t.cancelToken.unsubscribe(O),t.signal&&t.signal.removeEventListener("abort",O),_.removeAllListeners()};(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(O),t.signal&&(t.signal.aborted?O():t.signal.addEventListener("abort",O))),o((Z,Y)=>{if(h=!0,Y){y=!0,A();return}let{data:Be}=Z;if(Be instanceof Sot.default.Readable||Be instanceof Sot.default.Duplex){let Pe=Sot.default.finished(Be,()=>{Pe(),A()})}else A()});let v=j4t(t.baseURL,t.url,t.allowAbsoluteUrls),P=new URL(v,jv.hasBrowserEnv?jv.origin:void 0),I=P.protocol||Rll[0];if(I==="data:"){if(t.maxContentLength>-1){let Y=String(t.url||v||"");if(WHa(Y)>t.maxContentLength)return i(new ca("maxContentLength size of "+t.maxContentLength+" exceeded",ca.ERR_BAD_RESPONSE,t))}let Z;if(m!=="GET")return zNe(n,i,{status:405,statusText:"method not allowed",headers:{},config:t});try{Z=QHa(t.url,p==="blob",{Blob:t.env&&t.env.Blob})}catch(Y){throw ca.from(Y,ca.ERR_BAD_REQUEST,t)}return p==="text"?(Z=Z.toString(d),(!d||d==="utf8")&&(Z=Ar.stripBOM(Z))):p==="stream"&&(Z=Sot.default.Readable.from(Z)),zNe(n,i,{data:Z,status:200,statusText:"OK",headers:new Bx,config:t})}if(Rll.indexOf(I)===-1)return i(new ca("Unsupported protocol "+I,ca.ERR_BAD_REQUEST,t));let E=Bx.from(t.headers).normalize();E.set("User-Agent","axios/"+B4t,!1);let{onUploadProgress:x,onDownloadProgress:T}=t,W=t.maxRate,H,G;if(Ar.isSpecCompliantForm(a)){let Z=E.getContentType(/boundary=([-_\w\d]{10,70})/i);a=Ill(a,Y=>{E.set(Y)},{tag:`axios-${B4t}-boundary`,boundary:Z&&Z[1]||void 0})}else if(Ar.isFormData(a)&&Ar.isFunction(a.getHeaders)){if(E.set(a.getHeaders()),!E.hasContentLength())try{let Z=await $Ha.default.promisify(a.getLength).call(a);Number.isFinite(Z)&&Z>=0&&E.setContentLength(Z)}catch{}}else if(Ar.isBlob(a)||Ar.isFile(a))a.size&&E.setContentType(a.type||"application/octet-stream"),E.setContentLength(a.size||0),a=Sot.default.Readable.from(Gzn(a));else if(a&&!Ar.isStream(a)){if(!Buffer.isBuffer(a))if(Ar.isArrayBuffer(a))a=Buffer.from(new Uint8Array(a));else if(Ar.isString(a))a=Buffer.from(a,"utf-8");else return i(new ca("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",ca.ERR_BAD_REQUEST,t));if(E.setContentLength(a.length,!1),t.maxBodyLength>-1&&a.length>t.maxBodyLength)return i(new ca("Request body larger than maxBodyLength limit",ca.ERR_BAD_REQUEST,t))}let ie=Ar.toFiniteNumber(E.getContentLength());Ar.isArray(W)?(H=W[0],G=W[1]):H=G=W,a&&(x||H)&&(Ar.isStream(a)||(a=Sot.default.Readable.from(a,{objectMode:!1})),a=Sot.default.pipeline([a,new kHa({maxRate:Ar.toFiniteNumber(H)})],Ar.noop),x&&a.on("progress",Fll(a,hur(ie,Cot(yur(x),!1,3)))));let oe;if(t.auth){let Z=t.auth.username||"",Y=t.auth.password||"";oe=Z+":"+Y}if(!oe&&P.username){let Z=P.username,Y=P.password;oe=Z+":"+Y}oe&&E.delete("authorization");let $;try{$=x4t(P.pathname+P.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(Z){let Y=new Error(Z.message);return Y.config=t,Y.url=t.url,Y.exists=!0,i(Y)}E.set("Accept-Encoding","gzip, compress, deflate"+(Tll?", br":""),!1);let te={path:$,method:m,headers:E.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:oe,protocol:I,family:c,beforeRedirect:C3b,beforeRedirects:{},http2Options:u};!Ar.isUndefined(s)&&(te.lookup=s),t.socketPath?te.socketPath=t.socketPath:(te.hostname=P.hostname.startsWith("[")?P.hostname.slice(1,-1):P.hostname,te.port=P.port,kll(te,t.proxy,I+"//"+P.hostname+(P.port?":"+P.port:"")+te.path));let Ge,Ke=x3b.test(te.protocol);if(te.agent=Ke?t.httpsAgent:t.httpAgent,b?Ge=T3b:t.transport?Ge=t.transport:t.maxRedirects===0?Ge=Ke?Qll.default:zll.default:(t.maxRedirects&&(te.maxRedirects=t.maxRedirects),t.beforeRedirect&&(te.beforeRedirects.config=t.beforeRedirect),Ge=Ke?I3b:E3b),t.maxBodyLength>-1?te.maxBodyLength=t.maxBodyLength:te.maxBodyLength=1/0,t.insecureHTTPParser&&(te.insecureHTTPParser=t.insecureHTTPParser),g=Ge.request(te,function(Y){if(g.destroyed)return;let Be=[Y],Pe=Ar.toFiniteNumber(Y.headers["content-length"]);if(T||G){let he=new kHa({maxRate:Ar.toFiniteNumber(G)});T&&he.on("progress",Fll(he,hur(Pe,Cot(yur(T),!0,3)))),Be.push(he)}let ke=Y,Ye=Y.req||g;if(t.decompress!==!1&&Y.headers["content-encoding"])switch((m==="HEAD"||Y.statusCode===204)&&delete Y.headers["content-encoding"],(Y.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Be.push(Bot.default.createUnzip(Dll)),delete Y.headers["content-encoding"];break;case"deflate":Be.push(new jll),Be.push(Bot.default.createUnzip(Dll)),delete Y.headers["content-encoding"];break;case"br":Tll&&(Be.push(Bot.default.createBrotliDecompress(P3b)),delete Y.headers["content-encoding"])}ke=Be.length>1?Sot.default.pipeline(Be,Ar.noop):Be[0];let Oe={status:Y.statusCode,statusText:Y.statusMessage,headers:new Bx(Y.headers),config:t,request:Ye};if(p==="stream")Oe.data=ke,zNe(n,i,Oe);else{let he=[],pt=0;ke.on("data",function(br){he.push(br),pt+=br.length,t.maxContentLength>-1&&pt>t.maxContentLength&&(y=!0,ke.destroy(),O(new ca("maxContentLength size of "+t.maxContentLength+" exceeded",ca.ERR_BAD_RESPONSE,t,Ye)))}),ke.on("aborted",function(){if(y)return;let br=new ca("stream has been aborted",ca.ERR_BAD_RESPONSE,t,Ye);ke.destroy(br),i(br)}),ke.on("error",function(br){g.destroyed||i(ca.from(br,null,t,Ye))}),ke.on("end",function(){try{let br=he.length===1?he[0]:Buffer.concat(he);p!=="arraybuffer"&&(br=br.toString(d),(!d||d==="utf8")&&(br=Ar.stripBOM(br))),Oe.data=br}catch(br){return i(ca.from(br,null,t,Oe.request,Oe))}zNe(n,i,Oe)})}_.once("abort",he=>{ke.destroyed||(ke.emit("error",he),ke.destroy())})}),_.once("abort",Z=>{g.close?g.close():g.destroy(Z)}),g.on("error",function(Y){i(ca.from(Y,null,t,g))}),g.on("socket",function(Y){Y.setKeepAlive(!0,1e3*60)}),t.timeout){let Z=parseInt(t.timeout,10);if(Number.isNaN(Z)){O(new ca("error trying to parse `config.timeout` to int",ca.ERR_BAD_OPTION_VALUE,t,g));return}g.setTimeout(Z,function(){if(h)return;let Be=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",Pe=t.transitional||Kht;t.timeoutErrorMessage&&(Be=t.timeoutErrorMessage),O(new ca(Be,Pe.clarifyTimeoutError?ca.ETIMEDOUT:ca.ECONNABORTED,t,g))})}else g.setTimeout(0);if(Ar.isStream(a)){let Z=!1,Y=!1;a.on("end",()=>{Z=!0}),a.once("error",Be=>{Y=!0,g.destroy(Be)}),a.on("close",()=>{!Z&&!Y&&O(new kJ("Request stream has been aborted",t,g))}),a.pipe(g)}else a&&g.write(a),g.end()})};var Lll=jv.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,jv.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(jv.origin),jv.navigator&&/(msie|trident)/i.test(jv.navigator.userAgent)):()=>!0;var Wll=jv.hasStandardBrowserEnv?{write(e,t,r,n,i,o,a){if(typeof document>"u")return;let s=[`${e}=${encodeURIComponent(t)}`];Ar.isNumber(r)&&s.push(`expires=${new Date(r).toUTCString()}`),Ar.isString(n)&&s.push(`path=${n}`),Ar.isString(i)&&s.push(`domain=${i}`),o===!0&&s.push("secure"),Ar.isString(a)&&s.push(`SameSite=${a}`),document.cookie=s.join("; ")},read(e){if(typeof document>"u")return null;let t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};var Gll=e=>e instanceof Bx?{...e}:e;function hxe(e,t){t=t||{};let r={};function n(l,u,p,d){return Ar.isPlainObject(l)&&Ar.isPlainObject(u)?Ar.merge.call({caseless:d},l,u):Ar.isPlainObject(u)?Ar.merge({},u):Ar.isArray(u)?u.slice():u}function i(l,u,p,d){if(Ar.isUndefined(u)){if(!Ar.isUndefined(l))return n(void 0,l,p,d)}else return n(l,u,p,d)}function o(l,u){if(!Ar.isUndefined(u))return n(void 0,u)}function a(l,u){if(Ar.isUndefined(u)){if(!Ar.isUndefined(l))return n(void 0,l)}else return n(void 0,u)}function s(l,u,p){if(p in t)return n(l,u);if(p in e)return n(void 0,l)}let c={url:o,method:o,data:o,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:s,headers:(l,u,p)=>i(Gll(l),Gll(u),p,!0)};return Ar.forEach(Object.keys({...e,...t}),function(u){if(u==="__proto__"||u==="constructor"||u==="prototype")return;let p=Ar.hasOwnProp(c,u)?c[u]:i,d=p(e[u],t[u],u);Ar.isUndefined(d)&&p!==s||(r[u]=d)}),r}var Hzn=e=>{let t=hxe({},e),{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:o,headers:a,auth:s}=t;if(t.headers=a=Bx.from(a),t.url=x4t(j4t(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),s&&a.set("Authorization","Basic "+btoa((s.username||"")+":"+(s.password?unescape(encodeURIComponent(s.password)):""))),Ar.isFormData(r)){if(jv.hasStandardBrowserEnv||jv.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(Ar.isFunction(r.getHeaders)){let c=r.getHeaders(),l=["content-type","content-length"];Object.entries(c).forEach(([u,p])=>{l.includes(u.toLowerCase())&&a.set(u,p)})}}if(jv.hasStandardBrowserEnv&&(n&&Ar.isFunction(n)&&(n=n(t)),n||n!==!1&&Lll(t.url))){let c=i&&o&&Wll.read(o);c&&a.set(i,c)}return t};var R3b=typeof XMLHttpRequest<"u",Hll=R3b&&function(e){return new Promise(function(r,n){let i=Hzn(e),o=i.data,a=Bx.from(i.headers).normalize(),{responseType:s,onUploadProgress:c,onDownloadProgress:l}=i,u,p,d,m,h;function y(){m&&m(),h&&h(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let g=new XMLHttpRequest;g.open(i.method.toUpperCase(),i.url,!0),g.timeout=i.timeout;function b(){if(!g)return;let O=Bx.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders()),v={data:!s||s==="text"||s==="json"?g.responseText:g.response,status:g.status,statusText:g.statusText,headers:O,config:e,request:g};zNe(function(I){r(I),y()},function(I){n(I),y()},v),g=null}"onloadend"in g?g.onloadend=b:g.onreadystatechange=function(){!g||g.readyState!==4||g.status===0&&!(g.responseURL&&g.responseURL.indexOf("file:")===0)||setTimeout(b)},g.onabort=function(){g&&(n(new ca("Request aborted",ca.ECONNABORTED,e,g)),g=null)},g.onerror=function(A){let v=A&&A.message?A.message:"Network Error",P=new ca(v,ca.ERR_NETWORK,e,g);P.event=A||null,n(P),g=null},g.ontimeout=function(){let A=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",v=i.transitional||Kht;i.timeoutErrorMessage&&(A=i.timeoutErrorMessage),n(new ca(A,v.clarifyTimeoutError?ca.ETIMEDOUT:ca.ECONNABORTED,e,g)),g=null},o===void 0&&a.setContentType(null),"setRequestHeader"in g&&Ar.forEach(a.toJSON(),function(A,v){g.setRequestHeader(v,A)}),Ar.isUndefined(i.withCredentials)||(g.withCredentials=!!i.withCredentials),s&&s!=="json"&&(g.responseType=i.responseType),l&&([d,h]=Cot(l,!0),g.addEventListener("progress",d)),c&&g.upload&&([p,m]=Cot(c),g.upload.addEventListener("progress",p),g.upload.addEventListener("loadend",m)),(i.cancelToken||i.signal)&&(u=O=>{g&&(n(!O||O.type?new kJ(null,e,g):O),g.abort(),g=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));let _=L$r(i.url);if(_&&jv.protocols.indexOf(_)===-1){n(new ca("Unsupported protocol "+_+":",ca.ERR_BAD_REQUEST,e));return}g.send(o||null)})};var F3b=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let n=new AbortController,i,o=function(l){if(!i){i=!0,s();let u=l instanceof Error?l:this.reason;n.abort(u instanceof ca?u:new kJ(u instanceof Error?u.message:u))}},a=t&&setTimeout(()=>{a=null,o(new ca(`timeout of ${t}ms exceeded`,ca.ETIMEDOUT))},t),s=()=>{e&&(a&&clearTimeout(a),a=null,e.forEach(l=>{l.unsubscribe?l.unsubscribe(o):l.removeEventListener("abort",o)}),e=null)};e.forEach(l=>l.addEventListener("abort",o));let{signal:c}=n;return c.unsubscribe=()=>Ar.asap(s),c}},$ll=F3b;var N3b=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},M3b=async function*(e,t){for await(let r of z3b(e))yield*N3b(r,t)},z3b=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()}},JHa=(e,t,r,n)=>{let i=M3b(e,t),o=0,a,s=c=>{a||(a=!0,n&&n(c))};return new ReadableStream({async pull(c){try{let{done:l,value:u}=await i.next();if(l){s(),c.close();return}let p=u.byteLength;if(r){let d=o+=p;r(d)}c.enqueue(new Uint8Array(u))}catch(l){throw s(l),l}},cancel(c){return s(c),i.return()}},{highWaterMark:2})};var Jll=64*1024,{isFunction:$zn}=Ar,Q3b=(({Request:e,Response:t})=>({Request:e,Response:t}))(Ar.global),{ReadableStream:Kll,TextEncoder:Yll}=Ar.global,Xll=(e,...t)=>{try{return!!e(...t)}catch{return!1}},q3b=e=>{e=Ar.merge.call({skipUndefined:!0},Q3b,e);let{fetch:t,Request:r,Response:n}=e,i=t?$zn(t):typeof fetch=="function",o=$zn(r),a=$zn(n);if(!i)return!1;let s=i&&$zn(Kll),c=i&&(typeof Yll=="function"?(h=>y=>h.encode(y))(new Yll):async h=>new Uint8Array(await new r(h).arrayBuffer())),l=o&&s&&Xll(()=>{let h=!1,y=new r(jv.origin,{body:new Kll,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!y}),u=a&&s&&Xll(()=>Ar.isReadableStream(new n("").body)),p={stream:u&&(h=>h.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!p[h]&&(p[h]=(y,g)=>{let b=y&&y[h];if(b)return b.call(y);throw new ca(`Response type '${h}' is not supported`,ca.ERR_NOT_SUPPORT,g)})});let d=async h=>{if(h==null)return 0;if(Ar.isBlob(h))return h.size;if(Ar.isSpecCompliantForm(h))return(await new r(jv.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(Ar.isArrayBufferView(h)||Ar.isArrayBuffer(h))return h.byteLength;if(Ar.isURLSearchParams(h)&&(h=h+""),Ar.isString(h))return(await c(h)).byteLength},m=async(h,y)=>{let g=Ar.toFiniteNumber(h.getContentLength());return g??d(y)};return async h=>{let{url:y,method:g,data:b,signal:_,cancelToken:O,timeout:A,onDownloadProgress:v,onUploadProgress:P,responseType:I,headers:E,withCredentials:x="same-origin",fetchOptions:T}=Hzn(h),W=t||fetch;I=I?(I+"").toLowerCase():"text";let H=$ll([_,O&&O.toAbortSignal()],A),G=null,ie=H&&H.unsubscribe&&(()=>{H.unsubscribe()}),oe;try{if(P&&l&&g!=="get"&&g!=="head"&&(oe=await m(E,b))!==0){let Y=new r(y,{method:"POST",body:b,duplex:"half"}),Be;if(Ar.isFormData(b)&&(Be=Y.headers.get("content-type"))&&E.setContentType(Be),Y.body){let[Pe,ke]=hur(oe,Cot(yur(P)));b=JHa(Y.body,Jll,Pe,ke)}}Ar.isString(x)||(x=x?"include":"omit");let $=o&&"credentials"in r.prototype,te={...T,signal:H,method:g.toUpperCase(),headers:E.normalize().toJSON(),body:b,duplex:"half",credentials:$?x:void 0};G=o&&new r(y,te);let Ge=await(o?W(G,T):W(y,te)),Ke=u&&(I==="stream"||I==="response");if(u&&(v||Ke&&ie)){let Y={};["status","statusText","headers"].forEach(Ye=>{Y[Ye]=Ge[Ye]});let Be=Ar.toFiniteNumber(Ge.headers.get("content-length")),[Pe,ke]=v&&hur(Be,Cot(yur(v),!0))||[];Ge=new n(JHa(Ge.body,Jll,Pe,()=>{ke&&ke(),ie&&ie()}),Y)}I=I||"text";let Z=await p[Ar.findKey(p,I)||"text"](Ge,h);return!Ke&&ie&&ie(),await new Promise((Y,Be)=>{zNe(Y,Be,{data:Z,headers:Bx.from(Ge.headers),status:Ge.status,statusText:Ge.statusText,config:h,request:G})})}catch($){throw ie&&ie(),$&&$.name==="TypeError"&&/Load failed|fetch/i.test($.message)?Object.assign(new ca("Network Error",ca.ERR_NETWORK,h,G,$&&$.response),{cause:$.cause||$}):ca.from($,$&&$.code,h,G,$&&$.response)}}},V3b=new Map,KHa=e=>{let t=e&&e.env||{},{fetch:r,Request:n,Response:i}=t,o=[n,i,r],a=o.length,s=a,c,l,u=V3b;for(;s--;)c=o[s],l=u.get(c),l===void 0&&u.set(c,l=s?new Map:q3b(t)),u=l;return l},N0C=KHa();var YHa={http:Ull,xhr:Hll,fetch:{get:KHa}};Ar.forEach(YHa,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var Zll=e=>`- ${e}`,U3b=e=>Ar.isFunction(e)||e===null||e===!1;function L3b(e,t){e=Ar.isArray(e)?e:[e];let{length:r}=e,n,i,o={};for(let a=0;a<r;a++){n=e[a];let s;if(i=n,!U3b(n)&&(i=YHa[(s=String(n)).toLowerCase()],i===void 0))throw new ca(`Unknown adapter '${s}'`);if(i&&(Ar.isFunction(i)||(i=i.get(t))))break;o[s||"#"+a]=i}if(!i){let a=Object.entries(o).map(([c,l])=>`adapter ${c} `+(l===!1?"is not supported by the environment":"is not available in the build")),s=r?a.length>1?`since :
|
|
@@ -1529,7 +1529,7 @@ ${r}`);return i!=null?i(a):a},Rvl(n))}var ers=class{async handle(t,r){let n=r["d
|
|
|
1529
1529
|
Location: ${i.join("-> ")}`),Bn.unknown({nameOverride:p,generatedName:h,title:y,description:g,availability:b,namespace:s,groupName:m,example:void 0})}}function xaA(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1}}}function Bgt(e){if(e.$ref.startsWith(nLt))return e.$ref.replace(nLt,"")}function qas(e,t,r,n,i){let o=ni(e,wi.TYPE_NAME),a=HC(t,n),s=e.description,c=rq(e),l=Bgt(e);if(l==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return Pc.reference({generatedName:a,nameOverride:o,title:void 0,schema:l,description:s??void 0,availability:c,namespace:i.getNamespace(l),groupName:void 0,source:r})}function jaA(e){return e.oneOf==null||e.oneOf.length===0}function gSl(e){return e.allOf==null||e.allOf.length===0}function WJn(e){return e.properties==null||kO(e.properties)===0}function HJn(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function jMe(e,t,r,n){if(e.type==="reference")return Bn.reference({...e,description:t,availability:e.availability,namespace:r,groupName:n});if(e.type==="optional"){let i=jMe(e.value,t,r,n);return Bn.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i,description:t,availability:e.availability,namespace:r,groupName:n,inline:void 0})}else if(e.type==="nullable"){let i=jMe(e.value,t,r,n);return Bn.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i,description:t,availability:e.availability,namespace:r,groupName:n,inline:void 0})}else if(e.type==="primitive"&&t!=null&&e.description==null)return Bn.primitive({...e,description:t});return e}function GJn(e){return fo(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>GJn(t)):e.oneOf!=null?e.oneOf.every(t=>GJn(t)):e.anyOf!=null?e.anyOf.every(t=>GJn(t)):!1}function bSl({literal:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:o,availability:a,nameOverride:s,generatedName:c,title:l}){let u=Bn.literal({nameOverride:s,generatedName:c,title:l,value:e,namespace:n,groupName:i,description:o,availability:a});return r&&(u=Bn.nullable({nameOverride:s,generatedName:c,title:l,value:u,namespace:n,groupName:i,description:o,availability:a,inline:void 0})),t&&(u=Bn.optional({nameOverride:s,generatedName:c,title:l,value:u,namespace:n,groupName:i,description:o,availability:a,inline:void 0})),u}function nq({primitive:e,wrapAsOptional:t,wrapAsNullable:r,namespace:n,groupName:i,description:o,availability:a,generatedName:s,nameOverride:c,title:l}){i=typeof i=="string"?[i]:i;let u=Bn.primitive({nameOverride:c,generatedName:s,title:l,schema:e,description:o,availability:a,namespace:n,groupName:i});return r&&(u=Bn.nullable({nameOverride:c,generatedName:s,title:l,value:u,namespace:n,groupName:i,description:o,availability:a,inline:void 0})),t&&(u=Bn.optional({nameOverride:c,generatedName:s,title:l,value:u,namespace:n,groupName:i,description:o,availability:a,inline:void 0})),u}function CaA({schemas:e}){let t=new Set;for(let r of e){if(fo(r))return;if(r.enum!=null&&HJn(r.enum))r.enum.forEach(n=>t.add(n));else return}return Array.from(t)}function ASl({schemas:e,context:t}){let r={};for(let n of e){let i=OSl({schema:n,context:t});for(let[o,a]of Object.entries(i)){let s=r[o];s!=null?s[a]=n:r[o]={[a]:n}}}for(let[n,i]of Object.entries(r))if(Object.keys(i).length===e.length)return{discriminant:n,schemas:i}}function OSl({schema:e,context:t}){let r=fo(e)?t.resolveSchemaReference(e):e;return SaA({schema:r,context:t})}function SaA({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let n of e.anyOf){let i=OSl({schema:n,context:t});for(let[o,a]of Object.entries(i??{}))r[o]=a}return r}for(let[n,i]of Object.entries(e.properties??{})){let o=fo(i)?t.resolveSchemaReference(i):i;o.type==="string"&&o.enum!=null&&HJn(o.enum)&&BaA(o.enum).length===1&&o.enum[0]!=null&&(r[n]=o.enum[0]);let a=wSl(o,"const");o.type==="string"&&a!=null&&(r[n]=a),n==="type"&&o.example!=null&&(r[n]=o.example)}return r}function BaA(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function wSl(e,t){let r=e[t];if(r!=null)return r}function DaA({schema:e,logger:t}){let r=XCl({schema:e,logger:t});if(r!=null)return aSl(r)}var Rfr=class{document;taskContext;logger;DUMMY;options;namespace;static MESSAGE_REFERENCE_PREFIX="#/components/messages/";constructor({document:t,taskContext:r,options:n,namespace:i}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=n,this.namespace=i}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let n=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};n.push(i)}return n.concat(t??[])}resolveSchemaReference(t){if(!t.$ref.startsWith(nLt))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let n=t.$ref.substring(nLt.length).split("/"),i=this.document.components;if(i==null||i.schemas==null)throw new Error("Document does not have components.schemas.");let[o,a,s]=n;if(o==null||o==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let c=i.schemas[o];if(c==null)throw new Error(`Schema "${o}" is undefined in document.components.schemas.`);if(fo(c)&&(c=this.resolveSchemaReference(c)),a==="properties"&&s!=null){let l=c.properties?.[s];if(l==null)throw new Error(`Property "${s}" not found on "${o}". Full ref: ${t.$ref}`);fo(l)?c=this.resolveSchemaReference(l):c=l}return c}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,n){}markSchemaWithDiscriminantValue(t,r,n){}getNamespace(t){return this.namespace}};var JJn=class extends Rfr{getExampleMessageReference(t){return`#/components/messages/${t.messageId}`}resolveMessageReference(t){let r="#/components/messages/",n=this.document.components;if(n==null||n.messages==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve message reference: ${t.$ref} in v2 components`);let i=t.$ref.substring(r.length),o=n.messages[i];if(o==null)throw new Error(`${t.$ref} is undefined`);return o}};function Ffr(e,t){let r={};if(e!=null)return{rootSchemas:r,namespacedSchemas:{[e]:t}};let n={};for(let[i,o]of Object.entries(t))switch(o.type){case"object":case"array":case"map":case"optional":case"enum":case"literal":case"reference":case"nullable":case"primitive":{if(o.namespace==null){r[i]=o;continue}let a=o.namespace;n[a]??={},n[a][i]=o;continue}case"oneOf":case"unknown":r[i]=o;continue;default:qe(o)}return{rootSchemas:r,namespacedSchemas:n}}var Nfr=We(require("fs"),1),iLt=We(require("path"),1);function Tgt(e){if(typeof e=="string")return Al.primitive(Ga.string(e));if(typeof e=="number")return Number.isInteger(e)?Al.primitive(Ga.int(e)):Al.primitive(Ga.double(e));if(typeof e=="boolean")return Al.primitive(Ga.boolean(e));if(Array.isArray(e)){let t=e.map(r=>Tgt(r));return t.length===0?void 0:Al.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,n]of Object.entries(e)){let i=Tgt(n);i!=null&&t.push({key:Ga.string(r),value:i})}return Al.map(t)}}function rXr(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function PSl(e){if(e!=null&&Array.isArray(e))return e}var Rgt=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,n){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=n}buildExample({schema:t,exampleId:r,example:n,options:i,skipReadonly:o}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:n,options:{...i,maxCheckerDepth:i.maxCheckerDepth??5},depth:0,skipReadonly:o??!1})}buildExampleHelper({exampleId:t,example:r,schema:n,depth:i,visitedSchemaIds:o,options:a,skipReadonly:s}){switch(n.type){case"enum":return typeof r=="string"&&ESl({schema:n,value:r})?Al.enum(r):n.values[0]!=null?Al.enum(n.values[0]?.value):void 0;case"literal":return Al.literal(n.value);case"nullable":{if(r===null)return Al.null({});if(r==null&&!this.hasExample(n.value,0,o,a)&&this.exceedsMaxDepth(i,a))return Al.null({});let c=this.buildExampleHelper({schema:n.value,visitedSchemaIds:o,exampleId:t,example:r,depth:i,options:a,skipReadonly:s});return c??Al.null({})}case"optional":{if(r==null&&!this.hasExample(n.value,0,o,a)&&(a.ignoreOptionals||this.exceedsMaxDepth(i,a))||Object.is(r,null))return;let c=this.buildExampleHelper({schema:n.value,visitedSchemaIds:o,exampleId:t,example:r,depth:i,options:a,skipReadonly:s});return c!=null&&c.type==="array"&&c.value.length===0||c!=null&&c.type==="map"&&c.value.length===0||c!=null&&c.type==="object"&&Object.keys(c.properties).length===0?void 0:c}case"primitive":{let c=this.buildExampleFromPrimitive({schema:n.schema,example:r,options:a});return Al.primitive(c)}case"reference":{let c=this.schemas[n.schema];if(c!=null&&!o.has(n.schema)){o.add(n.schema);let l=c?.type==="object"&&!this.nonRequestReferencedSchemas.has(n.schema),u=this.buildExampleHelper({example:r,schema:c,exampleId:t,visitedSchemaIds:o,depth:i,options:a,skipReadonly:l||this.context.options.respectReadonlySchemas?s:!1});return o.delete(n.schema),u}return}case"oneOf":switch(n.value.type){case"discriminated":{let c={},l={},u={},p=rXr(r),d=p?.[n.value.discriminantProperty],m=n.value.schemas[d],h=[],y=this.getDiscriminatedUnionVariantSchema(n.value,p);y!=null&&h.push(y),h.push(...Object.entries(n.value.schemas));for(let g of h)if(d!=null&&m!=null&&m.type==="object"){l=this.getAllProperties(m),u=this.getAllRequiredProperties(m),c[n.value.discriminantProperty]=Al.primitive(Ga.string(d));break}else{let b=this.buildExampleHelper({exampleId:t,schema:g[1],example:void 0,visitedSchemaIds:o,depth:i,options:a,skipReadonly:s});if(b!=null){this.mergeExampleWith(b,c),c[n.value.discriminantProperty]=Al.primitive(Ga.string(g[0]));break}}for(let g of n.value.commonProperties){l[g.key]={schema:g.schema,readonly:!1};let b=this.getResolvedSchema(g.schema);b.type!=="optional"&&b.type!=="nullable"&&(u[g.key]=g.schema)}for(let[g,b]of Object.entries(l)){let _=g in u;if(_&&p?.[g]!=null){let O=this.buildExampleHelper({schema:b.schema,exampleId:t,example:p[g],visitedSchemaIds:o,depth:i+1,options:a,skipReadonly:s});if(O!=null)c[g]=O;else return}else{let O=this.buildExampleHelper({exampleId:t,schema:b.schema,example:p?.[g],visitedSchemaIds:o,depth:i+1,options:a,skipReadonly:s});if(O!=null)c[g]=O;else if(_)return}}return Al.oneOf(bgt.discriminated(c))}case"undiscriminated":{let c=this.getUnDiscriminatedUnionVariantSchema(n.value,r);if(c!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:c,visitedSchemaIds:o,depth:i,options:a,skipReadonly:s});break}}return;case"unknown":if(r!=null){let c=Tgt(r);if(c!=null)return Al.unknown(c)}return a.ignoreOptionals||this.exceedsMaxDepth(i,a)?void 0:a.isParameter?Al.primitive(Ga.string(a.name??"string")):Al.map([{key:Ga.string("key"),value:Al.primitive(Ga.string("value"))}]);case"array":{let c=PSl(r),l=[];if(c!=null&&c.length>0)for(let u of c){let p=this.buildExampleHelper({exampleId:t,example:u,schema:n.value,depth:i+1,visitedSchemaIds:o,options:a,skipReadonly:s});p!=null&&l.push(p)}else if(n.example!=null&&n.example.length>0)for(let u of n.example){let p=this.buildExampleHelper({exampleId:t,example:u,schema:n.value,depth:i+1,visitedSchemaIds:o,options:a,skipReadonly:s});p!=null&&l.push(p)}else{let u=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,depth:i+1,visitedSchemaIds:o,options:a,skipReadonly:s});u!=null&&l.push(u)}return Al.array(l)}case"map":{let c=rXr(r??n.example);if(c!=null&&Object.entries(c).length>0){let p=[];for(let[d,m]of Object.entries(c)){let h=this.buildExampleFromPrimitive({schema:n.key.schema,example:d,options:a}),y=this.buildExampleHelper({exampleId:t,example:m,schema:n.value,visitedSchemaIds:o,depth:i+1,options:a,skipReadonly:s});y!=null&&p.push({key:h,value:y})}return Al.map(p)}if(n.key.schema.type==="string"&&n.value.type==="unknown")return Al.map([{key:Ga.string("key"),value:Al.unknown(Al.primitive(Ga.string("value")))}]);let l=this.buildExampleFromPrimitive({schema:n.key.schema,example:void 0,options:{...a,name:"key"}}),u=this.buildExampleHelper({exampleId:t,example:void 0,schema:n.value,visitedSchemaIds:o,depth:i+1,options:{...a,name:"value"},skipReadonly:s});return u!=null&&u.type!=="null"?Al.map([{key:l,value:u}]):Al.map([])}case"object":{let c={},l=n.fullExamples?.find(m=>m.name===t)??n.fullExamples?.find(m=>m.name==null)??n.fullExamples?.[0],u=rXr(r)??(l!=null?rXr(l.value):{})??{},p=this.getAllProperties(n),d=this.getAllRequiredProperties(n);for(let[m,h]of Object.entries(p)){if(s&&h.readonly||h.schema._visit({optional:v=>typeof v.availability=="string"&&v.availability==="Deprecated",primitive:()=>!1,object:()=>!1,array:()=>!1,map:()=>!1,enum:()=>!1,reference:()=>!1,literal:()=>!1,oneOf:()=>!1,nullable:()=>!1,unknown:()=>!1,_other:()=>!1}))continue;let y=m in d,g=Object.keys(u).includes(m),b=u[m],_=this.getSchemaExample(h.schema),O=g?b:_,A=this.buildExampleHelper({schema:h.schema,exampleId:t,example:O,visitedSchemaIds:o,depth:i+1,options:{...a,name:m},skipReadonly:s});if(y&&A!=null)c[m]=A;else{if(y)return;(g&&A!=null||!a.ignoreOptionals&&A!=null)&&(c[m]=A)}}if(n.additionalProperties){for(let[m,h]of Object.entries(u))if(!(m in c)){let y=this.buildExampleHelper({schema:Bn.unknown({example:h,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0}),exampleId:t,example:h,visitedSchemaIds:o,depth:i+1,options:{...a,name:m},skipReadonly:s});y!=null&&(c[m]=y)}}return Al.object({properties:c})}default:qe(n)}}mergeExampleWith(t,r){t._visit({array:Rt,enum:Rt,literal:Rt,map:n=>{for(let i of n){let o=i.key;o.type==="string"&&(r[o.value]=i.value)}},object:n=>{for(let[i,o]of Object.entries(n.properties))r[i]=o},oneOf:n=>{if(n.type==="discriminated")for(let[i,o]of Object.entries(n.value))r[i]=o;else this.mergeExampleWith(n.value,r)},primitive:Rt,unknown:Rt,null:Rt,_other:Rt})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let n=r?.[t.discriminantProperty];if(n==null||typeof n!="string")return Object.entries(t.schemas)[0];let i=t.schemas[n];return i==null?Object.entries(t.schemas)[0]:[n,i]}getUnDiscriminatedUnionVariantSchema(t,r){if(r==null){let o=t.schemas.find(s=>this.hasExample(s,0,new Set,{ignoreOptionals:!1,isParameter:!1}));if(o!=null)return o;let a=t.schemas.find(s=>this.hasInherentExample(s));return a??t.schemas[0]}return t.schemas.map(o=>({schema:o,heuristic:this.calcExampleHeuristic(o,r)})).sort((o,a)=>a.heuristic-o.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return ESl({schema:t,value:r})?5:0;case"object":{if(!Hc(r))return 0;let n=this.getAllProperties(t),i=0;for(let[o,a]of Object.entries(n))r[o]!=null?(i++,i+=this.calcExampleHeuristic(a.schema,r[o])):i--;return i}case"array":{if(!Array.isArray(r))return 0;let n=0;for(let i of r)n+=this.calcExampleHeuristic(t.value,i);return n}case"map":{if(!Hc(r))return 0;let n=0;for(let[,i]of Object.entries(r))n+=this.calcExampleHeuristic(t.value,i);return n}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let n=this.getResolvedSchema(t);return n==null?0:this.calcExampleHeuristic(n,r)}case"oneOf":return Object.values(t.value.schemas).map(i=>this.calcExampleHeuristic(i,r)).sort((i,o)=>o-i)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,n=new Set,i){if(this.exceedsMaxCheckerDepth(r,i))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,n,i);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,n,i);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let a of t.properties)if(this.hasExample(a.schema,r+1,n,i))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let o=this.schemas[t.schema];if(o!=null&&!n.has(t.schema)){n.add(t.schema);let a=this.hasExample(o,r,n,i);return n.delete(t.schema),a}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(o=>this.hasExample(o,r,n,i));default:return!1}}hasInherentExample(t){switch(t.type){case"literal":return!0;case"enum":return t.values.length>0;case"optional":case"nullable":return this.hasInherentExample(t.value);case"reference":{let r=this.schemas[t.schema];return r!=null?this.hasInherentExample(r):!1}default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let n of t.properties)r[n.key]={schema:n.schema,readonly:n.readonly??!1};for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let o=this.getResolvedSchema(i);o.type==="object"&&(r={...this.getAllProperties(o),...r})}return r}getAllRequiredProperties(t){let r={};for(let n of t.properties){let i=this.getResolvedSchema(n.schema);i.type!=="optional"&&i.type!=="nullable"&&(r[n.key]=n.schema)}for(let n of t.allOf){let i=this.schemas[n.schema];if(i==null)continue;let o=this.getResolvedSchema(i);o.type==="object"&&(r={...this.getAllRequiredProperties(o),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}getSchemaExample(t){return t._visit({primitive:r=>r.schema.example,object:r=>r.fullExamples?.[0]?.value,array:r=>r.example,map:r=>r.example,optional:r=>this.getSchemaExample(r.value),enum:r=>r.example,reference:r=>{let n=this.schemas[r.schema];return n!=null?this.getSchemaExample(n):void 0},literal:()=>{},oneOf:()=>{},nullable:r=>this.getSchemaExample(r.value),unknown:r=>r.example,_other:()=>{}})}buildExampleFromPrimitive({example:t,schema:r,options:n}){switch(r.type){case"string":return t!=null&&typeof t=="string"?Ga.string(t):r.example!=null?Ga.string(r.example):Ga.string(n.name??Wo.STRING);case"base64":return t!=null&&typeof t=="string"?Ga.base64(t):r.example!=null?Ga.base64(r.example):Ga.base64(Wo.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?Ga.boolean(t):r.example!=null?Ga.boolean(r.example):Ga.boolean(Wo.BOOLEAN);case"date":return t!=null&&typeof t=="string"?Ga.date(t):r.example!=null?Ga.date(r.example):Ga.date(Wo.DATE);case"datetime":return t!=null&&typeof t=="string"?Ga.datetime(t):r.example!=null?Ga.datetime(r.example):Ga.datetime(Wo.DATE_TIME);case"double":return t!=null&&typeof t=="number"?Ga.double(t):r.example!=null?Ga.double(r.example):Ga.double(Wo.DOUBLE);case"float":return t!=null&&typeof t=="number"?Ga.float(t):r.example!=null?Ga.float(r.example):Ga.float(Wo.FLOAT);case"int":return t!=null&&typeof t=="number"?Ga.int(t):r.example!=null?Ga.int(r.example):Ga.int(Wo.INT);case"int64":return t!=null&&typeof t=="number"?Ga.int64(t):r.example!=null?Ga.int64(r.example):Ga.int64(Wo.INT64);case"uint":return t!=null&&typeof t=="number"?Ga.uint(t):r.example!=null?Ga.uint(r.example):Ga.uint(Wo.UINT);case"uint64":return t!=null&&typeof t=="number"?Ga.uint64(t):r.example!=null?Ga.uint64(r.example):Ga.uint64(Wo.UINT64);default:qe(r)}}};function ESl({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function Nxe(e){switch(e.type){case"object":return Bn.object({allOf:e.allOf,properties:e.properties.map(t=>RaA(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:void 0,minProperties:e.minProperties,maxProperties:e.maxProperties});case"array":return Bn.array({description:e.description,availability:e.availability,value:Nxe(e.value),generatedName:e.generatedName,title:e.title,namespace:e.namespace,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0,minItems:e.minItems,maxItems:e.maxItems});case"enum":return Bn.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,namespace:e.namespace,groupName:e.groupName,example:void 0,source:e.source,inline:void 0});case"literal":return Bn.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName});case"nullable":return Bn.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:Nxe(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return Bn.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:Nxe(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return Bn.primitive({description:e.description,availability:e.availability,schema:ISl(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Bn.map({description:e.description,availability:e.availability,key:Bn.primitive({description:e.key.description,availability:e.key.availability,schema:ISl(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:Nxe(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,example:void 0,inline:void 0,minProperties:e.minProperties,maxProperties:e.maxProperties});case"reference":return Bn.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,namespace:e.namespace,groupName:e.groupName,source:e.source});case"oneOf":return Bn.oneOf(TaA(e.value));case"unknown":return Bn.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:void 0,example:void 0,namespace:void 0,groupName:void 0,description:void 0,availability:void 0});default:qe(e)}}function TaA(e){switch(e.type){case"discriminated":return KJ.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:Nxe(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,discriminantPropertyNameOverride:e.discriminantPropertyNameOverride,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,Nxe(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return KJ.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>Nxe(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:qe(e)}}function ISl(e){switch(e.type){case"string":return Yo.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return Yo.base64({example:void 0});case"boolean":return Yo.boolean({default:e.default,example:void 0});case"date":return Yo.date({example:void 0});case"datetime":return Yo.datetime({example:void 0});case"double":return Yo.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return Yo.float({example:void 0});case"int":return Yo.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return Yo.int64({default:e.default,example:void 0});case"uint":return Yo.uint({default:void 0,example:void 0});case"uint64":return Yo.uint64({default:void 0,example:void 0});default:qe(e)}}function RaA(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:Nxe(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function KJn(e){return e.type!=="optional"&&e.type!=="nullable"}function kas(e){return e==="POST"||e==="PUT"||e==="PATCH"}function nXr(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var YJn=class{schemas;context;globalHeaders;exampleTypeFactory;logger;missingExamples=[];constructor(t,r,n){this.schemas=t,this.context=r,this.globalHeaders=n,this.schemas=t,this.exampleTypeFactory=new Rgt(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}addMissingExampleRecord(t,r,n,i,o={}){this.missingExamples.push({endpoint:t.path,method:t.method.toUpperCase(),type:r,schemaType:n,reason:i,operationSummary:t.summary,operationDescription:t.description,schemaDescription:o.schemaDescription,autoGeneratedExample:o.autoGeneratedExample})}writeMissingExamplesLog(){if(this.missingExamples.length===0)return;let t;if(this.context.source.type==="openapi"){let o=this.context.source.file,a=iLt.dirname(o),s=a;for(;s!==iLt.dirname(s);){let c=iLt.join(s,"fern");if(Nfr.existsSync(c)&&Nfr.statSync(c).isDirectory()){t=c;break}s=iLt.dirname(s)}t||(t=a)}else t=process.cwd();let r=t??process.cwd(),n=iLt.join(r,"schemas_missing_examples.txt"),i=["# Schemas Missing Examples Report",`# Generated on: ${new Date().toISOString()}`,`# Total missing examples: ${this.missingExamples.length}`,"",...this.missingExamples.flatMap(o=>{let a=[];if(a.push(`${o.method} ${o.endpoint} - ${o.type.toUpperCase()} (${o.schemaType}): ${o.reason}`),o.operationSummary&&a.push(` Operation: ${o.operationSummary}`),o.operationDescription&&o.operationDescription!==o.operationSummary&&a.push(` Description: ${o.operationDescription}`),o.schemaDescription&&a.push(` ${o.type==="request"?"Request":"Response"} Schema: ${o.schemaDescription}`),o.autoGeneratedExample){a.push(" Auto-generated example:");let c=JSON.stringify(o.autoGeneratedExample,null,4).split(`
|
|
1530
1530
|
`).map(l=>` ${l}`).join(`
|
|
1531
1531
|
`);a.push(c)}return a.push(""),a}),""].join(`
|
|
1532
|
-
`);try{Nfr.writeFileSync(n,i,"utf8"),this.logger.info(`Missing examples report written to: ${n}`)}catch(o){this.logger.warn(`Failed to write missing examples report to ${n}:`,String(o))}}finalize(){}convertExampleToJson(t){switch(t.type){case"primitive":return t.value;case"array":return t.value.map(r=>this.convertExampleToJson(r));case"object":{let r={};return Object.entries(t.properties).forEach(([n,i])=>{r[n]=this.convertExampleToJson(i)}),r}case"map":{let r={};return t.value.forEach(n=>{r[String(n.key)]=this.convertExampleToJson(n.value)}),r}case"oneOf":if(t.value.type==="undiscriminated")return this.convertExampleToJson(t.value.value);{let r={};return Object.entries(t.value.value).forEach(([n,i])=>{r[n]=this.convertExampleToJson(i)}),r}case"enum":return t.value;case"literal":return t.value;case"null":return null;case"unknown":return this.convertExampleToJson(t.value);default:return t}}getSchemaDescription(t){if("description"in t)return t.description}getSchemaTypeName(t){switch(t.type){case"primitive":return`primitive (${t.schema.type})`;case"object":return t.generatedName||"object";case"array":return"array";case"map":return"map";case"optional":return`optional (${this.getSchemaTypeName(t.value)})`;case"nullable":return`nullable (${this.getSchemaTypeName(t.value)})`;case"reference":return t.generatedName||"reference";case"enum":return t.generatedName||"enum";case"literal":return"literal";case"oneOf":return"oneOf";case"unknown":return"unknown";default:return"unknown"}}buildEndpointExample(t){let r=NaA(t.request),n=MaA(t.response);if(r?.type==="unsupported"||n?.type==="unsupported")return[];let i=[];if(r!=null&&r.type==="present"){let p=this.isSchemaRequired(r.schema);if(r.examples.length===0){let d=this.exampleTypeFactory.buildExample({skipReadonly:kas(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});d!=null?(i.push([void 0,d]),this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(r.schema),autoGeneratedExample:this.convertExampleToJson(d)})):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(r.schema)})}else for(let{name:d,value:m}of r.examples){let h=this.exampleTypeFactory.buildExample({skipReadonly:kas(t.method),schema:r.schema,exampleId:d,example:m,options:{isParameter:!1,ignoreOptionals:!0}});h!=null?i.push([d,h]):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),`Failed to build example from provided data (example id: ${d})`,{schemaDescription:this.getSchemaDescription(r.schema)})}if(p&&i.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let o=[];if(n!=null&&n.type==="present"){let p=this.isSchemaRequired(n.schema);if(n.examples.length===0){let d=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});d!=null?(t.response?.type==="json"?o.push([void 0,nre.withoutStreaming(d)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,nre.withStreaming({sse:t.response?.type==="streamingSse",events:[d]})]),this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(n.schema),autoGeneratedExample:this.convertExampleToJson(d)})):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(n.schema)})}else for(let{name:d,value:m}of n.examples){let h=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:d,example:m,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});h!=null?t.response?.type==="json"?o.push([d,nre.withoutStreaming(h)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,nre.withStreaming({sse:t.response?.type==="streamingSse",events:[h]})]):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),`Failed to build example from provided data (example id: ${d})`,{schemaDescription:this.getSchemaDescription(n.schema)})}if(p&&o.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];for(let p of t.pathParameters){let d=this.isSchemaRequired(p.schema),m=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(m!=null&&!Mxe(m)&&(this.logger.debug(`Expected a primitive example but got ${m.type} for path parameter ${p.name} for ${t.method.toUpperCase()} ${t.path}`),m=void 0),d&&m==null)return[];m!=null&&a.push({name:p.name,parameterNameOverride:p.parameterNameOverride,value:m})}let s=[];for(let p of t.queryParameters){let d=this.isSchemaRequired(p.schema),m=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(m!=null&&!Mxe(m)&&(this.logger.debug(`Expected a primitive example but got ${m.type} for query parameter ${p.name} for ${t.method.toUpperCase()} ${t.path}`),m=void 0),d&&m==null)return[];m!=null&&s.push({name:p.name,value:m})}let c=[];for(let p of t.headers){let d=this.isSchemaRequired(p.schema),m=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(m!=null&&!Mxe(m)&&(this.logger.debug(`Expected a primitive example but got ${m.type} for header ${p.name} for ${t.method.toUpperCase()} ${t.path}`),m=void 0),d&&m==null)return[];m!=null&&c.push({name:p.name,value:m})}for(let p of this.globalHeaders){let d=p.schema!=null?Nxe(p.schema):Bn.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:Yo.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),m=this.exampleTypeFactory.buildExample({schema:d,exampleId:void 0,example:void 0,options:{name:p.header,isParameter:!0,ignoreOptionals:!0}});if(m!=null&&!Mxe(m)&&(this.logger.debug(`Expected a primitive example but got ${m.type} for global header ${p.header} for ${t.method.toUpperCase()} ${t.path}`),m=void 0),m==null)return[];m!=null&&c.push({name:p.header,value:m})}let l=[];t.request!=null&&t.response!=null?l=FaA(i,o):t.request!=null?l=i.map(([p,d])=>({id:p,request:d,response:void 0})):t.response!=null&&(l=o.map(([p,d])=>({id:p,request:void 0,response:d})));let u=t.examples.filter(p=>nXr(p)).flatMap(p=>{if(p.type==="unknown"){if(p.value!=null){let d=p.value["code-samples"];if(d!=null)return this.convertCodeSamples(d)}return}else return p.codeSamples}).filter(p=>Gu(p));return l.length===0?[rre.full({name:void 0,description:void 0,pathParameters:a,queryParameters:s,headers:c,request:void 0,response:void 0,codeSamples:u})]:l.map(({id:p,request:d,response:m})=>rre.full({name:p,description:void 0,pathParameters:a,queryParameters:s,headers:c,request:d,response:m,codeSamples:u}))}convertCodeSamples(t){return t.map(r=>"language"in r?bMe.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):bMe.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?SR.Csharp:r.sdk,code:r.code})).filter(Gu)}isSchemaRequired(t){return KJn(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function FaA(e,t){let r=[];if(e.length<=1){let[i,o]=e[0]??[];if(t.length===0)return r.push({id:i,request:o,response:void 0}),r;for(let[a,s]of t)r.push({id:a??i,request:o,response:s});return r}if(t.length<=1){let[i,o]=t[0]??[];if(t.length===0)return r.push({id:i,request:void 0,response:o}),r;for(let[a,s]of e)r.push({id:a??i,request:s,response:o});return r}let n=new Set;for(let[i,o]of e){let a=t.find(([c])=>c==null)?.[1]??t[0]?.[1];if(i==null){if(a==null)continue;r.push({id:void 0,request:o,response:a});continue}let s=!1;for(let c=0;c<t.length;c++){let[l,u]=t[c];l==null||n.has(c)||i===l&&(r.push({id:i,request:o,response:u}),l!=null&&n.add(c),s=!0)}!s&&a!=null&&r.push({id:i,request:o,response:a})}for(let i=0;i<t.length;i++){if(n.has(i))continue;let[o,a]=t[i],s=e.find(([c])=>c==null)?.[1]??e[0]?.[1];s!=null&&r.push({id:o,request:s,response:a})}return r}function NaA(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:zaA(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function MaA(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function Mxe(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return Mxe(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return Mxe(e.value.value);default:return!1}case"null":return!0;default:qe(e)}}function zaA(e){return Bn.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:Nxe(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(Gu),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source,inline:void 0,minProperties:void 0,maxProperties:void 0})}var Mfr=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new Rgt(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:n,source:i,namespace:o}){let a=[];for(let s of r){let c=[];for(let p of n.queryParameters){let d=this.isSchemaRequired(p.schema),m=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:s.queryParameters?.[p.name],options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!Mxe(m)&&(m=void 0),!(d&&m==null)&&m!=null&&c.push({name:p.name,value:m})}let l=[];for(let p of n.headers){let d=this.isSchemaRequired(p.schema),m=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:s.headers?.[p.name],options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!Mxe(m)&&(m=void 0),!(d&&m==null)&&m!=null&&l.push({name:p.name,value:m})}let u=[];for(let p of s.messages){let d=t.getExampleMessageReference(p),m=t.resolveMessageReference({$ref:d}),h=fo(m.payload)?t.resolveSchemaReference(m.payload):m.payload,y=this.exampleTypeFactory.buildExample({schema:El(h,!1,!1,t,[p.messageId],i,o),exampleId:void 0,example:p.value,options:{isParameter:!1,ignoreOptionals:!0}});y!=null&&u.push({messageType:p.type,payload:y,description:void 0})}a.push({name:s.summary,queryParameters:c,headers:l,description:s.description,messages:u})}return a}buildWebsocketSessionExample({handshake:t,messages:r}){let n={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},i=[];for(let a of t.queryParameters){let s=this.isSchemaRequired(a.schema),c=this.exampleTypeFactory.buildExample({schema:a.schema,exampleId:void 0,example:void 0,options:{name:a.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!Mxe(c)&&(c=void 0),s&&c==null)return;c!=null&&i.push({name:a.name,value:c})}let o=[];for(let a of t.headers){let s=this.isSchemaRequired(a.schema),c=this.exampleTypeFactory.buildExample({schema:a.schema,exampleId:void 0,example:void 0,options:{name:a.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!Mxe(c)&&(c=void 0),s&&c==null)return;c!=null&&o.push({name:a.name,value:c})}for(let a of r){let s=this.exampleTypeFactory.buildExample({schema:a.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});s!=null&&n.messages.push({messageType:a.type,payload:s,description:void 0})}return n}isSchemaRequired(t){return KJn(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var uz={FERN_PARAMETER_OPTIONAL:"x-fern-optional",FERN_CHANNEL_ADDRESS:"x-fern-address",FERN_DISPLAY_NAME:"x-fern-display-name",FERN_SDK_GROUP_NAME:"x-fern-sdk-group-name",FERN_SDK_METHOD_NAME:"x-fern-sdk-method-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore",FERN_PARAMETER_NAME:"x-fern-parameter-name"};function XJn(e){return ni(e,uz.FERN_EXAMPLES)??[]}function ZJn(e,t){return t.includes("://")?t:`${e}://${t}`}function eKn(e){return e.startsWith("/")?e:"/"+e}function CSl({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let o={},a={};for(let[l,u]of Object.entries(i.components?.schemas??{})){let p=El(u,!1,!1,e,[l],r,e.namespace);o[l]=p}let s=new Mfr(o,e),c={};for(let[l,u]of Object.entries(i.servers??{}))c[l]={name:l,url:ZJn(u.protocol,u.url)};for(let[l,u]of Object.entries(i.channels??{})){let p=ni(u,uz.IGNORE);if(p!=null&&p){e.logger.debug(`Channel ${l} is marked with x-fern-ignore. Skipping.`);continue}let d=[];if(u.parameters!=null)for(let[b,_]of Object.entries(u.parameters??{})){let O=ni(_,uz.FERN_PARAMETER_NAME);d.push({name:b,description:_.description,parameterNameOverride:O,schema:_.schema!=null?El(_.schema,!1,!1,e,t,r,e.namespace):Bn.primitive({schema:Yo.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:rq(_),source:r,explode:void 0})}let m=[],h=[];if(u.bindings?.ws!=null){if(u.bindings.ws.headers!=null){let b=u.bindings.ws.headers.required??[];for(let[_,O]of Object.entries(u.bindings.ws.headers.properties??{})){if(fo(O)){let I=e.resolveSchemaReference(O),E=b.includes(_),[x,T]=e.options.coerceOptionalSchemasToNullable?[!1,!E]:[!E,!1];m.push({name:_,schema:sat(O,x,T,e,t,void 0,r,e.namespace),description:I.description,parameterNameOverride:void 0,env:void 0,availability:rq(I),source:r});continue}let A=b.includes(_),[v,P]=e.options.coerceOptionalSchemasToNullable?[!1,!A]:[!A,!1];m.push({name:_,schema:El(O,v,P,e,[...t,_],r,e.namespace),description:O.description,parameterNameOverride:void 0,env:void 0,availability:rq(O),source:r})}}if(u.bindings.ws.query!=null){let b=u.bindings.ws.query.required??[];for(let[_,O]of Object.entries(u.bindings.ws.query.properties??{})){if(fo(O)){let I=e.resolveSchemaReference(O),E=b.includes(_),[x,T]=e.options.coerceOptionalSchemasToNullable?[!1,!E]:[!E,!1];h.push({name:_,schema:sat(O,x,T,e,t,void 0,r,e.namespace),description:I.description,parameterNameOverride:void 0,availability:rq(I),source:r,explode:void 0});continue}let A=b.includes(_),[v,P]=e.options.coerceOptionalSchemasToNullable?[!1,!A]:[!A,!1];h.push({name:_,schema:El(O,v,P,e,[...t,_],r,e.namespace),description:O.description,parameterNameOverride:void 0,availability:rq(O),source:r,explode:void 0})}}}let y;u.publish!=null&&("oneOf"in u.publish.message?y=xSl({generatedName:u.publish.operationId??"PublishEvent",event:u.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):y=jSl({action:"Publish",channelPath:l,message:u.publish.message,context:e,source:r}));let g;if(u.subscribe!=null&&("oneOf"in u.subscribe.message?g=xSl({generatedName:u.subscribe.operationId??"SubscribeEvent",event:u.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):g=jSl({action:"Subscribe",channelPath:l,message:u.subscribe.message,context:e,source:r})),m.length>0||h.length>0||y!=null||g!=null){let b=XJn(u),_=[];if(b.length>0)_=s.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:b,handshake:{headers:m,queryParameters:h},source:r,namespace:e.namespace});else{let P=[];y!=null&&P.push({type:"publish",payload:y}),g!=null&&P.push({type:"subscribe",payload:g});let I=s.buildWebsocketSessionExample({handshake:{headers:m,queryParameters:h},messages:P});I!=null&&_.push(I)}let O=ni(u,uz.FERN_CHANNEL_ADDRESS),A=O??eKn(l),v=[];y!=null&&v.push({origin:"client",name:"publish",body:MA(y),methodName:void 0}),g!=null&&v.push({origin:"server",name:"subscribe",body:MA(g),methodName:void 0}),a[l]={audiences:ni(u,wi.AUDIENCES)??[],handshake:{headers:m.map(P=>({...P,schema:MA(P.schema),env:P.env})),queryParameters:h.map(P=>({...P,schema:MA(P.schema)})),pathParameters:d.map(P=>({...P,schema:MA(P.schema)}))},groupName:e.resolveGroupName([ni(u,uz.FERN_SDK_GROUP_NAME)??l]),messages:v,servers:(u.servers?.map(P=>c[P])??Object.values(c)).filter(P=>P!=null&&P.name!=null).map(P=>({...P,name:P.name})),summary:ni(u,uz.FERN_DISPLAY_NAME),path:A,description:u.description,examples:_,source:r}}}return{groupedSchemas:Ffr(e.namespace,o),channels:a??void 0,servers:Object.values(c).map(l=>({...l,name:l.name})),basePath:ni(i,uz.BASE_PATH)}}function xSl({generatedName:e,event:t,context:r,breadcrumbs:n,source:i,options:o,asyncApiOptions:a}){if("oneOf"in t.message&&t.message.oneOf!=null){let s=[],c=[];for(let l of t.message.oneOf){let u,p={type:"notFound"};if(fo(l)){let d=r.resolveMessageReference(l);!fo(d.payload)&&a.naming==="v2"?(p=d.name?{type:"name",name:d.name}:p,u={...d.payload,title:d.name??d.payload.title,description:d.name??d.payload.description}):u=d.payload}else u=l;c.push(p),s.push(u)}return Dgt({description:t.description??t.message.description,availability:rq(t.message),subtypes:s,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsOptional:!1,wrapAsNullable:!1,breadcrumbs:n,context:r,encoding:void 0,source:i,namespace:r.namespace,subtypeSuffixOverrides:a.naming==="v2"?c:[]})}}function jSl({action:e,channelPath:t,message:r,context:n,source:i}){if(r.payload!=null){let o=r.payload;return fo(r.payload)&&(o=n.resolveSchemaReference(r.payload)),El(o,!1,!1,n,[t,e],i,n.namespace)}}var tKn=class extends Rfr{getExampleMessageReference(t){return`#/channels/${t.channelId}/messages/${t.messageId}`}resolveParameterReference(t){let r="#/components/parameters/";if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve ${t.$ref}`);let n=t.$ref.substring(r.length),i=this.document.components.parameters[n];if(i==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in i?this.resolveParameterReference(i):i}resolveMessageReference(t,r=!1){let n="#/channels/",i="#/components/messages/";if(t==null)throw new Error("Cannot resolve message reference: message is null or undefined");if(!t.$ref)throw new Error("Cannot resolve message reference: message.$ref is undefined or empty");if(t.$ref.startsWith(n)){let c=t.$ref.split("/"),l=c[2],u=c[4],p=l?.replace(/~1/g,"/").replace(/~0/g,"~");if(p==null||u==null||!this.document.channels?.[p])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${p}`);let m=this.document.channels[p].messages?.[u];if(m==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in m&&!r?this.resolveMessageReference(m):{...m,name:u}}let o=this.document.components;if(!t.$ref.startsWith(i)||!o?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let a=t.$ref.substring(i.length),s=o.messages[a];if(s==null)throw new Error(`${t.$ref} is undefined`);return{...s,name:a}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}};var SSl="#/channels/",BSl="#/servers/",Uas="$message.";function TSl({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){$Jn();let o={},a={},s={},c=[],l={};e.logger.debug("Parsing V3 AsyncAPI...");let u=IMe();for(let[I,E]of Object.entries(i.components?.schemas??{})){let x=u.getUniqueSchemaId(I,e.logger,e.options.resolveSchemaCollisions);o[x]=El(E,!1,!1,e,[x],r,e.namespace)}for(let[I,E]of Object.entries(i.channels??{}))if(a[I]||(a[I]={}),E.messages)for(let[x,T]of Object.entries(E.messages))if(s[x]||(s[x]=[]),e.isReferenceObject(T)){let W=e.resolveMessageReference(T);s[x].push({channelId:I,payload:W.payload})}else e.isMessageWithPayload(T)&&s[x].push({channelId:I,payload:T.payload});for(let[I,E]of Object.entries(s))if(E.length===1){let x=E[0],T=x.channelId;a[T]=a[T]||{},a[T][I]=El(x.payload,!1,!1,e,[I],r,e.namespace)}else{c.push(I);for(let{channelId:x,payload:T}of E){let W=`${x}_${I}`;a[x]||(a[x]={}),a[x][W]=El(T,!1,!1,e,[W],r,e.namespace)}}let p={},d=IMe();for(let[I,E]of Object.entries(a))for(let[x,T]of Object.entries(E)){let W=d.getUniqueSchemaId(x,e.logger,e.options.resolveSchemaCollisions);p[W]=T}let m=new Mfr({...o,...p},e),h={};for(let[I,E]of Object.entries(i.servers??{}))h[I]={name:I,url:ZJn(E.protocol,E.host)};let y={},g=Object.keys(i.channels??{});for(let[I,E]of Object.entries(i.operations??{})){if(ni(E,uz.IGNORE))continue;let x;if(E.channel==null||!("$ref"in E.channel)||E.channel.$ref==null)if(g.length===1&&g[0]!=null)x=g[0];else continue;else x=qaA(E);y[x]||(y[x]={subscribe:[],publish:[],__parsedMessages:[]});let T=ni(E,uz.FERN_SDK_METHOD_NAME);if(!E.messages||!Array.isArray(E.messages))continue;let W=E.messages.filter(G=>G!=null&&G.$ref!=null).map(G=>({ref:G,methodName:T})),H=y[x];if(H==null)throw new Error(`Internal error: channelEvents["${x}"] is unexpectedly undefined for operation ${I}`);if(E.action==="receive")H.subscribe.push(...W);else if(E.action==="send")H.publish.push(...W);else throw new Error(`Operation ${I} has an invalid action: ${E.action}`)}for(let[I,E]of Object.entries(y)){let x=[];x.push(...DSl({messages:E.subscribe,channelPath:I,origin:"server",messageSchemas:a[I]??{},duplicatedMessageIds:c,context:e})),x.push(...DSl({messages:E.publish,channelPath:I,origin:"client",messageSchemas:a[I]??{},duplicatedMessageIds:c,context:e})),y[I]!=null&&(y[I].__parsedMessages=x)}for(let[I,E]of Object.entries(i.channels??{})){if(ni(E,uz.IGNORE))continue;let x=[],T=[],W=[];if(E.parameters!=null)for(let[H,G]of Object.entries(E.parameters)){let ie=e.isReferenceObject(G)?e.resolveParameterReference(G):G,{type:oe,parameterKey:$}=ie.location!=null?VaA(ie.location):{type:E.address?.includes(`={${H}}`)?"query":"path",parameterKey:H},te=ni(ie,uz.FERN_PARAMETER_OPTIONAL),Ge=Xd(Xi(I))+Xd(Xi(H)),Ke={...ie,type:"string",title:Ge,example:ie.examples?.[0],default:ie.default,enum:ie.enum,required:void 0},Z=El(Ke,!1,!1,e,[$],r,e.namespace);te&&(Z=Bn.optional({value:Z,description:void 0,availability:void 0,generatedName:"",title:Ge,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}));let Y={name:$,description:ie.description,parameterNameOverride:void 0,schema:Z,variableReference:void 0,availability:rq(G),source:r,explode:void 0};oe==="header"?x.push({...Y,env:void 0}):oe==="path"?T.push(Y):(oe==="payload"||oe==="query")&&W.push(Y)}if(x.length>0||W.length>0||y[I]!=null&&(y[I].publish!=null||y[I].subscribe!=null)){let H=XJn(E),G=y[I]?.__parsedMessages??[],ie=[];if(H.length>0)ie=m.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:H,handshake:{headers:x,queryParameters:W},source:r,namespace:e.namespace});else{let Ge=[],{examplePublishMessage:Ke,exampleSubscribeMessage:Z}=UaA({messages:G,messageSchemas:a[I]??{}});Ke!=null&&Ge.push(Ke),Z!=null&&Ge.push(Z);let Y=m.buildWebsocketSessionExample({handshake:{headers:x,queryParameters:W},messages:Ge});Y!=null&&ie.push(Y)}let oe=ni(E,uz.FERN_SDK_GROUP_NAME),$=(E.servers?.map(Ge=>kaA(h,Ge))??Object.values(h)).map(Ge=>({...Ge,name:Ge.name})),te=E.address?.split("?")[0]??eKn(I);l[I]={audiences:ni(E,wi.AUDIENCES)??[],handshake:{headers:x.map(Ge=>({...Ge,schema:MA(Ge.schema),env:Ge.env})),queryParameters:W.map(Ge=>({...Ge,schema:MA(Ge.schema)})),pathParameters:T.map(Ge=>({...Ge,parameterNameOverride:void 0,schema:MA(Ge.schema)}))},groupName:e.resolveGroupName(typeof oe=="string"?[oe]:oe??[I]),messages:G,summary:ni(E,uz.FERN_DISPLAY_NAME),servers:$,path:te,description:E.description,examples:ie,source:r}}else e.logger.warn(`Skipping AsyncAPI channel ${I} as it does not qualify for inclusion (no headers, query params, or operations)`)}let b={...o,...p},_={},O=IMe();for(let[I,E]of Object.entries(b)){let x=O.getUniqueSchemaId(I,e.logger,e.options.resolveSchemaCollisions);_[x]=MA(E)}let A=Ffr(e.namespace,o),v=Object.values(h).map(I=>({...I,name:I.name})),P=ni(i,uz.BASE_PATH);return{groupedSchemas:A,channels:l,servers:v,basePath:P}}function QaA(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function qaA(e){if(!e.channel)throw new Error("Operation is missing required 'channel' field");if(!e.channel.$ref)throw new Error("Operation channel is missing required '$ref' field");if(!e.channel.$ref.startsWith(SSl))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return QaA(e.channel.$ref.substring(SSl.length))}function VaA(e){try{let[t,r]=e.split("#/");if(t==null||r==null)throw new Error(`Invalid location format: ${e}; unable to parse message type and parameter key`);if(!t.startsWith(Uas))throw new Error(`Invalid location format: ${e}; expected ${Uas} prefix`);let n=t.substring(Uas.length);if(n!=="header"&&n!=="path"&&n!=="payload")throw new Error(`Invalid message type: ${n}. Must be one of: header, path, payload`);return{type:n,parameterKey:r}}catch{throw new Error(`Invalid location format: ${e}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`)}}function kaA(e,t){if(!t.$ref.startsWith(BSl))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(BSl.length),n=e[r];if(n==null)throw new Error(`Failed to find server with name ${r}`);return n}function DSl({messages:e,channelPath:t,origin:r,messageSchemas:n,duplicatedMessageIds:i,context:o}){let a=[];return e.forEach((s,c)=>{let u=o.resolveMessageReference(s.ref,!0).name;i.includes(u)&&(u=`${t}_${u}`);let p=n[u];p!=null&&a.push({origin:r,name:u??`${r}Message${c+1}`,body:MA(p),methodName:s.methodName})}),a}function UaA({messages:e,messageSchemas:t}){let r=e.find(a=>a.origin==="client")?.name,n=e.find(a=>a.origin==="server")?.name,i=r!=null?t[r]:void 0,o=n!=null?t[n]:void 0;return{examplePublishMessage:i!=null&&r!=null?{type:r,payload:i}:void 0,exampleSubscribeMessage:o!=null&&n!=null?{type:n,payload:o}:void 0}}function RSl({document:e,taskContext:t,options:r,source:n,asyncApiOptions:i,namespace:o}){let a=[];if(o!=null&&a.push(o),parseFloat(e.asyncapi)<3){let s=e;s.tags?.[0]!=null?a.push(s.tags[0].name):i.naming!=="v2"&&a.push("websocket");let c=new JJn({document:s,taskContext:t,options:r,namespace:o});return CSl({context:c,breadcrumbs:a,source:n,asyncApiOptions:i,document:s})}else{let s=e,c=new tKn({document:s,taskContext:t,options:r,namespace:o});return TSl({context:c,breadcrumbs:a,source:n,asyncApiOptions:i,document:s})}}function FSl(e){return ni(e,wi.ASYNC_CONFIG)}var NSl="$request.";function MSl(e){let t=ni(e,wi.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:LaA(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function LaA(e){return e.startsWith(NSl)?e.slice(NSl.length):e}function zSl(e){let t=e;if(t.cursor!=null)return MT.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;if("next_uri"in r)return MT.uri({nextUri:r.next_uri,results:r.results});let n=e;if("next_path"in n)return MT.path({nextPath:n.next_path,results:n.results});if("offset"in e){let i=e;return MT.offset({offset:i.offset,results:i.results,step:i.step,hasNextPage:i["has-next-page"]})}if("type"in e&&e.type==="custom"){let i=e;return MT.custom({results:i.results})}throw new Error("Invalid pagination extension")}function QSl(e,t){let r=ni(t,wi.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=ni(e,wi.PAGINATION);if(typeof n=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return n==null?void 0:zSl(n)}return zSl(r)}}function qSl(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let n=e[r];if(n==null)continue;let i=n,o=n.schema??i.itemSchema;return{contentType:r,schema:o??{},examples:zfr(n,t)}}}function VSl(e){for(let t of Object.keys(e))if(t.includes("text/event-stream")){let r=e[t];if(r==null)continue;if(r.itemSchema!=null)return!0}return!1}function WaA(e){return e.includes("json")||e==="*/*"}function Las({content:e,context:t}){for(let[r,n]of Object.entries(e))if(rKn({mediaType:r,mediaTypeObject:n,context:t})!=null)return[r,n]}function rKn({mediaType:e,mediaTypeObject:t,context:r}){if(!WaA(e))return;let n=t.schema;return{contentType:e.includes("*")?void 0:e,schema:n??{},examples:zfr(t,r)}}function nKn({content:e,context:t}){let r=Las({content:e,context:t});if(!r)return;let[n,i]=r;return rKn({mediaType:n,mediaTypeObject:i,context:t})}function kSl(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:zfr(n,t)}}}function zfr(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=ni(e,sz.EXAMPLES);return n!=null&&Object.keys(n).length>0&&r.push(...Object.entries(n).map(([i,o])=>({name:o.summary??i,value:o.value,description:o.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([i,o])=>{let a=fo(o)?t.resolveExampleReference(o):o;return{name:a.summary??i,value:a.value,description:a.description}})),r}function USl(e){let t=GaA(e),r={};return Was({obj:t,occurrences:r,breadcrumbs:[]}),r}function Was({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)Was({obj:n,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let n=e.$ref;t[n]==null?t[n]=1:t[n]+=1;return}for(let n in e)Was({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function GaA(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?iXr(r.get):void 0,put:r?.put!=null?iXr(r.put):void 0,post:r?.post!=null?iXr(r.post):void 0,patch:r?.patch!=null?iXr(r.patch):void 0,delete:r?.delete!=null?iXr(r.delete):void 0}]))}}function iXr(e){return{...e,requestBody:e.requestBody!=null?fo(e.requestBody)?e.requestBody:HaA(e.requestBody):void 0}}function HaA(e){let t,r;for(let n in e.content){let i=SA.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[SA.MULTIPART_FORM_DATA]:r}}:e}var iKn=class{endpoints;parser=new Vot;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let n=[];for(let i of r){let o=this.parser.tryParse(i);if(o==null){t.logger.debug(`Ignoring configured filter endpoint "${i}"; expected format "POST /users/get"`);continue}n.push(`${o.method} ${o.path}`)}return n}};var LSl="#/components/parameters/",WSl="#/components/responses/",GSl="#/components/examples/",HSl="#/components/requestBodies/",$Sl="#/components/securitySchemes/",Qfr=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;schemaNamespaceMapping;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:a}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=n,this.refOccurrences=USl(t),this.options=i,this.source=o,this.filter=new iKn({context:r,options:i}),this.DUMMY=this.getDummy(),this.namespace=a,this.schemaNamespaceMapping=this.buildSchemaNamespaceMapping()}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};r.push(n)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return{"x-fern-type":"unknown"};if(Array.isArray(n)){let o=parseInt(i,10);if(isNaN(o)||o<0||o>=n.length)return{"x-fern-type":"unknown"};n=n[o]}else n=n[i]}return n==null?(this.logger.debug(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(fo(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(LSl))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(LSl.length),n=this.document.components.parameters[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return fo(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(HSl))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(HSl.length),n=this.document.components.requestBodies[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return fo(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(WSl))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(WSl.length),n=this.document.components.responses[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return fo(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(GSl))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(GSl.length),n=this.document.components.examples[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return fo(n)?this.resolveExampleReference(n):n}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith($Sl))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring($Sl.length),n=this.document.components.securitySchemes[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return fo(n)?this.resolveSecuritySchemeReference(n):n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}getNamespace(t){return this.schemaNamespaceMapping?.get(t)}buildSchemaNamespaceMapping(){let t=new Map;if(!this.document.components?.schemas)return t;for(let[r,n]of Object.entries(this.document.components.schemas))!n||fo(n)||t.set(r,ni(n,wi.SDK_NAMESPACE)||this.namespace);return t}};var oLt=class extends Qfr{constructor({document:t,taskContext:r,options:n,source:i,namespace:o}){super({document:t,taskContext:r,authHeaders:new Set,options:n,source:i,namespace:o})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,n){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,n){}getDiscriminatedUnionMetadata(t){}};var oKn=require("fs"),aKn=require("path");var $aA=Lt.object({lang:Lt.string(),label:Lt.optional(Lt.string()),source:Lt.string()}),Gas=Lt.array($aA);var JSl={README_EXT:"x-readme"};function JaA(e){if(!Array.isArray(e))return!1;for(let t of e)if(!Hc(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function KSl(e){let t=ni(e,JSl.README_EXT);if(!Hc(t))return[];let r=t["code-samples"];if(!JaA(r))return[];let n=[];for(let i of r)n.push({name:i.name,language:i.language,code:i.code,install:i.install,docs:void 0});return n}function KaA(e){return Hc(e)&&typeof e.$ref=="string"}function YaA(e,t){if(e!=null){if(typeof e=="string")return e;if(KaA(e)){let r=(0,aKn.resolve)(t??process.cwd(),e.$ref);if((0,oKn.existsSync)(r))try{return(0,oKn.readFileSync)(r,"utf-8")}catch{return}}}}function XaA(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!Hc(n))continue;let o=YaA(n.code,t);o!=null&&r.push({...n,code:o})}return r}function YSl(e,t,r){let n=ni(t,wi.EXAMPLES),i=r.source.type==="openapi"?(0,aKn.dirname)(r.source.file):void 0,a=(n??[]).map(p=>{if(!Hc(p))return p;let m=p["code-samples"];if(m!=null){let h=XaA(m,i);return{...p,"code-samples":h}}return p}).filter(p=>{let d=zj.serialization.ExampleEndpointCallSchema.parse(p);return d.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),d.ok}),s=XYr(t,sz.REDOCLY_CODE_SAMPLES_KEBAB,Gas,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],l=[...XYr(t,sz.REDOCLY_CODE_SAMPLES_CAMEL,Gas,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...s];l.length>0&&a.push({"code-samples":l.map(p=>({name:p.label??p.lang,language:p.lang,code:p.source,install:void 0,docs:void 0}))});let u=KSl(t);return u.length>0&&a.push({"code-samples":u}),a.map(rre.unknown)}function XSl(e){let t=ni(e,wi.AVAILABILITY);if(t==="ga"||t==="generally-available")return jR.GenerallyAvailable;if(t==="beta"||t==="pre-release")return jR.Beta;if(t==="deprecated")return jR.Deprecated;if(e.deprecated)return jR.Deprecated}function ZSl(e){let t=ni(e,wi.RETRIES);if(t!=null&&t.disabled===!0)return _Hn.RetriesConfiguration.disabled(t.disabled)}var ZaA="x-fern-default-url";function sKn(e,t){let r=e.variables!=null&&Object.keys(e.variables).length>0,n=esA(e);return{url:rsA({url:e.url,variables:e.variables??{}}),description:e.description,name:nsA(e,t),audiences:ni(e,wi.AUDIENCES),urlTemplate:r?e.url:void 0,variables:r&&e.variables!=null?tsA(e.variables):void 0,defaultUrl:r?n:void 0}}function esA(e){let t=e[ZaA];if(typeof t=="string")return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}function tsA(e){return Object.entries(e).map(([t,r])=>({id:t,default:r.default,values:r.enum}))}function rsA({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([n,i])=>[n,i.default]));for(let[n,i]of Object.entries(r))e=e.replace(`{${n}}`,encodeURIComponent(i));return e}function nsA(e,t){let r=ni(e,[wi.SERVER_NAME_V1,wi.SERVER_NAME_V2]);if(r!=null)return r;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox";if(t?.groupMultiApiEnvironments&&e.description!=null&&e.description.trim()!==""){let n=e.description.toLowerCase();return n==="prd"?"Production":n==="sbx"?"Sandbox":n==="staging"||n==="stg"?"Staging":n==="development"||n==="dev"?"Development":e.description}}function eBl(e){return ni(e,wi.PARAMETER_NAME)}function tBl(e){return ni(e,wi.SDK_VARIABLE)}function uKn({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:o}){let a={pathParameters:[],queryParameters:[],headers:[]};for(let s of r){let c=ni(s,wi.IGNORE);if(c!=null&&c){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let l=fo(s)?n.resolveParameterReference(s):s,u=l.required??!1,p=rq(l),d=[...i,l.name],m=HC(d,n.options.preserveSchemaIds),[h,y]=n.options.coerceOptionalSchemasToNullable?[!1,!u]:[!u,!1],g=l.schema!=null?El(l.schema,h,y,n,d,o,n.namespace,!1,new Set,xMe({schema:l,logger:n.logger})):u?Bn.primitive({nameOverride:void 0,generatedName:m,title:void 0,schema:Yo.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:xMe({schema:l,logger:n.logger})}),description:void 0,availability:p,namespace:void 0,groupName:void 0}):Bn.optional({nameOverride:void 0,generatedName:m,title:void 0,value:Bn.primitive({nameOverride:void 0,generatedName:m,title:void 0,schema:Yo.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:xMe({schema:l,logger:n.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:p,namespace:void 0,groupName:void 0,inline:void 0});if(l.in==="header"&&l.schema!=null&&!fo(l.schema)&&l.schema.default!=null){let _=l.schema.default;typeof _=="string"&&_.length>0&&(g=Bn.literal({nameOverride:void 0,generatedName:m,title:void 0,value:WP.string(_),description:void 0,availability:p,namespace:void 0,groupName:void 0}))}let b={name:l.name,schema:g,description:l.description,parameterNameOverride:eBl(l),availability:p,source:o};l.in==="query"?a.queryParameters.push({...b,explode:osA(l)}):l.in==="path"?a.pathParameters.push({...b,variableReference:tBl(l),explode:asA(l)}):l.in==="header"?!isA.has(l.name.toLowerCase())&&!n.authHeaders.has(l.name)?a.headers.push({...b,env:void 0}):n.logger.debug(`Ignoring ${l.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${l.in} parameter, ${l.name}, in ${t.toUpperCase()} ${e}`)}return a}var isA=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function osA(e){let t=e.style??"form",r=e.explode;if(r!==void 0)return t==="form"?r===!0?void 0:r:r===!1?void 0:r}function asA(e){let t=e.explode;if(t!==void 0)return t===!1?void 0:t}function ssA({content:e,context:t}){for(let[r,n]of Object.entries(e))if(nBl({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function nBl({mediaType:e,mediaTypeObject:t,context:r}){if(SA.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:zfr(t,r)}}function usA({content:e,context:t}){for(let[r,n]of Object.entries(e))if(iBl({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function iBl({mediaType:e,mediaTypeObject:t,context:r}){if(SA.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding,examples:zfr(t,r)}}function oBl({mediaType:e}){return SA.parse(e)?.isBinary()??!1}function csA({content:e}){for(let[t,r]of Object.entries(e))if(oBl({mediaType:t}))return[t,r]}function lsA(e,t){let r=fo(e)?Has(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!fo(i)&&i.type==="string"&&i.format==="binary")!=null}function lKn({content:e,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:a}){let s=csA({content:e});if(s){let[d,m]=s;return CMe({mediaType:d,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:a})}let c=usA({content:e,context:n}),l=Las({content:e,context:n}),u=psA({json:l,multipart:c,document:r,visitor:{json:([d,m])=>CMe({mediaType:d,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:a}),multipart:([d,m])=>CMe({mediaType:d,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:a}),neither:()=>{}}});if(u)return u;let p=ssA({content:e,context:n});if(p){let[d,m]=p;return CMe({mediaType:d,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:a})}}function psA({json:e,multipart:t,document:r,visitor:n}){if(!e&&!t)return n.neither();let[,i]=e??[void 0,void 0],[,o]=t??[void 0,void 0];return!i?.schema&&!o?.schema?n.neither():i?.schema&&o?.schema?i.schema&&lsA(i.schema,r)?n.multipart(t):n.json(e):i?.schema?n.json(e):o?.schema?n.multipart(t):n.neither()}function CMe({mediaType:e,mediaTypeObject:t,description:r,document:n,context:i,requestBreadcrumbs:o,source:a,namespace:s}){let c=fsA({mediaTypeObject:t});if(oBl({mediaType:e}))return DU.octetStream({description:r,source:a,sdkMethodName:c,contentType:e});let l=iBl({mediaType:e,mediaTypeObject:t,context:i}),u=l?.schema,p=l?.encoding,d=l?.examples;if(u){let y=fo(u)?Has(u,n):{id:void 0,schema:u},g=El(y.schema,!1,!1,i,o,a,s,!1),b=[];if(g.type==="object"){let _=new Set(y.schema.required??[]);for(let O of g.properties){let A=_.has(O.key),{isFile:v,isOptional:P,isArray:I,description:E}=cKn({schema:O.schema,isOptional:!A});if(v){let x=rBl(O.key,p);b.push({key:O.key,schema:AMe.file({isOptional:P,isArray:I,description:E}),description:E,contentType:x,exploded:!1,encoding:x==null?i.options.defaultFormParameterEncoding:void 0})}else{let x=rBl(O.key,p);b.push({key:O.key,schema:AMe.json(O.schema),description:void 0,contentType:x,exploded:p?.[O.key]?.explode,encoding:x==null?i.options.defaultFormParameterEncoding:msA(x)})}}}return DU.multipart({name:fo(u)&&i.getNumberOfOccurrencesForRef(u)===1?y.id:void 0,description:y.schema.description,properties:b,source:a,sdkMethodName:c,fullExamples:d})}let m=rKn({mediaType:e,mediaTypeObject:t,context:i});if(m){let y=El(m.schema,!1,!1,i,o,a,s,!0);return DU.json({description:void 0,schema:y,contentType:m.contentType,fullExamples:m.examples,additionalProperties:!fo(m.schema)&&eXr(m.schema.additionalProperties,i.options),source:a,sdkMethodName:c})}let h=nBl({mediaType:e,mediaTypeObject:t,context:i});if(h!=null&&h.schema!=null){let y=El(h.schema,!1,!1,i,o,a,s,!1);return DU.formUrlEncoded({schema:y,description:r,contentType:h.contentType,source:a,fullExamples:h.examples,additionalProperties:!1,sdkMethodName:c})}}function fsA({mediaTypeObject:e}){return ni(e,wi.SDK_METHOD_NAME)}var dsA={"application/json":"json"};function msA(e){return e?dsA[e]:void 0}function Has(e,t){if(!e.$ref.startsWith(nLt))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=Bgt(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let n=t.components?.schemas?.[r];if(n==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return fo(n)?Has(n,t):{id:r,schema:n}}function cKn({schema:e,isOptional:t,isArray:r,description:n}){return ysA(e)?cKn({schema:e.value,isOptional:!0,isArray:r,description:e.description}):gsA(e)?cKn({schema:e.value,isOptional:t,isArray:r,description:e.description}):bsA(e)?cKn({schema:e.value,isOptional:t,isArray:!0,description:e.description}):hsA(e)?{isFile:!0,isOptional:t??!1,isArray:r??!1,description:n??e.description}:{isFile:!1,isOptional:t??!1,isArray:r??!1,description:void 0}}function hsA(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function ysA(e){return e.type==="optional"}function gsA(e){return e.type==="nullable"}function bsA(e){return e.type==="array"}function rBl(e,t){return t?.[e]?.contentType}var $as={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},aBl=new Set(Object.values($as));var AsA=["200","201","202","204"];function pKn({operationContext:e,responses:t,context:r,responseBreadcrumbs:n,responseStatusCode:i,streamFormat:o,source:a}){if(t==null)return{value:void 0,errors:{}};let s=_sA({responses:t,context:r,source:a,namespace:r.namespace}),c=!1,l;for(let u of i!=null?[i]:AsA){let p=t[u];p!=null&&(c=!0,l==null&&(l=sBl({operationContext:e,response:p,context:r,responseBreadcrumbs:n,streamFormat:o,source:a,namespace:r.namespace,statusCode:typeof u=="string"?parseInt(u):u})))}if(l==null&&!c&&t.default!=null&&(l=sBl({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:o,source:a,namespace:r.namespace})),l!=null)switch(l.type){case"json":return{value:l,errors:s};case"streamingJson":case"streamingSse":return{value:l,errors:s};case"bytes":case"file":case"text":case"streamingText":return{value:l,errors:s};default:qe(l)}return{value:void 0,errors:s}}function sBl({operationContext:e,streamFormat:t,response:r,context:n,responseBreadcrumbs:i,source:o,namespace:a,statusCode:s}){let c=fo(r)?n.resolveResponseReference(r):r;if(c.content!=null&&Object.entries(c.content).find(([d,m])=>{if(m.schema==null)return!1;let h=fo(m.schema)?n.resolveSchemaReference(m.schema):m.schema;return h.type==="string"&&h.format==="binary"}))return n.options.useBytesForBinaryResponse&&t==null?Gw.bytes({description:c.description,source:o,statusCode:s}):Gw.file({description:c.description,source:o,statusCode:s});let l=qSl(c.content??{},n);if(l!=null&&t!=null)switch(t){case"json":return Gw.streamingJson({statusCode:s,description:c.description,responseProperty:ni(e.operation,wi.RESPONSE_PROPERTY),fullExamples:l.examples,schema:El(l.schema,!1,!1,n,i,o,a),source:o});case"sse":return Gw.streamingSse({description:c.description,responseProperty:void 0,fullExamples:l.examples,schema:El(l.schema,!1,!1,n,i,o,a),source:o,statusCode:s})}let u=nKn({context:n,content:c.content??{}});if(u){if(t!=null)switch(t){case"json":return Gw.streamingJson({description:c.description,responseProperty:void 0,fullExamples:u.examples,schema:El(u.schema,!1,!1,n,i,o,a),source:o,statusCode:s});case"sse":return Gw.streamingSse({description:c.description,responseProperty:void 0,fullExamples:u.examples,schema:El(u.schema,!1,!1,n,i,o,a),source:o,statusCode:s})}return Gw.json({description:c.description,schema:El(u.schema,!1,!1,n,i,o,a),responseProperty:ni(e.operation,wi.RESPONSE_PROPERTY),fullExamples:u.examples,source:o,statusCode:s})}for(let[p,d]of Object.entries(c.content??{})){let m=SA.parse(p);if(m!=null){if(m.isOctetStream()||m.isPDF()||m.isAudio()||m.isImage()||m.isVideo()||m.isMultiPartMixed())return Gw.file({description:c.description,source:o,statusCode:s});if(m.isPlainText()){let h=d.schema;if(h==null)return Gw.text({description:c.description,source:o,statusCode:s});let y=fo(h)?n.resolveSchemaReference(h):h;return y.type==="string"&&y.format==="byte"?Gw.file({description:c.description,source:o,statusCode:s}):Gw.text({description:c.description,source:o,statusCode:s})}}}}function _sA({responses:e,context:t,source:r,namespace:n}){let i={};for(let[o,a]of Object.entries(e)){if(o==="default")continue;let s=parseInt(o);if(s<400||s>600)continue;let c=fo(a)?t.resolveResponseReference(a):a,l=kSl(c.content??{},t),u=$as[s];if(u==null){t.logger.warn(`No error name found for status code ${o}`);continue}i[s]={statusCode:s,nameOverride:void 0,generatedName:u,description:c.description,schema:El(l?.schema??{},!1,!1,t,[u,"Body"],r,n),fullExamples:l?.examples,source:r}}return i}function uat({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,source:o}){let{document:a,operation:s,path:c,method:l,baseBreadcrumbs:u}=e,p=ni(s,wi.IDEMPOTENT),d=ni(s,[wi.REQUEST_NAME_V1,wi.REQUEST_NAME_V2]),m=[...u,"Request"],h=uKn({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:m,path:c,httpMethod:l,source:o}),y=/{([^}]+)}/g,g=[...c.matchAll(y)].map(T=>T[1]).filter(T=>T!==void 0),b=[...c.matchAll(y)].map(T=>T[1]);switch(t.options.pathParameterOrder){case vi.PathParameterOrder.SpecOrder:{let T=b.filter(W=>!h.pathParameters.some(H=>H.name===W));if(T.length>0)for(let W of T)h.pathParameters.push({name:W??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:o,schema:Bn.primitive({schema:Yo.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0})}break;case vi.PathParameterOrder.UrlOrder:if(g.length>0){let T=new Map(h.pathParameters.map(G=>[G.name,G])),W=[],H=new Set;for(let G of g){let ie=T.get(G);H.add(G),ie?W.push(ie):W.push({name:G,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:o,schema:Bn.primitive({schema:Yo.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0})}for(let G of h.pathParameters)H.has(G.name)||W.push(G);h.pathParameters=W}break;default:qe(t.options.pathParameterOrder)}let _=(()=>{if(e.method==="GET")return[void 0];if(!s.requestBody)return[void 0];let T=fo(s.requestBody)?t.resolveRequestBodyReference(s.requestBody):s.requestBody,W=Object.values(T.content).every(G=>OsA({mediaTypeObject:G})!=null),H=[];if(W)return H.push(...Object.entries(T.content).map(([G,ie])=>{let oe=CMe({mediaType:G,mediaTypeObject:ie,description:T.description,document:a,context:new oLt({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:m,source:o,namespace:t.namespace});return uBl({context:t,convertedParameters:h})&&oe!=null&&(oe.type==="json"||oe.type==="formUrlEncoded")&&oe.schema.type!=="object"&&s.requestBody!=null?oe=CMe({mediaType:G,mediaTypeObject:ie,description:T.description,document:a,context:t,requestBreadcrumbs:[...m,"Body"],source:o,namespace:t.namespace}):s.requestBody!=null&&(oe=CMe({mediaType:G,mediaTypeObject:ie,description:T.description,document:a,context:t,requestBreadcrumbs:[...m],source:o,namespace:t.namespace})),oe}).filter(G=>G!=null)),H.length===0?[void 0]:H;{let G=lKn({content:T.content,description:T.description,document:a,context:new oLt({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:m,source:o,namespace:t.namespace});return uBl({context:t,convertedParameters:h})&&G!=null&&(G.type==="json"||G.type==="formUrlEncoded")&&G.schema.type!=="object"&&s.requestBody!=null?G=lKn({content:T.content,description:T.description,document:a,context:t,requestBreadcrumbs:[...m,"Body"],source:o,namespace:t.namespace}):s.requestBody!=null&&(G=lKn({content:T.content,description:T.description,document:a,context:t,requestBreadcrumbs:[...m],source:o,namespace:t.namespace})),[G]}})(),O=_.length>1,A=[...u,"Response"],v=pKn({operationContext:e,streamFormat:i,responses:s.responses,context:t,responseBreadcrumbs:A,responseStatusCode:r,source:o}),P=ZSl(s),I=XSl(s),E=YSl(e,s,t),x=ni(s,wi.SERVER_NAME_V2);return _.map(T=>({summary:s.summary,internal:ni(s,sz.INTERNAL),idempotent:p,audiences:ni(s,wi.AUDIENCES)??[],operationId:s.operationId!=null&&n!=null?s.operationId+"_"+n:s.operationId,tags:t.resolveTagsToTagIds(s.tags),namespace:t.namespace,sdkName:wsA({operationContext:e,request:T}),pathParameters:h.pathParameters,queryParameters:h.queryParameters,headers:h.headers,requestNameOverride:d??void 0,generatedRequestName:HC(O?vsA({breadcrumbs:m,request:T}):m,t.options.preserveSchemaIds),request:T,response:v.value,errors:v.errors,servers:x!=null?[{name:x,url:void 0,audiences:void 0}]:(s.servers??[]).map(W=>sKn(W,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:s.description,authed:EsA(s,a),security:PsA(s),availability:I,method:l,path:c,examples:E,pagination:e.pagination,source:o,retries:P}))}function vsA({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function OsA({mediaTypeObject:e}){return ni(e,wi.SDK_METHOD_NAME)}function wsA({operationContext:e,request:t}){return!t||!t.sdkMethodName?e.sdkMethodName:e.sdkMethodName?{groupName:[...e.sdkMethodName.groupName],methodName:t.sdkMethodName??e.sdkMethodName.methodName}:{groupName:[],methodName:t.sdkMethodName}}function PsA(e){return e.security}function EsA(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function uBl({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function lBl({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:o,operationParameters:a}=e,s=r.discriminant.name,c=r.discriminant.value,l=r["response-status-code"],u=cBl({context:t,headerToIgnore:s,parameters:o}),p=cBl({context:t,headerToIgnore:s,parameters:a}),d=uat({operationContext:{...e,pathItemParameters:u,operationParameters:p,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([h])=>parseInt(h)!==l))}},context:t,streamFormat:void 0,source:n}),m=uat({operationContext:{...e,pathItemParameters:u,operationParameters:p,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:l,streamFormat:void 0,source:n});return m.forEach(h=>{h.headers.push({name:s,schema:Bn.literal({nameOverride:void 0,generatedName:HC([s],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:WP.string(c),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n})}),{sync:d,async:m}}function cBl({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=fo(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}var Jas="stream";function mBl({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:uat({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:[]};case"streamCondition":{let n=pBl({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(n?.schemaReference!=null){let l=Bgt(n.schemaReference);l!=null&&t.excludeSchema(l)}let i=fBl({operation:e.operation,response:r.responseStream}),o=uat({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+Jas}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,Jas]},context:t,streamFormat:r.format,suffix:Jas,source:t.source});o.forEach(l=>{l.examples=l.examples.filter(u=>dBl(u,t)!==!1)});let a=pBl({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),s=fBl({operation:e.operation,response:r.response}),c=uat({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:a?.requestBody,responses:s}},context:t,source:t.source});return c.forEach(l=>{l.examples=l.examples.filter(u=>dBl(u,t)!==!0)}),{streaming:o,nonStreaming:c}}default:qe(r)}}function pBl({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=fo(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,o=nKn({content:i.content,context:e});if(o==null)return;let a=fo(o.schema)?e.resolveSchemaReference(o.schema):o.schema;if(a.allOf==null&&a.properties==null)return;let s=a.properties?.[r.streamConditionProperty];s!=null&&fo(s)&&(s=void 0);let c={...a,properties:{...a.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":n,...s??{}}},title:void 0,required:[...a.required??[],r.streamConditionProperty]};return{requestBody:{content:{[SA.APPLICATION_JSON]:{schema:c}}},schemaReference:fo(o.schema)?o.schema:void 0}}function fBl({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[SA.APPLICATION_JSON]:{schema:t}}}}}function dBl(e,t){return e._visit({unknown:r=>{let n=zj.serialization.ExampleEndpointCallSchema.parse(r);if(n.ok&&n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}var hBl=require("crypto");function yBl({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:o,method:a,baseBreadcrumbs:s,sdkMethodName:c}=t,l=[...s,"Payload"],u=[...s,"Response"],p=uKn({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:l,path:o,httpMethod:a,source:r});if(i.requestBody==null)return e.logger.error(`Skipping webhook ${a.toUpperCase()} ${o}: Missing a request body`),[];let d=i.operationId??xsA({path:o,method:a,sdkMethodName:c}),m=i.responses?pKn({operationContext:t,streamFormat:void 0,responses:i.responses,context:e,responseBreadcrumbs:u,source:r}):void 0;if(a!=="POST"&&a!=="GET")return e.logger.error(`Skipping webhook ${a.toUpperCase()} ${o}: Not POST or GET`),[];let h=fo(i.requestBody)?e.resolveRequestBodyReference(i.requestBody):i.requestBody;return Object.entries(h.content).map(([y,g])=>CMe({mediaType:y,mediaTypeObject:g,description:h.description,document:n,context:e,requestBreadcrumbs:[...s,"Payload"],source:r,namespace:e.namespace})).filter(y=>y!=null).map(y=>{if(y==null||y.type!=="json"&&y.type!=="formUrlEncoded"&&y.type!=="multipart"){e.logger.error(`Skipping webhook ${o} because non-json, non-formUrlEncoded, and non-multipart request body`);return}let g,b;return y.type==="multipart"?(g={name:y.name,properties:y.properties,description:y.description,source:y.source},b=Bn.unknown({nameOverride:void 0,generatedName:HC(l,e.options.preserveSchemaIds),title:void 0,description:y.description,availability:void 0,namespace:e.namespace,groupName:void 0,example:void 0})):b=y.schema,{summary:i.summary,audiences:ni(i,wi.AUDIENCES)??[],sdkName:c,namespace:e.namespace,method:a,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:HC(l,e.options.preserveSchemaIds),payload:b,multipartFormData:g,response:m?.value,description:i.description,examples:IsA(y.fullExamples),source:r}}).filter(y=>y!=null)}function IsA(e){if(e==null)return[];let t=[];for(let r of e){let n=Tgt(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function xsA({path:e,method:t,sdkMethodName:r}){let n=r?.methodName??jsA(e),i=(0,hBl.createHash)("sha256").update(e).digest("hex").slice(0,8);return CsA(`${n}_${t.toLowerCase()}_${i}`)}function jsA(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function CsA(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function Kas({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=ni(r,wi.IGNORE);if(i!=null&&i){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let o=SsA(r,e),a=QSl(e.document,r),s={...t,sdkMethodName:o,baseBreadcrumbs:BsA({operation:r,sdkMethodName:o,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:a};if(n)return{type:"webhook",value:yBl({context:e,operationContext:s,source:e.source})};let c=MSl(r);if(c==null&&DsA({operation:r,context:e})&&(c={type:"stream",format:"sse"}),c!=null){let p=mBl({context:e,operationContext:s,streamingExtension:c});return p!=null?{type:"streaming",streaming:p.streaming,nonStreaming:p.nonStreaming}:void 0}let l=FSl(r);if(l!=null){let p=lBl({context:e,operationContext:s,asyncExtension:l,source:e.source});return{type:"async",async:p.async,sync:p.sync}}return{type:"http",value:uat({context:e,operationContext:s,streamFormat:void 0,source:e.source})}}function SsA(e,t){let r=ni(e,wi.SDK_METHOD_NAME),n=ni(e,wi.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function BsA({sdkMethodName:e,operation:t,httpMethod:r,path:n,shouldUseIdiomaticRequestNames:i}){let o=[];if(e!=null){if(i&&o.push(e.methodName),e.groupName.length>0){let a=e.groupName[e.groupName.length-1];a!=null&&o.push(typeof a=="string"?a:a.name)}i||o.push(e.methodName)}else t.operationId!=null?o.push(t.operationId):o.push(Xi(`${r}_${n.split("/").join("_")}`));return o}function DsA({operation:e,context:t}){if(e.responses==null)return!1;for(let r of Object.values(e.responses)){let n=fo(r)?t.resolveResponseReference(r):r;if(n.content!=null&&VSl(n.content))return!0}return!1}function gBl(e,t,r,n){let i=[],o=ABl(t),a={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let s of o){if(n.filter.skipEndpoint({method:s.method,path:e})){n.logger.debug(`Skipping endpoint "${s.method} ${e}"`);continue}let c=TsA({operation:s.operation}),l=Kas({context:n,pathItemContext:{...a,method:s.method},operation:s.operation,convertToWebhook:c});l&&i.push(l)}return i}function bBl(e,t,r,n){let i=[],o=ABl(t),a={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let s of o){if(n.filter.skipEndpoint({method:s.method,path:e})){n.logger.debug(`Skipping endpoint "${s.method} ${e}"`);continue}let c=Kas({context:n,pathItemContext:{...a,method:s.method},operation:s.operation,convertToWebhook:!0});c&&i.push(c)}return i}function ABl(e){let t=[];return e.get!=null&&t.push({method:CR.Get,operation:e.get}),e.post!=null&&t.push({method:CR.Post,operation:e.post}),e.put!=null&&t.push({method:CR.Put,operation:e.put}),e.delete!=null&&t.push({method:CR.Delete,operation:e.delete}),e.patch!=null&&t.push({method:CR.Patch,operation:e.patch}),e.head!=null&&t.push({method:CR.Head,operation:e.head}),t}function TsA({operation:e}){return ni(e,[wi.WEBHOOK])??!1}function _Bl(e){let t=ni(e,wi.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=ni(e,wi.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function vBl(e){return ni(e,wi.FERN_BASIC_AUTH)}function wBl(e,t,r,n){if(fo(e)){if(n==null)throw new Error(`Converting referenced security schemes requires context: ${JSON.stringify(e)}`);let i=n.resolveSecuritySchemeReference(e);return OBl(i,t,r)}return OBl(e,t,r)}function OBl(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let n=ni(e,sz.BEARER_FORMAT),i=ni(e,wi.FERN_HEADER_AUTH);return xR.header({headerName:e.name,prefix:n!=null?"Bearer":i?.prefix,headerVariableName:i?.name??ni(e,wi.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let n=ni(e,wi.FERN_BEARER_TOKEN);return xR.bearer({tokenVariableName:n?.name??ni(e,wi.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:n?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let n=vBl(e),i=_Bl(e);return xR.basic({usernameVariableName:n?.username?.name??i.usernameVariable,usernameEnvVar:n?.username?.env,passwordVariableName:n?.password?.name??i.passwordVariable,passwordEnvVar:n?.password?.env})}else{if(e.type==="openIdConnect")return xR.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return xR.oauth({scopesEnum:RsA(e,t)})}}catch(n){r.logger.debug(`Error converting security scheme: ${n?.message}`)}r.logger.debug(`Skipping security scheme: ${JSON.stringify(e,null)} - not currently supported. Please reach out to Fern support team!`)}function RsA(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let n=Sgt({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([o,a])=>[o,{description:a}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsOptional:!1,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),i=MA(n);if(i.type==="enum")return i}}function PBl(e){return ni(e,wi.BASE_PATH)}var FsA=Lt.record(Lt.string(),Lt.object({summary:Lt.string().optional(),description:Lt.string().optional()}));function EBl({document:e,context:t}){return XYr(e,wi.GROUPS,FsA,t.logger)}function IBl({context:e,document:t}){return ni(t,wi.FERN_VERSION)??void 0}function xBl(e){let t=ni(e,wi.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?ZYr({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function jBl(e){let t=ni(e,wi.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?ZYr({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function CBl(e,t){let r=ni(e,wi.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([n,i])=>{if(i.type==="string")return[n,{nameOverride:void 0,generatedName:HC([n],t),title:i.title,schema:Ph.string({default:Tfr(i),pattern:i.pattern,format:i.format,minLength:i.minLength,maxLength:i.maxLength}),description:i.description,availability:void 0,namespace:void 0,groupName:void 0}];throw new Error(`Variable ${n} has unsupported schema ${JSON.stringify(i)}`)}))}var NsA="webhooks";function SBl(e){return ni(e,NsA)??{}}var oXr=class extends Qfr{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:a}){super({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:a})}getDummy(){return new oLt({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,n){let i=this.discriminatedUnionReferences[t.$ref];i!=null?(i.discriminants.add(r),i.numReferences+=n):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:n}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,n){let i=this.discriminatedUnionMetadata[t.$ref];i!=null?i.discriminants.set(r,n):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,n]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function BBl(e){return ni(e,wi.RESOLUTIONS)}function DBl({openapi:e}){let t=BBl(e);if(t==null)return e;let r={};for(let n of t){let i=`#/components/schemas/${n.name}`;for(let o of n.resolutions)e=MsA({openapi:e,schemaReference:o,schemaName:n.name}),e=TBl({openapi:e,replaceReference:o,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(a=>[i,a]))}}return e}function MsA({openapi:e,schemaReference:t,schemaName:r}){let n=t.replace("#/","").split("/").map(o=>o.replaceAll("~1","/")),i=e;for(let o of n){let a=i[o];if(a==null)return e;i=a}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=i,e}function TBl({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(c=>t.startsWith(c)).sort((c,l)=>l.length-c.length)[0];if(i!=null){let c=n[i];if(c!=null){let l=r.replace(i,c);return TBl({openapi:e,replaceReference:t,schemaReference:l,replacedReferences:{}})}}let o=t.replace("#/","").split("/").map(c=>c.replaceAll("~1","/")),a=e;for(let c of o.slice(0,-1)){let l=a[c];if(l==null)return e;a=l}let s=o[o.length-1];return s==null||(a[s]={$ref:r}),e}function FBl({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=DBl({openapi:e}),$Jn();let o=new oXr({document:e,taskContext:t,authHeaders:new Set,options:r,source:n,namespace:i}),a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([W,H])=>{let G=wBl(H,n,t,o);return G==null?null:[W,G]}).filter(W=>W!==null)),s=e.security?.filter(W=>W!=null),c=new Set(...Object.entries(a).map(([W,H])=>H.type==="basic"||H.type==="bearer"?"Authorization":H.type==="header"?H.headerName:null)),l=CBl(e,r.preserveSchemaIds),u=xBl(e),p=jBl(e),d=r.audiences??[],m=[],h=[],y=new oXr({document:e,taskContext:t,authHeaders:c,options:r,source:n,namespace:i});y.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([W,H])=>{if(H==null)return;let G=gBl(W,H,e,y);for(let ie of G){let oe=RBl({operation:ie});if(!(d.length>0&&!d.some($=>oe.includes($))))switch(ie.type){case"async":m.push(...ie.sync),m.push(...ie.async);break;case"http":m.push(...ie.value);break;case"streaming":m.push(...ie.streaming),ie.nonStreaming&&m.push(...ie.nonStreaming);break;case"webhook":h.push(...ie.value);break;default:qe(ie)}}}),Object.entries(SBl(e)).forEach(([W,H])=>{if(H==null)return;t.logger.debug(`Converting path ${W}`);let G=bBl(W,H,e,y);for(let ie of G){let oe=RBl({operation:ie});d.length>0&&!d.some($=>oe.includes($))||h.push(...ie.value)}});let g=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([W,H])=>{let G=ni(H,wi.SDK_NAMESPACE);if(!fo(H)){let ie=ni(H,wi.IGNORE);if(ie!=null&&ie)return[];if(aBl.has(W))return[W,El({...H,"x-fern-type-name":`${W}Body`},!1,!1,y,[W],n,G??i)]}return[W,El(H,!1,!1,y,[W],n,G??i)]}).filter(W=>W.length>0)),b=zsA(g,y,n),_=QsA(b,y),O=IMe(),A={};for(let[W,H]of Object.entries(_)){let G=MA(H);if(y.isSchemaExcluded(W))continue;let ie=O.getUniqueSchemaId(W,y.logger,r.resolveSchemaCollisions);A[ie]=G}let v=new Rgt(_,y.nonRequestReferencedSchemas,y),P=h.map(W=>{let G=W.examples;if(!r.disableExamples&&G.length===0){let ie=v.buildExample({schema:W.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});ie!=null&&(G=[{name:void 0,description:void 0,payload:ie}])}return{...W,payload:MA(W.payload),examples:G}}),I=new YJn(_,y,u),E=m.map(W=>{let H=W.examples,G=H;if(!r.disableExamples&&(H.length===0||H.every(nXr))){let $=I.buildEndpointExample(W);$.length>0&&(G=[...$,...H.filter(te=>!nXr(te))])}let ie=W.request,oe=W.response;return{...W,request:ie?.type==="json"||ie?.type==="formUrlEncoded"?{...ie,schema:MA(ie.schema)}:ie,response:oe?.type==="json"?{...oe,schema:MA(oe.schema)}:oe,queryParameters:W.queryParameters.map($=>({description:$.description,name:$.name,schema:MA($.schema),parameterNameOverride:$.parameterNameOverride,availability:$.availability,source:$.source})),pathParameters:W.pathParameters.map($=>({description:$.description,name:$.name,schema:MA($.schema),parameterNameOverride:$.parameterNameOverride,variableReference:$.variableReference,availability:$.availability,source:$.source})),headers:W.headers.map($=>({description:$.description,name:$.name,schema:MA($.schema),parameterNameOverride:$.parameterNameOverride,env:$.env,availability:$.availability,source:$.source})),examples:G,errors:Mi(W.errors,$=>{let te=$.fullExamples?.map(Ge=>{let Ke=Tgt(Ge.value);if(Ke!=null)return{name:Ge.name,description:Ge.description,example:Ke}}).filter(Gu);if(te?.length===0){let Ge=v.buildExample({schema:$.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Ge!=null&&te.push({name:void 0,description:void 0,example:Ge})}return{generatedName:$.generatedName,nameOverride:$.nameOverride,schema:MA($.schema),description:$.description,source:$.source,examples:te}}),retries:W.retries}});I.finalize();let x=EBl({document:e,context:y});return{apiVersion:IBl({context:y,document:e}),basePath:PBl(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(x??{}).map(([W,H])=>[W,{summary:H.summary??void 0,description:H.description??void 0}])),servers:(e.servers??[]).map(W=>sKn(W,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(W=>[W.name,{id:W.name,description:W.description}])),orderedTagIds:e.tags?.map(W=>W.name)},endpoints:E,webhooks:P,channels:{},groupedSchemas:Ffr(i,A),securitySchemes:a,security:s,hasEndpointsMarkedInternal:E.some(W=>W.internal),nonRequestReferencedSchemas:y.getReferencedSchemas(),variables:l,globalHeaders:u,idempotencyHeaders:p}}function zsA(e,t,r){if(t.options.removeDiscriminantsFromSchemas===vi.RemoveDiscriminantsFromSchemas.Never)return e;let n={};for(let[i,o]of Object.entries(e)){if(o.type!=="object"){n[i]=o;continue}let a={$ref:`#/components/schemas/${i}`},s=t.getReferencesFromDiscriminatedUnion(a);if(s==null){n[i]=o;continue}if(t.getReferencedSchemas().has(i)){n[i]=o;continue}let l={...o,type:"object",properties:o.properties.filter(p=>!s.discriminants.has(p.key)),allOfPropertyConflicts:o.allOfPropertyConflicts.filter(p=>!s.discriminants.has(p.propertyKey)),source:r};n[i]=l;let u=NBl({schema:o,schemas:e});for(let p of[...new Set(u)]){let d=n[p]??e[p];d==null||d.type!=="object"||(n[p]={...d,type:"object",properties:d.properties.filter(m=>!s.discriminants.has(m.key)),allOfPropertyConflicts:d.allOfPropertyConflicts.filter(m=>!s.discriminants.has(m.propertyKey))})}}return n}function QsA(e,t){let r={};for(let[n,i]of Object.entries(e)){if(i.type!=="object"){r[n]=i;continue}let o={$ref:`#/components/schemas/${n}`},a=t.getDiscriminatedUnionMetadata(o);if(a==null){r[n]=i;continue}let s=[];for(let l of i.properties)if(a.discriminants.has(l.key)){let u=a.discriminants.get(l.key);u!=null&&s.push({...l,schema:Bn.literal({nameOverride:void 0,generatedName:HC([i.generatedName,u],t.options.preserveSchemaIds),title:void 0,value:WP.string(u),namespace:void 0,groupName:void 0,description:void 0,availability:i.availability})})}else s.push(l);let c={...i,type:"object",properties:s};r[n]=c}return r}function NBl({schema:e,schemas:t}){let r=[];for(let n of e.allOf){r.push(n.schema);let i=t[n.schema];i!=null&&i.type==="object"&&r.push(...NBl({schema:i,schemas:t}))}return r}function fKn(e){return[...new Set(e)]}function RBl({operation:e}){let t=[];switch(e.type){case"async":t=fKn(e.async.flatMap(r=>r.audiences));break;case"http":t=fKn(e.value.flatMap(r=>r.audiences));break;case"streaming":t=fKn(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=fKn(e.value.flatMap(r=>r.audiences));break;default:qe(e)}return t}function aLt({context:e,documents:t,options:r}){let n={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},security:void 0,globalHeaders:[],idempotencyHeaders:[],groups:{}},i=0;for(let o of t)try{let a=o.source!=null?o.source:eq.openapi({file:"<memory>"});switch(o.type){case"openapi":{let s=FBl({taskContext:e,openApi:o.value,options:ore({options:o.settings,overrides:r}),source:a,namespace:o.namespace});n=LsA(n,s,ore({options:o.settings,overrides:r})),i++;break}case"asyncapi":{let s=RSl({document:o.value,taskContext:e,options:ore({options:o.settings,overrides:r}),source:a,asyncApiOptions:qsA({options:o.settings}),namespace:o.namespace});s.servers!=null&&(n.websocketServers=[...n.websocketServers,...s.servers.map(c=>({...c,audiences:void 0,description:void 0,defaultUrl:void 0,urlTemplate:void 0,variables:void 0}))]),s.channels!=null&&(n.channels={...n.channels,...s.channels}),s.groupedSchemas!=null&&(n.groupedSchemas=dKn(n.groupedSchemas,s.groupedSchemas,r)),s.basePath!=null&&(n.basePath=s.basePath),i++;break}default:qe(o)}}catch(a){e.logger.error(`Failed to parse ${o.type} document ${o.type==="openapi"?o.value.info?.title:o.source?.file}`),a instanceof Error&&e.logger.error(a.message,a.stack?`
|
|
1532
|
+
`);try{Nfr.writeFileSync(n,i,"utf8"),this.logger.info(`Missing examples report written to: ${n}`)}catch(o){this.logger.warn(`Failed to write missing examples report to ${n}:`,String(o))}}finalize(){}convertExampleToJson(t){switch(t.type){case"primitive":return t.value;case"array":return t.value.map(r=>this.convertExampleToJson(r));case"object":{let r={};return Object.entries(t.properties).forEach(([n,i])=>{r[n]=this.convertExampleToJson(i)}),r}case"map":{let r={};return t.value.forEach(n=>{r[String(n.key)]=this.convertExampleToJson(n.value)}),r}case"oneOf":if(t.value.type==="undiscriminated")return this.convertExampleToJson(t.value.value);{let r={};return Object.entries(t.value.value).forEach(([n,i])=>{r[n]=this.convertExampleToJson(i)}),r}case"enum":return t.value;case"literal":return t.value;case"null":return null;case"unknown":return this.convertExampleToJson(t.value);default:return t}}getSchemaDescription(t){if("description"in t)return t.description}getSchemaTypeName(t){switch(t.type){case"primitive":return`primitive (${t.schema.type})`;case"object":return t.generatedName||"object";case"array":return"array";case"map":return"map";case"optional":return`optional (${this.getSchemaTypeName(t.value)})`;case"nullable":return`nullable (${this.getSchemaTypeName(t.value)})`;case"reference":return t.generatedName||"reference";case"enum":return t.generatedName||"enum";case"literal":return"literal";case"oneOf":return"oneOf";case"unknown":return"unknown";default:return"unknown"}}buildEndpointExample(t){let r=NaA(t.request),n=MaA(t.response);if(r?.type==="unsupported"||n?.type==="unsupported")return[];let i=[];if(r!=null&&r.type==="present"){let p=this.isSchemaRequired(r.schema);if(r.examples.length===0){let d=this.exampleTypeFactory.buildExample({skipReadonly:kas(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});d!=null?(i.push([void 0,d]),this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(r.schema),autoGeneratedExample:this.convertExampleToJson(d)})):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(r.schema)})}else for(let{name:d,value:m}of r.examples){let h=this.exampleTypeFactory.buildExample({skipReadonly:kas(t.method),schema:r.schema,exampleId:d,example:m,options:{isParameter:!1,ignoreOptionals:!0}});h!=null?i.push([d,h]):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),`Failed to build example from provided data (example id: ${d})`,{schemaDescription:this.getSchemaDescription(r.schema)})}if(p&&i.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let o=[];if(n!=null&&n.type==="present"){let p=this.isSchemaRequired(n.schema);if(n.examples.length===0){let d=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});d!=null?(t.response?.type==="json"?o.push([void 0,nre.withoutStreaming(d)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,nre.withStreaming({sse:t.response?.type==="streamingSse",events:[d]})]),this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(n.schema),autoGeneratedExample:this.convertExampleToJson(d)})):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(n.schema)})}else for(let{name:d,value:m}of n.examples){let h=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:n.schema,exampleId:d,example:m,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});h!=null?t.response?.type==="json"?o.push([d,nre.withoutStreaming(h)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&o.push([void 0,nre.withStreaming({sse:t.response?.type==="streamingSse",events:[h]})]):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(n.schema),`Failed to build example from provided data (example id: ${d})`,{schemaDescription:this.getSchemaDescription(n.schema)})}if(p&&o.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];for(let p of t.pathParameters){let d=this.isSchemaRequired(p.schema),m=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(m!=null&&!Mxe(m)&&(this.logger.debug(`Expected a primitive example but got ${m.type} for path parameter ${p.name} for ${t.method.toUpperCase()} ${t.path}`),m=void 0),d&&m==null)return[];m!=null&&a.push({name:p.name,parameterNameOverride:p.parameterNameOverride,value:m})}let s=[];for(let p of t.queryParameters){let d=this.isSchemaRequired(p.schema),m=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(m!=null&&!Mxe(m)&&(this.logger.debug(`Expected a primitive example but got ${m.type} for query parameter ${p.name} for ${t.method.toUpperCase()} ${t.path}`),m=void 0),d&&m==null)return[];m!=null&&s.push({name:p.name,value:m})}let c=[];for(let p of t.headers){let d=this.isSchemaRequired(p.schema),m=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:void 0,options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});if(m!=null&&!Mxe(m)&&(this.logger.debug(`Expected a primitive example but got ${m.type} for header ${p.name} for ${t.method.toUpperCase()} ${t.path}`),m=void 0),d&&m==null)return[];m!=null&&c.push({name:p.name,value:m})}for(let p of this.globalHeaders){let d=p.schema!=null?Nxe(p.schema):Bn.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:Yo.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),m=this.exampleTypeFactory.buildExample({schema:d,exampleId:void 0,example:void 0,options:{name:p.header,isParameter:!0,ignoreOptionals:!0}});if(m!=null&&!Mxe(m)&&(this.logger.debug(`Expected a primitive example but got ${m.type} for global header ${p.header} for ${t.method.toUpperCase()} ${t.path}`),m=void 0),m==null)return[];m!=null&&c.push({name:p.header,value:m})}let l=[];t.request!=null&&t.response!=null?l=FaA(i,o):t.request!=null?l=i.map(([p,d])=>({id:p,request:d,response:void 0})):t.response!=null&&(l=o.map(([p,d])=>({id:p,request:void 0,response:d})));let u=t.examples.filter(p=>nXr(p)).flatMap(p=>{if(p.type==="unknown"){if(p.value!=null){let d=p.value["code-samples"];if(d!=null)return this.convertCodeSamples(d)}return}else return p.codeSamples}).filter(p=>Gu(p));return l.length===0?[rre.full({name:void 0,description:void 0,pathParameters:a,queryParameters:s,headers:c,request:void 0,response:void 0,codeSamples:u})]:l.map(({id:p,request:d,response:m})=>rre.full({name:p,description:void 0,pathParameters:a,queryParameters:s,headers:c,request:d,response:m,codeSamples:u}))}convertCodeSamples(t){return t.map(r=>"language"in r?bMe.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):bMe.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?SR.Csharp:r.sdk,code:r.code})).filter(Gu)}isSchemaRequired(t){return KJn(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function FaA(e,t){let r=[];if(e.length<=1){let[i,o]=e[0]??[];if(t.length===0)return r.push({id:i,request:o,response:void 0}),r;for(let[a,s]of t)r.push({id:a??i,request:o,response:s});return r}if(t.length<=1){let[i,o]=t[0]??[];if(t.length===0)return r.push({id:i,request:void 0,response:o}),r;for(let[a,s]of e)r.push({id:a??i,request:s,response:o});return r}let n=new Set;for(let[i,o]of e){let a=t.find(([c])=>c==null)?.[1]??t[0]?.[1];if(i==null){if(a==null)continue;r.push({id:void 0,request:o,response:a});continue}let s=!1;for(let c=0;c<t.length;c++){let[l,u]=t[c];l==null||n.has(c)||i===l&&(r.push({id:i,request:o,response:u}),l!=null&&n.add(c),s=!0)}!s&&a!=null&&r.push({id:i,request:o,response:a})}for(let i=0;i<t.length;i++){if(n.has(i))continue;let[o,a]=t[i],s=e.find(([c])=>c==null)?.[1]??e[0]?.[1];s!=null&&r.push({id:o,request:s,response:a})}return r}function NaA(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:zaA(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function MaA(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function Mxe(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return Mxe(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return Mxe(e.value.value);default:return!1}case"null":return!0;default:qe(e)}}function zaA(e){return Bn.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:Nxe(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(Gu),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source,inline:void 0,minProperties:void 0,maxProperties:void 0})}var Mfr=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new Rgt(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:n,source:i,namespace:o}){let a=[];for(let s of r){let c=[];for(let p of n.queryParameters){let d=this.isSchemaRequired(p.schema),m=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:s.queryParameters?.[p.name],options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!Mxe(m)&&(m=void 0),!(d&&m==null)&&m!=null&&c.push({name:p.name,value:m})}let l=[];for(let p of n.headers){let d=this.isSchemaRequired(p.schema),m=this.exampleTypeFactory.buildExample({schema:p.schema,exampleId:void 0,example:s.headers?.[p.name],options:{name:p.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!Mxe(m)&&(m=void 0),!(d&&m==null)&&m!=null&&l.push({name:p.name,value:m})}let u=[];for(let p of s.messages){let d=t.getExampleMessageReference(p),m=t.resolveMessageReference({$ref:d}),h=fo(m.payload)?t.resolveSchemaReference(m.payload):m.payload,y=this.exampleTypeFactory.buildExample({schema:El(h,!1,!1,t,[p.messageId],i,o),exampleId:void 0,example:p.value,options:{isParameter:!1,ignoreOptionals:!0}});y!=null&&u.push({messageType:p.type,payload:y,description:void 0})}a.push({name:s.summary,queryParameters:c,headers:l,description:s.description,messages:u})}return a}buildWebsocketSessionExample({handshake:t,messages:r}){let n={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},i=[];for(let a of t.queryParameters){let s=this.isSchemaRequired(a.schema),c=this.exampleTypeFactory.buildExample({schema:a.schema,exampleId:void 0,example:void 0,options:{name:a.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!Mxe(c)&&(c=void 0),s&&c==null)return;c!=null&&i.push({name:a.name,value:c})}let o=[];for(let a of t.headers){let s=this.isSchemaRequired(a.schema),c=this.exampleTypeFactory.buildExample({schema:a.schema,exampleId:void 0,example:void 0,options:{name:a.name,isParameter:!0,ignoreOptionals:!0}});if(c!=null&&!Mxe(c)&&(c=void 0),s&&c==null)return;c!=null&&o.push({name:a.name,value:c})}for(let a of r){let s=this.exampleTypeFactory.buildExample({schema:a.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});s!=null&&n.messages.push({messageType:a.type,payload:s,description:void 0})}return n}isSchemaRequired(t){return KJn(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var uz={FERN_PARAMETER_OPTIONAL:"x-fern-optional",FERN_CHANNEL_ADDRESS:"x-fern-address",FERN_DISPLAY_NAME:"x-fern-display-name",FERN_SDK_GROUP_NAME:"x-fern-sdk-group-name",FERN_SDK_METHOD_NAME:"x-fern-sdk-method-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore",FERN_PARAMETER_NAME:"x-fern-parameter-name"};function XJn(e){return ni(e,uz.FERN_EXAMPLES)??[]}function ZJn(e,t){return t.includes("://")?t:`${e}://${t}`}function eKn(e){return e.startsWith("/")?e:"/"+e}function CSl({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){let o={},a={};for(let[l,u]of Object.entries(i.components?.schemas??{})){let p=El(u,!1,!1,e,[l],r,e.namespace);o[l]=p}let s=new Mfr(o,e),c={};for(let[l,u]of Object.entries(i.servers??{}))c[l]={name:l,url:ZJn(u.protocol,u.url)};for(let[l,u]of Object.entries(i.channels??{})){let p=ni(u,uz.IGNORE);if(p!=null&&p){e.logger.debug(`Channel ${l} is marked with x-fern-ignore. Skipping.`);continue}let d=[];if(u.parameters!=null)for(let[b,_]of Object.entries(u.parameters??{})){let O=ni(_,uz.FERN_PARAMETER_NAME);d.push({name:b,description:_.description,parameterNameOverride:O,schema:_.schema!=null?El(_.schema,!1,!1,e,t,r,e.namespace):Bn.primitive({schema:Yo.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:rq(_),source:r,explode:void 0})}let m=[],h=[];if(u.bindings?.ws!=null){if(u.bindings.ws.headers!=null){let b=u.bindings.ws.headers.required??[];for(let[_,O]of Object.entries(u.bindings.ws.headers.properties??{})){if(fo(O)){let I=e.resolveSchemaReference(O),E=b.includes(_),[x,T]=e.options.coerceOptionalSchemasToNullable?[!1,!E]:[!E,!1];m.push({name:_,schema:sat(O,x,T,e,t,void 0,r,e.namespace),description:I.description,parameterNameOverride:void 0,env:void 0,availability:rq(I),source:r});continue}let A=b.includes(_),[v,P]=e.options.coerceOptionalSchemasToNullable?[!1,!A]:[!A,!1];m.push({name:_,schema:El(O,v,P,e,[...t,_],r,e.namespace),description:O.description,parameterNameOverride:void 0,env:void 0,availability:rq(O),source:r})}}if(u.bindings.ws.query!=null){let b=u.bindings.ws.query.required??[];for(let[_,O]of Object.entries(u.bindings.ws.query.properties??{})){if(fo(O)){let I=e.resolveSchemaReference(O),E=b.includes(_),[x,T]=e.options.coerceOptionalSchemasToNullable?[!1,!E]:[!E,!1];h.push({name:_,schema:sat(O,x,T,e,t,void 0,r,e.namespace),description:I.description,parameterNameOverride:void 0,availability:rq(I),source:r,explode:void 0});continue}let A=b.includes(_),[v,P]=e.options.coerceOptionalSchemasToNullable?[!1,!A]:[!A,!1];h.push({name:_,schema:El(O,v,P,e,[...t,_],r,e.namespace),description:O.description,parameterNameOverride:void 0,availability:rq(O),source:r,explode:void 0})}}}let y;u.publish!=null&&("oneOf"in u.publish.message?y=xSl({generatedName:u.publish.operationId??"PublishEvent",event:u.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):y=jSl({action:"Publish",channelPath:l,message:u.publish.message,context:e,source:r}));let g;if(u.subscribe!=null&&("oneOf"in u.subscribe.message?g=xSl({generatedName:u.subscribe.operationId??"SubscribeEvent",event:u.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:n}):g=jSl({action:"Subscribe",channelPath:l,message:u.subscribe.message,context:e,source:r})),m.length>0||h.length>0||y!=null||g!=null){let b=XJn(u),_=[];if(b.length>0)_=s.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:b,handshake:{headers:m,queryParameters:h},source:r,namespace:e.namespace});else{let P=[];y!=null&&P.push({type:"publish",payload:y}),g!=null&&P.push({type:"subscribe",payload:g});let I=s.buildWebsocketSessionExample({handshake:{headers:m,queryParameters:h},messages:P});I!=null&&_.push(I)}let O=ni(u,uz.FERN_CHANNEL_ADDRESS),A=O??eKn(l),v=[];y!=null&&v.push({origin:"client",name:"publish",body:MA(y),methodName:void 0}),g!=null&&v.push({origin:"server",name:"subscribe",body:MA(g),methodName:void 0}),a[l]={audiences:ni(u,wi.AUDIENCES)??[],handshake:{headers:m.map(P=>({...P,schema:MA(P.schema),env:P.env})),queryParameters:h.map(P=>({...P,schema:MA(P.schema)})),pathParameters:d.map(P=>({...P,schema:MA(P.schema)}))},groupName:e.resolveGroupName([ni(u,uz.FERN_SDK_GROUP_NAME)??l]),messages:v,servers:(u.servers?.map(P=>c[P])??Object.values(c)).filter(P=>P!=null&&P.name!=null).map(P=>({...P,name:P.name})),summary:ni(u,uz.FERN_DISPLAY_NAME),path:A,description:u.description,examples:_,source:r}}}return{groupedSchemas:Ffr(e.namespace,o),channels:a??void 0,servers:Object.values(c).map(l=>({...l,name:l.name})),basePath:ni(i,uz.BASE_PATH)}}function xSl({generatedName:e,event:t,context:r,breadcrumbs:n,source:i,options:o,asyncApiOptions:a}){if("oneOf"in t.message&&t.message.oneOf!=null){let s=[],c=[];for(let l of t.message.oneOf){let u,p={type:"notFound"};if(fo(l)){let d=r.resolveMessageReference(l);!fo(d.payload)&&a.naming==="v2"?(p=d.name?{type:"name",name:d.name}:p,u={...d.payload,title:d.name??d.payload.title,description:d.name??d.payload.description}):u=d.payload}else u=l;c.push(p),s.push(u)}return Dgt({description:t.description??t.message.description,availability:rq(t.message),subtypes:s,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsOptional:!1,wrapAsNullable:!1,breadcrumbs:n,context:r,encoding:void 0,source:i,namespace:r.namespace,subtypeSuffixOverrides:a.naming==="v2"?c:[]})}}function jSl({action:e,channelPath:t,message:r,context:n,source:i}){if(r.payload!=null){let o=r.payload;return fo(r.payload)&&(o=n.resolveSchemaReference(r.payload)),El(o,!1,!1,n,[t,e],i,n.namespace)}}var tKn=class extends Rfr{getExampleMessageReference(t){return`#/channels/${t.channelId}/messages/${t.messageId}`}resolveParameterReference(t){let r="#/components/parameters/";if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve ${t.$ref}`);let n=t.$ref.substring(r.length),i=this.document.components.parameters[n];if(i==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in i?this.resolveParameterReference(i):i}resolveMessageReference(t,r=!1){let n="#/channels/",i="#/components/messages/";if(t==null)throw new Error("Cannot resolve message reference: message is null or undefined");if(!t.$ref)throw new Error("Cannot resolve message reference: message.$ref is undefined or empty");if(t.$ref.startsWith(n)){let c=t.$ref.split("/"),l=c[2],u=c[4],p=l?.replace(/~1/g,"/").replace(/~0/g,"~");if(p==null||u==null||!this.document.channels?.[p])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${p}`);let m=this.document.channels[p].messages?.[u];if(m==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in m&&!r?this.resolveMessageReference(m):{...m,name:u}}let o=this.document.components;if(!t.$ref.startsWith(i)||!o?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let a=t.$ref.substring(i.length),s=o.messages[a];if(s==null)throw new Error(`${t.$ref} is undefined`);return{...s,name:a}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}};var SSl="#/channels/",BSl="#/servers/",Uas="$message.";function TSl({context:e,breadcrumbs:t,source:r,asyncApiOptions:n,document:i}){$Jn();let o={},a={},s={},c=[],l={};e.logger.debug("Parsing V3 AsyncAPI...");let u=IMe();for(let[I,E]of Object.entries(i.components?.schemas??{})){let x=u.getUniqueSchemaId(I,e.logger,e.options.resolveSchemaCollisions);o[x]=El(E,!1,!1,e,[x],r,e.namespace)}for(let[I,E]of Object.entries(i.channels??{}))if(a[I]||(a[I]={}),E.messages)for(let[x,T]of Object.entries(E.messages))if(s[x]||(s[x]=[]),e.isReferenceObject(T)){let W=e.resolveMessageReference(T);s[x].push({channelId:I,payload:W.payload})}else e.isMessageWithPayload(T)&&s[x].push({channelId:I,payload:T.payload});for(let[I,E]of Object.entries(s))if(E.length===1){let x=E[0],T=x.channelId;a[T]=a[T]||{},a[T][I]=El(x.payload,!1,!1,e,[I],r,e.namespace)}else{c.push(I);for(let{channelId:x,payload:T}of E){let W=`${x}_${I}`;a[x]||(a[x]={}),a[x][W]=El(T,!1,!1,e,[W],r,e.namespace)}}let p={},d=IMe();for(let[I,E]of Object.entries(a))for(let[x,T]of Object.entries(E)){let W=d.getUniqueSchemaId(x,e.logger,e.options.resolveSchemaCollisions);p[W]=T}let m=new Mfr({...o,...p},e),h={};for(let[I,E]of Object.entries(i.servers??{}))h[I]={name:I,url:ZJn(E.protocol,E.host)};let y={},g=Object.keys(i.channels??{});for(let[I,E]of Object.entries(i.operations??{})){if(ni(E,uz.IGNORE))continue;let x;if(E.channel==null||!("$ref"in E.channel)||E.channel.$ref==null)if(g.length===1&&g[0]!=null)x=g[0];else continue;else x=qaA(E);y[x]||(y[x]={subscribe:[],publish:[],__parsedMessages:[]});let T=ni(E,uz.FERN_SDK_METHOD_NAME);if(!E.messages||!Array.isArray(E.messages))continue;let W=E.messages.filter(G=>G!=null&&G.$ref!=null).map(G=>({ref:G,methodName:T})),H=y[x];if(H==null)throw new Error(`Internal error: channelEvents["${x}"] is unexpectedly undefined for operation ${I}`);if(E.action==="receive")H.subscribe.push(...W);else if(E.action==="send")H.publish.push(...W);else throw new Error(`Operation ${I} has an invalid action: ${E.action}`)}for(let[I,E]of Object.entries(y)){let x=[];x.push(...DSl({messages:E.subscribe,channelPath:I,origin:"server",messageSchemas:a[I]??{},duplicatedMessageIds:c,context:e})),x.push(...DSl({messages:E.publish,channelPath:I,origin:"client",messageSchemas:a[I]??{},duplicatedMessageIds:c,context:e})),y[I]!=null&&(y[I].__parsedMessages=x)}for(let[I,E]of Object.entries(i.channels??{})){if(ni(E,uz.IGNORE))continue;let x=[],T=[],W=[];if(E.parameters!=null)for(let[H,G]of Object.entries(E.parameters)){let ie=e.isReferenceObject(G)?e.resolveParameterReference(G):G,{type:oe,parameterKey:$}=ie.location!=null?VaA(ie.location):{type:E.address?.includes(`={${H}}`)?"query":"path",parameterKey:H},te=ni(ie,uz.FERN_PARAMETER_OPTIONAL),Ge=Xd(Xi(I))+Xd(Xi(H)),Ke={...ie,type:"string",title:Ge,example:ie.examples?.[0],default:ie.default,enum:ie.enum,required:void 0},Z=El(Ke,!1,!1,e,[$],r,e.namespace);te&&(Z=Bn.optional({value:Z,description:void 0,availability:void 0,generatedName:"",title:Ge,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}));let Y={name:$,description:ie.description,parameterNameOverride:void 0,schema:Z,variableReference:void 0,availability:rq(G),source:r,explode:void 0};oe==="header"?x.push({...Y,env:void 0}):oe==="path"?T.push(Y):(oe==="payload"||oe==="query")&&W.push(Y)}if(x.length>0||W.length>0||y[I]!=null&&(y[I].publish!=null||y[I].subscribe!=null)){let H=XJn(E),G=y[I]?.__parsedMessages??[],ie=[];if(H.length>0)ie=m.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:H,handshake:{headers:x,queryParameters:W},source:r,namespace:e.namespace});else{let Ge=[],{examplePublishMessage:Ke,exampleSubscribeMessage:Z}=UaA({messages:G,messageSchemas:a[I]??{}});Ke!=null&&Ge.push(Ke),Z!=null&&Ge.push(Z);let Y=m.buildWebsocketSessionExample({handshake:{headers:x,queryParameters:W},messages:Ge});Y!=null&&ie.push(Y)}let oe=ni(E,uz.FERN_SDK_GROUP_NAME),$=(E.servers?.map(Ge=>kaA(h,Ge))??Object.values(h)).map(Ge=>({...Ge,name:Ge.name})),te=E.address?.split("?")[0]??eKn(I);l[I]={audiences:ni(E,wi.AUDIENCES)??[],handshake:{headers:x.map(Ge=>({...Ge,schema:MA(Ge.schema),env:Ge.env})),queryParameters:W.map(Ge=>({...Ge,schema:MA(Ge.schema)})),pathParameters:T.map(Ge=>({...Ge,parameterNameOverride:void 0,schema:MA(Ge.schema)}))},groupName:e.resolveGroupName(typeof oe=="string"?[oe]:oe??[I]),messages:G,summary:ni(E,uz.FERN_DISPLAY_NAME),servers:$,path:te,description:E.description,examples:ie,source:r}}else e.logger.warn(`Skipping AsyncAPI channel ${I} as it does not qualify for inclusion (no headers, query params, or operations)`)}let b={...o,...p},_={},O=IMe();for(let[I,E]of Object.entries(b)){let x=O.getUniqueSchemaId(I,e.logger,e.options.resolveSchemaCollisions);_[x]=MA(E)}let A=Ffr(e.namespace,o),v=Object.values(h).map(I=>({...I,name:I.name})),P=ni(i,uz.BASE_PATH);return{groupedSchemas:A,channels:l,servers:v,basePath:P}}function QaA(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function qaA(e){if(!e.channel)throw new Error("Operation is missing required 'channel' field");if(!e.channel.$ref)throw new Error("Operation channel is missing required '$ref' field");if(!e.channel.$ref.startsWith(SSl))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return QaA(e.channel.$ref.substring(SSl.length))}function VaA(e){try{let[t,r]=e.split("#/");if(t==null||r==null)throw new Error(`Invalid location format: ${e}; unable to parse message type and parameter key`);if(!t.startsWith(Uas))throw new Error(`Invalid location format: ${e}; expected ${Uas} prefix`);let n=t.substring(Uas.length);if(n!=="header"&&n!=="path"&&n!=="payload")throw new Error(`Invalid message type: ${n}. Must be one of: header, path, payload`);return{type:n,parameterKey:r}}catch{throw new Error(`Invalid location format: ${e}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`)}}function kaA(e,t){if(!t.$ref.startsWith(BSl))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(BSl.length),n=e[r];if(n==null)throw new Error(`Failed to find server with name ${r}`);return n}function DSl({messages:e,channelPath:t,origin:r,messageSchemas:n,duplicatedMessageIds:i,context:o}){let a=[];return e.forEach((s,c)=>{let u=o.resolveMessageReference(s.ref,!0).name;i.includes(u)&&(u=`${t}_${u}`);let p=n[u];p!=null&&a.push({origin:r,name:u??`${r}Message${c+1}`,body:MA(p),methodName:s.methodName})}),a}function UaA({messages:e,messageSchemas:t}){let r=e.find(a=>a.origin==="client")?.name,n=e.find(a=>a.origin==="server")?.name,i=r!=null?t[r]:void 0,o=n!=null?t[n]:void 0;return{examplePublishMessage:i!=null&&r!=null?{type:r,payload:i}:void 0,exampleSubscribeMessage:o!=null&&n!=null?{type:n,payload:o}:void 0}}function RSl({document:e,taskContext:t,options:r,source:n,asyncApiOptions:i,namespace:o}){let a=[];if(o!=null&&a.push(o),parseFloat(e.asyncapi)<3){let s=e;s.tags?.[0]!=null?a.push(s.tags[0].name):i.naming!=="v2"&&a.push("websocket");let c=new JJn({document:s,taskContext:t,options:r,namespace:o});return CSl({context:c,breadcrumbs:a,source:n,asyncApiOptions:i,document:s})}else{let s=e,c=new tKn({document:s,taskContext:t,options:r,namespace:o});return TSl({context:c,breadcrumbs:a,source:n,asyncApiOptions:i,document:s})}}function FSl(e){return ni(e,wi.ASYNC_CONFIG)}var NSl="$request.";function MSl(e){let t=ni(e,wi.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:LaA(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function LaA(e){return e.startsWith(NSl)?e.slice(NSl.length):e}function zSl(e){let t=e;if(t.cursor!=null)return MT.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;if("next_uri"in r)return MT.uri({nextUri:r.next_uri,results:r.results});let n=e;if("next_path"in n)return MT.path({nextPath:n.next_path,results:n.results});if("offset"in e){let i=e;return MT.offset({offset:i.offset,results:i.results,step:i.step,hasNextPage:i["has-next-page"]})}if("type"in e&&e.type==="custom"){let i=e;return MT.custom({results:i.results})}throw new Error("Invalid pagination extension")}function QSl(e,t){let r=ni(t,wi.PAGINATION);if(r!=null){if(typeof r=="boolean"){let n=ni(e,wi.PAGINATION);if(typeof n=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return n==null?void 0:zSl(n)}return zSl(r)}}function qSl(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let n=e[r];if(n==null)continue;let i=n,o=n.schema??i.itemSchema;return{contentType:r,schema:o??{},examples:zfr(n,t)}}}function VSl(e){for(let t of Object.keys(e))if(t.includes("text/event-stream")){let r=e[t];if(r==null)continue;if(r.itemSchema!=null)return!0}return!1}function WaA(e){return e.includes("json")||e==="*/*"}function Las({content:e,context:t}){for(let[r,n]of Object.entries(e))if(rKn({mediaType:r,mediaTypeObject:n,context:t})!=null)return[r,n]}function rKn({mediaType:e,mediaTypeObject:t,context:r}){if(!WaA(e))return;let n=t.schema;return{contentType:e.includes("*")?void 0:e,schema:n??{},examples:zfr(t,r)}}function nKn({content:e,context:t}){let r=Las({content:e,context:t});if(!r)return;let[n,i]=r;return rKn({mediaType:n,mediaTypeObject:i,context:t})}function kSl(e,t){for(let r of Object.keys(e)){let n=e[r];if(n==null)continue;return{schema:n.schema??{},examples:zfr(n,t)}}}function zfr(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let n=ni(e,sz.EXAMPLES);return n!=null&&Object.keys(n).length>0&&r.push(...Object.entries(n).map(([i,o])=>({name:o.summary??i,value:o.value,description:o.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([i,o])=>{let a=fo(o)?t.resolveExampleReference(o):o;return{name:a.summary??i,value:a.value,description:a.description}})),r}function USl(e){let t=GaA(e),r={};return Was({obj:t,occurrences:r,breadcrumbs:[]}),r}function Was({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let n of e)Was({obj:n,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let n=e.$ref;t[n]==null?t[n]=1:t[n]+=1;return}for(let n in e)Was({obj:e[n],occurrences:t,breadcrumbs:[...r,n]})}}}function GaA(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?iXr(r.get):void 0,put:r?.put!=null?iXr(r.put):void 0,post:r?.post!=null?iXr(r.post):void 0,patch:r?.patch!=null?iXr(r.patch):void 0,delete:r?.delete!=null?iXr(r.delete):void 0}]))}}function iXr(e){return{...e,requestBody:e.requestBody!=null?fo(e.requestBody)?e.requestBody:HaA(e.requestBody):void 0}}function HaA(e){let t,r;for(let n in e.content){let i=SA.parse(n);i!=null&&(i.isJSON()?t=e.content[n]:i.isMultipart()&&(r=e.content[n]))}return r!=null&&t!=null?{...e,content:{[SA.MULTIPART_FORM_DATA]:r}}:e}var iKn=class{endpoints;parser=new Vot;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let n=[];for(let i of r){let o=this.parser.tryParse(i);if(o==null){t.logger.debug(`Ignoring configured filter endpoint "${i}"; expected format "POST /users/get"`);continue}n.push(`${o.method} ${o.path}`)}return n}};var LSl="#/components/parameters/",WSl="#/components/responses/",GSl="#/components/examples/",HSl="#/components/requestBodies/",$Sl="#/components/securitySchemes/",Qfr=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;schemaNamespaceMapping;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:a}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=n,this.refOccurrences=USl(t),this.options=i,this.source=o,this.filter=new iKn({context:r,options:i}),this.DUMMY=this.getDummy(),this.namespace=a,this.schemaNamespaceMapping=this.buildSchemaNamespaceMapping()}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};r.push(n)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return{"x-fern-type":"unknown"};if(Array.isArray(n)){let o=parseInt(i,10);if(isNaN(o)||o<0||o>=n.length)return{"x-fern-type":"unknown"};n=n[o]}else n=n[i]}return n==null?(this.logger.debug(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(fo(n)&&(n=this.resolveSchemaReference(n)),n)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(LSl))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(LSl.length),n=this.document.components.parameters[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return fo(n)?this.resolveParameterReference(n):n}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(HSl))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(HSl.length),n=this.document.components.requestBodies[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return fo(n)?this.resolveRequestBodyReference(n):n}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(WSl))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(WSl.length),n=this.document.components.responses[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return fo(n)?this.resolveResponseReference(n):n}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(GSl))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(GSl.length),n=this.document.components.examples[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return fo(n)?this.resolveExampleReference(n):n}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith($Sl))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring($Sl.length),n=this.document.components.securitySchemes[r];if(n==null)throw new Error(`${t.$ref} is undefined`);return fo(n)?this.resolveSecuritySchemeReference(n):n}referenceExists(t){let r=t.substring(2).split("/").map(i=>i.replace(/~1/g,"/")),n=this.document;for(let i of r){if(typeof n!="object"||n==null)return!1;n=n[i]}return!0}getNamespace(t){return this.schemaNamespaceMapping?.get(t)}buildSchemaNamespaceMapping(){let t=new Map;if(!this.document.components?.schemas)return t;for(let[r,n]of Object.entries(this.document.components.schemas))!n||fo(n)||t.set(r,ni(n,wi.SDK_NAMESPACE)||this.namespace);return t}};var oLt=class extends Qfr{constructor({document:t,taskContext:r,options:n,source:i,namespace:o}){super({document:t,taskContext:r,authHeaders:new Set,options:n,source:i,namespace:o})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,n){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,n){}getDiscriminatedUnionMetadata(t){}};var oKn=require("fs"),aKn=require("path");var $aA=Lt.object({lang:Lt.string(),label:Lt.optional(Lt.string()),source:Lt.string()}),Gas=Lt.array($aA);var JSl={README_EXT:"x-readme"};function JaA(e){if(!Array.isArray(e))return!1;for(let t of e)if(!Hc(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function KSl(e){let t=ni(e,JSl.README_EXT);if(!Hc(t))return[];let r=t["code-samples"];if(!JaA(r))return[];let n=[];for(let i of r)n.push({name:i.name,language:i.language,code:i.code,install:i.install,docs:void 0});return n}function KaA(e){return Hc(e)&&typeof e.$ref=="string"}function YaA(e,t){if(e!=null){if(typeof e=="string")return e;if(KaA(e)){let r=(0,aKn.resolve)(t??process.cwd(),e.$ref);if((0,oKn.existsSync)(r))try{return(0,oKn.readFileSync)(r,"utf-8")}catch{return}}}}function XaA(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!Hc(n))continue;let o=YaA(n.code,t);o!=null&&r.push({...n,code:o})}return r}function YSl(e,t,r){let n=ni(t,wi.EXAMPLES),i=r.source.type==="openapi"?(0,aKn.dirname)(r.source.file):void 0,a=(n??[]).map(p=>{if(!Hc(p))return p;let m=p["code-samples"];if(m!=null){let h=XaA(m,i);return{...p,"code-samples":h}}return p}).filter(p=>{let d=zj.serialization.ExampleEndpointCallSchema.parse(p);return d.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),d.ok}),s=XYr(t,sz.REDOCLY_CODE_SAMPLES_KEBAB,Gas,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],l=[...XYr(t,sz.REDOCLY_CODE_SAMPLES_CAMEL,Gas,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...s];l.length>0&&a.push({"code-samples":l.map(p=>({name:p.label??p.lang,language:p.lang,code:p.source,install:void 0,docs:void 0}))});let u=KSl(t);return u.length>0&&a.push({"code-samples":u}),a.map(rre.unknown)}function XSl(e){let t=ni(e,wi.AVAILABILITY);if(t==="ga"||t==="generally-available")return jR.GenerallyAvailable;if(t==="beta"||t==="pre-release")return jR.Beta;if(t==="deprecated")return jR.Deprecated;if(e.deprecated)return jR.Deprecated}function ZSl(e){let t=ni(e,wi.RETRIES);if(t!=null&&t.disabled===!0)return _Hn.RetriesConfiguration.disabled(t.disabled)}var ZaA="x-fern-default-url";function sKn(e,t){let r=e.variables!=null&&Object.keys(e.variables).length>0,n=esA(e);return{url:rsA({url:e.url,variables:e.variables??{}}),description:e.description,name:nsA(e,t),audiences:ni(e,wi.AUDIENCES),urlTemplate:r?e.url:void 0,variables:r&&e.variables!=null?tsA(e.variables):void 0,defaultUrl:r?n:void 0}}function esA(e){let t=e[ZaA];if(typeof t=="string")return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}function tsA(e){return Object.entries(e).map(([t,r])=>({id:t,default:r.default,values:r.enum}))}function rsA({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([n,i])=>[n,i.default]));for(let[n,i]of Object.entries(r))e=e.replace(`{${n}}`,encodeURIComponent(i));return e}function nsA(e,t){let r=ni(e,[wi.SERVER_NAME_V1,wi.SERVER_NAME_V2]);if(r!=null)return r;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox";if(t?.groupMultiApiEnvironments&&e.description!=null&&e.description.trim()!==""){let n=e.description.toLowerCase();return n==="prd"?"Production":n==="sbx"?"Sandbox":n==="staging"||n==="stg"?"Staging":n==="development"||n==="dev"?"Development":e.description}}function eBl(e){return ni(e,wi.PARAMETER_NAME)}function tBl(e){return ni(e,wi.SDK_VARIABLE)}function uKn({path:e,httpMethod:t,parameters:r,context:n,requestBreadcrumbs:i,source:o}){let a={pathParameters:[],queryParameters:[],headers:[]};for(let s of r){let c=fo(s)?n.resolveParameterReference(s):s,l=ni(s,wi.IGNORE)??ni(c,wi.IGNORE);if(l!=null&&l){n.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let u=c.required??!1,p=rq(c),d=[...i,c.name],m=HC(d,n.options.preserveSchemaIds),[h,y]=n.options.coerceOptionalSchemasToNullable?[!1,!u]:[!u,!1],g=c.schema!=null?El(c.schema,h,y,n,d,o,n.namespace,!1,new Set,xMe({schema:c,logger:n.logger})):u?Bn.primitive({nameOverride:void 0,generatedName:m,title:void 0,schema:Yo.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:xMe({schema:c,logger:n.logger})}),description:void 0,availability:p,namespace:void 0,groupName:void 0}):Bn.optional({nameOverride:void 0,generatedName:m,title:void 0,value:Bn.primitive({nameOverride:void 0,generatedName:m,title:void 0,schema:Yo.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:xMe({schema:c,logger:n.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:p,namespace:void 0,groupName:void 0,inline:void 0});if(c.in==="header"&&c.schema!=null&&!fo(c.schema)&&c.schema.default!=null){let _=c.schema.default;typeof _=="string"&&_.length>0&&(g=Bn.literal({nameOverride:void 0,generatedName:m,title:void 0,value:WP.string(_),description:void 0,availability:p,namespace:void 0,groupName:void 0}))}let b={name:c.name,schema:g,description:c.description,parameterNameOverride:eBl(c),availability:p,source:o};c.in==="query"?a.queryParameters.push({...b,explode:osA(c)}):c.in==="path"?a.pathParameters.push({...b,variableReference:tBl(c),explode:asA(c)}):c.in==="header"?!isA.has(c.name.toLowerCase())&&!n.authHeaders.has(c.name)?a.headers.push({...b,env:void 0}):n.logger.debug(`Ignoring ${c.name} header, in ${t.toUpperCase()} ${e}`):n.logger.warn(`Skipping ${c.in} parameter, ${c.name}, in ${t.toUpperCase()} ${e}`)}return a}var isA=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function osA(e){let t=e.style??"form",r=e.explode;if(r!==void 0)return t==="form"?r===!0?void 0:r:r===!1?void 0:r}function asA(e){let t=e.explode;if(t!==void 0)return t===!1?void 0:t}function ssA({content:e,context:t}){for(let[r,n]of Object.entries(e))if(nBl({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function nBl({mediaType:e,mediaTypeObject:t,context:r}){if(SA.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:zfr(t,r)}}function usA({content:e,context:t}){for(let[r,n]of Object.entries(e))if(iBl({mediaType:r,mediaTypeObject:n,context:t}))return[r,n]}function iBl({mediaType:e,mediaTypeObject:t,context:r}){if(SA.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding,examples:zfr(t,r)}}function oBl({mediaType:e}){return SA.parse(e)?.isBinary()??!1}function csA({content:e}){for(let[t,r]of Object.entries(e))if(oBl({mediaType:t}))return[t,r]}function lsA(e,t){let r=fo(e)?Has(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([n,i])=>!fo(i)&&i.type==="string"&&i.format==="binary")!=null}function lKn({content:e,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:a}){let s=csA({content:e});if(s){let[d,m]=s;return CMe({mediaType:d,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:a})}let c=usA({content:e,context:n}),l=Las({content:e,context:n}),u=psA({json:l,multipart:c,document:r,visitor:{json:([d,m])=>CMe({mediaType:d,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:a}),multipart:([d,m])=>CMe({mediaType:d,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:a}),neither:()=>{}}});if(u)return u;let p=ssA({content:e,context:n});if(p){let[d,m]=p;return CMe({mediaType:d,mediaTypeObject:m,description:t,document:r,context:n,requestBreadcrumbs:i,source:o,namespace:a})}}function psA({json:e,multipart:t,document:r,visitor:n}){if(!e&&!t)return n.neither();let[,i]=e??[void 0,void 0],[,o]=t??[void 0,void 0];return!i?.schema&&!o?.schema?n.neither():i?.schema&&o?.schema?i.schema&&lsA(i.schema,r)?n.multipart(t):n.json(e):i?.schema?n.json(e):o?.schema?n.multipart(t):n.neither()}function CMe({mediaType:e,mediaTypeObject:t,description:r,document:n,context:i,requestBreadcrumbs:o,source:a,namespace:s}){let c=fsA({mediaTypeObject:t});if(oBl({mediaType:e}))return DU.octetStream({description:r,source:a,sdkMethodName:c,contentType:e});let l=iBl({mediaType:e,mediaTypeObject:t,context:i}),u=l?.schema,p=l?.encoding,d=l?.examples;if(u){let y=fo(u)?Has(u,n):{id:void 0,schema:u},g=El(y.schema,!1,!1,i,o,a,s,!1),b=[];if(g.type==="object"){let _=new Set(y.schema.required??[]);for(let O of g.properties){let A=_.has(O.key),{isFile:v,isOptional:P,isArray:I,description:E}=cKn({schema:O.schema,isOptional:!A});if(v){let x=rBl(O.key,p);b.push({key:O.key,schema:AMe.file({isOptional:P,isArray:I,description:E}),description:E,contentType:x,exploded:!1,encoding:x==null?i.options.defaultFormParameterEncoding:void 0})}else{let x=rBl(O.key,p);b.push({key:O.key,schema:AMe.json(O.schema),description:void 0,contentType:x,exploded:p?.[O.key]?.explode,encoding:x==null?i.options.defaultFormParameterEncoding:msA(x)})}}}return DU.multipart({name:fo(u)&&i.getNumberOfOccurrencesForRef(u)===1?y.id:void 0,description:y.schema.description,properties:b,source:a,sdkMethodName:c,fullExamples:d})}let m=rKn({mediaType:e,mediaTypeObject:t,context:i});if(m){let y=El(m.schema,!1,!1,i,o,a,s,!0);return DU.json({description:void 0,schema:y,contentType:m.contentType,fullExamples:m.examples,additionalProperties:!fo(m.schema)&&eXr(m.schema.additionalProperties,i.options),source:a,sdkMethodName:c})}let h=nBl({mediaType:e,mediaTypeObject:t,context:i});if(h!=null&&h.schema!=null){let y=El(h.schema,!1,!1,i,o,a,s,!1);return DU.formUrlEncoded({schema:y,description:r,contentType:h.contentType,source:a,fullExamples:h.examples,additionalProperties:!1,sdkMethodName:c})}}function fsA({mediaTypeObject:e}){return ni(e,wi.SDK_METHOD_NAME)}var dsA={"application/json":"json"};function msA(e){return e?dsA[e]:void 0}function Has(e,t){if(!e.$ref.startsWith(nLt))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=Bgt(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let n=t.components?.schemas?.[r];if(n==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return fo(n)?Has(n,t):{id:r,schema:n}}function cKn({schema:e,isOptional:t,isArray:r,description:n}){return ysA(e)?cKn({schema:e.value,isOptional:!0,isArray:r,description:e.description}):gsA(e)?cKn({schema:e.value,isOptional:t,isArray:r,description:e.description}):bsA(e)?cKn({schema:e.value,isOptional:t,isArray:!0,description:e.description}):hsA(e)?{isFile:!0,isOptional:t??!1,isArray:r??!1,description:n??e.description}:{isFile:!1,isOptional:t??!1,isArray:r??!1,description:void 0}}function hsA(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function ysA(e){return e.type==="optional"}function gsA(e){return e.type==="nullable"}function bsA(e){return e.type==="array"}function rBl(e,t){return t?.[e]?.contentType}var $as={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},aBl=new Set(Object.values($as));var AsA=["200","201","202","204"];function pKn({operationContext:e,responses:t,context:r,responseBreadcrumbs:n,responseStatusCode:i,streamFormat:o,source:a}){if(t==null)return{value:void 0,errors:{}};let s=_sA({responses:t,context:r,source:a,namespace:r.namespace}),c=!1,l;for(let u of i!=null?[i]:AsA){let p=t[u];p!=null&&(c=!0,l==null&&(l=sBl({operationContext:e,response:p,context:r,responseBreadcrumbs:n,streamFormat:o,source:a,namespace:r.namespace,statusCode:typeof u=="string"?parseInt(u):u})))}if(l==null&&!c&&t.default!=null&&(l=sBl({operationContext:e,response:t.default,context:r,responseBreadcrumbs:n,streamFormat:o,source:a,namespace:r.namespace})),l!=null)switch(l.type){case"json":return{value:l,errors:s};case"streamingJson":case"streamingSse":return{value:l,errors:s};case"bytes":case"file":case"text":case"streamingText":return{value:l,errors:s};default:qe(l)}return{value:void 0,errors:s}}function sBl({operationContext:e,streamFormat:t,response:r,context:n,responseBreadcrumbs:i,source:o,namespace:a,statusCode:s}){let c=fo(r)?n.resolveResponseReference(r):r;if(c.content!=null&&Object.entries(c.content).find(([d,m])=>{if(m.schema==null)return!1;let h=fo(m.schema)?n.resolveSchemaReference(m.schema):m.schema;return h.type==="string"&&h.format==="binary"}))return n.options.useBytesForBinaryResponse&&t==null?Gw.bytes({description:c.description,source:o,statusCode:s}):Gw.file({description:c.description,source:o,statusCode:s});let l=qSl(c.content??{},n);if(l!=null&&t!=null)switch(t){case"json":return Gw.streamingJson({statusCode:s,description:c.description,responseProperty:ni(e.operation,wi.RESPONSE_PROPERTY),fullExamples:l.examples,schema:El(l.schema,!1,!1,n,i,o,a),source:o});case"sse":return Gw.streamingSse({description:c.description,responseProperty:void 0,fullExamples:l.examples,schema:El(l.schema,!1,!1,n,i,o,a),source:o,statusCode:s})}let u=nKn({context:n,content:c.content??{}});if(u){if(t!=null)switch(t){case"json":return Gw.streamingJson({description:c.description,responseProperty:void 0,fullExamples:u.examples,schema:El(u.schema,!1,!1,n,i,o,a),source:o,statusCode:s});case"sse":return Gw.streamingSse({description:c.description,responseProperty:void 0,fullExamples:u.examples,schema:El(u.schema,!1,!1,n,i,o,a),source:o,statusCode:s})}return Gw.json({description:c.description,schema:El(u.schema,!1,!1,n,i,o,a),responseProperty:ni(e.operation,wi.RESPONSE_PROPERTY),fullExamples:u.examples,source:o,statusCode:s})}for(let[p,d]of Object.entries(c.content??{})){let m=SA.parse(p);if(m!=null){if(m.isOctetStream()||m.isPDF()||m.isAudio()||m.isImage()||m.isVideo()||m.isMultiPartMixed())return Gw.file({description:c.description,source:o,statusCode:s});if(m.isPlainText()){let h=d.schema;if(h==null)return Gw.text({description:c.description,source:o,statusCode:s});let y=fo(h)?n.resolveSchemaReference(h):h;return y.type==="string"&&y.format==="byte"?Gw.file({description:c.description,source:o,statusCode:s}):Gw.text({description:c.description,source:o,statusCode:s})}}}}function _sA({responses:e,context:t,source:r,namespace:n}){let i={};for(let[o,a]of Object.entries(e)){if(o==="default")continue;let s=parseInt(o);if(s<400||s>600)continue;let c=fo(a)?t.resolveResponseReference(a):a,l=kSl(c.content??{},t),u=$as[s];if(u==null){t.logger.warn(`No error name found for status code ${o}`);continue}i[s]={statusCode:s,nameOverride:void 0,generatedName:u,description:c.description,schema:El(l?.schema??{},!1,!1,t,[u,"Body"],r,n),fullExamples:l?.examples,source:r}}return i}function uat({operationContext:e,context:t,responseStatusCode:r,suffix:n,streamFormat:i,source:o}){let{document:a,operation:s,path:c,method:l,baseBreadcrumbs:u}=e,p=ni(s,wi.IDEMPOTENT),d=ni(s,[wi.REQUEST_NAME_V1,wi.REQUEST_NAME_V2]),m=[...u,"Request"],h=uKn({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:m,path:c,httpMethod:l,source:o}),y=/{([^}]+)}/g,g=[...c.matchAll(y)].map(T=>T[1]).filter(T=>T!==void 0),b=[...c.matchAll(y)].map(T=>T[1]);switch(t.options.pathParameterOrder){case vi.PathParameterOrder.SpecOrder:{let T=b.filter(W=>!h.pathParameters.some(H=>H.name===W));if(T.length>0)for(let W of T)h.pathParameters.push({name:W??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:o,schema:Bn.primitive({schema:Yo.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0})}break;case vi.PathParameterOrder.UrlOrder:if(g.length>0){let T=new Map(h.pathParameters.map(G=>[G.name,G])),W=[],H=new Set;for(let G of g){let ie=T.get(G);H.add(G),ie?W.push(ie):W.push({name:G,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:o,schema:Bn.primitive({schema:Yo.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0})}for(let G of h.pathParameters)H.has(G.name)||W.push(G);h.pathParameters=W}break;default:qe(t.options.pathParameterOrder)}let _=(()=>{if(e.method==="GET")return[void 0];if(!s.requestBody)return[void 0];let T=fo(s.requestBody)?t.resolveRequestBodyReference(s.requestBody):s.requestBody,W=Object.values(T.content).every(G=>OsA({mediaTypeObject:G})!=null),H=[];if(W)return H.push(...Object.entries(T.content).map(([G,ie])=>{let oe=CMe({mediaType:G,mediaTypeObject:ie,description:T.description,document:a,context:new oLt({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:m,source:o,namespace:t.namespace});return uBl({context:t,convertedParameters:h})&&oe!=null&&(oe.type==="json"||oe.type==="formUrlEncoded")&&oe.schema.type!=="object"&&s.requestBody!=null?oe=CMe({mediaType:G,mediaTypeObject:ie,description:T.description,document:a,context:t,requestBreadcrumbs:[...m,"Body"],source:o,namespace:t.namespace}):s.requestBody!=null&&(oe=CMe({mediaType:G,mediaTypeObject:ie,description:T.description,document:a,context:t,requestBreadcrumbs:[...m],source:o,namespace:t.namespace})),oe}).filter(G=>G!=null)),H.length===0?[void 0]:H;{let G=lKn({content:T.content,description:T.description,document:a,context:new oLt({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:m,source:o,namespace:t.namespace});return uBl({context:t,convertedParameters:h})&&G!=null&&(G.type==="json"||G.type==="formUrlEncoded")&&G.schema.type!=="object"&&s.requestBody!=null?G=lKn({content:T.content,description:T.description,document:a,context:t,requestBreadcrumbs:[...m,"Body"],source:o,namespace:t.namespace}):s.requestBody!=null&&(G=lKn({content:T.content,description:T.description,document:a,context:t,requestBreadcrumbs:[...m],source:o,namespace:t.namespace})),[G]}})(),O=_.length>1,A=[...u,"Response"],v=pKn({operationContext:e,streamFormat:i,responses:s.responses,context:t,responseBreadcrumbs:A,responseStatusCode:r,source:o}),P=ZSl(s),I=XSl(s),E=YSl(e,s,t),x=ni(s,wi.SERVER_NAME_V2);return _.map(T=>({summary:s.summary,internal:ni(s,sz.INTERNAL),idempotent:p,audiences:ni(s,wi.AUDIENCES)??[],operationId:s.operationId!=null&&n!=null?s.operationId+"_"+n:s.operationId,tags:t.resolveTagsToTagIds(s.tags),namespace:t.namespace,sdkName:wsA({operationContext:e,request:T}),pathParameters:h.pathParameters,queryParameters:h.queryParameters,headers:h.headers,requestNameOverride:d??void 0,generatedRequestName:HC(O?vsA({breadcrumbs:m,request:T}):m,t.options.preserveSchemaIds),request:T,response:v.value,errors:v.errors,servers:x!=null?[{name:x,url:void 0,audiences:void 0}]:(s.servers??[]).map(W=>sKn(W,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:s.description,authed:EsA(s,a),security:PsA(s),availability:I,method:l,path:c,examples:E,pagination:e.pagination,source:o,retries:P}))}function vsA({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function OsA({mediaTypeObject:e}){return ni(e,wi.SDK_METHOD_NAME)}function wsA({operationContext:e,request:t}){return!t||!t.sdkMethodName?e.sdkMethodName:e.sdkMethodName?{groupName:[...e.sdkMethodName.groupName],methodName:t.sdkMethodName??e.sdkMethodName.methodName}:{groupName:[],methodName:t.sdkMethodName}}function PsA(e){return e.security}function EsA(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function uBl({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function lBl({operationContext:e,context:t,asyncExtension:r,source:n}){let{operation:i,pathItemParameters:o,operationParameters:a}=e,s=r.discriminant.name,c=r.discriminant.value,l=r["response-status-code"],u=cBl({context:t,headerToIgnore:s,parameters:o}),p=cBl({context:t,headerToIgnore:s,parameters:a}),d=uat({operationContext:{...e,pathItemParameters:u,operationParameters:p,operation:{...i,responses:Object.fromEntries(Object.entries(i.responses).filter(([h])=>parseInt(h)!==l))}},context:t,streamFormat:void 0,source:n}),m=uat({operationContext:{...e,pathItemParameters:u,operationParameters:p,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:l,streamFormat:void 0,source:n});return m.forEach(h=>{h.headers.push({name:s,schema:Bn.literal({nameOverride:void 0,generatedName:HC([s],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:WP.string(c),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:n})}),{sync:d,async:m}}function cBl({context:e,headerToIgnore:t,parameters:r}){return r.filter(n=>{let i=fo(n)?e.resolveParameterReference(n):n;return!(i.in==="header"&&i.name===t)})}var Jas="stream";function mBl({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:uat({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:[]};case"streamCondition":{let n=pBl({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(n?.schemaReference!=null){let l=Bgt(n.schemaReference);l!=null&&t.excludeSchema(l)}let i=fBl({operation:e.operation,response:r.responseStream}),o=uat({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+Jas}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:n?.requestBody,responses:i},baseBreadcrumbs:[...e.baseBreadcrumbs,Jas]},context:t,streamFormat:r.format,suffix:Jas,source:t.source});o.forEach(l=>{l.examples=l.examples.filter(u=>dBl(u,t)!==!1)});let a=pBl({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),s=fBl({operation:e.operation,response:r.response}),c=uat({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:a?.requestBody,responses:s}},context:t,source:t.source});return c.forEach(l=>{l.examples=l.examples.filter(u=>dBl(u,t)!==!0)}),{streaming:o,nonStreaming:c}}default:qe(r)}}function pBl({context:e,operation:t,streamingExtension:r,isStreaming:n}){if(t.requestBody==null)return;let i=fo(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,o=nKn({content:i.content,context:e});if(o==null)return;let a=fo(o.schema)?e.resolveSchemaReference(o.schema):o.schema;if(a.allOf==null&&a.properties==null)return;let s=a.properties?.[r.streamConditionProperty];s!=null&&fo(s)&&(s=void 0);let c={...a,properties:{...a.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":n,...s??{}}},title:void 0,required:[...a.required??[],r.streamConditionProperty]};return{requestBody:{content:{[SA.APPLICATION_JSON]:{schema:c}}},schemaReference:fo(o.schema)?o.schema:void 0}}function fBl({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[SA.APPLICATION_JSON]:{schema:t}}}}}function dBl(e,t){return e._visit({unknown:r=>{let n=zj.serialization.ExampleEndpointCallSchema.parse(r);if(n.ok&&n.value.response!=null)return n.value.response.stream!=null},full:()=>{},_other:()=>{}})}var hBl=require("crypto");function yBl({context:e,operationContext:t,source:r}){let{document:n,operation:i,path:o,method:a,baseBreadcrumbs:s,sdkMethodName:c}=t,l=[...s,"Payload"],u=[...s,"Response"],p=uKn({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:l,path:o,httpMethod:a,source:r});if(i.requestBody==null)return e.logger.error(`Skipping webhook ${a.toUpperCase()} ${o}: Missing a request body`),[];let d=i.operationId??xsA({path:o,method:a,sdkMethodName:c}),m=i.responses?pKn({operationContext:t,streamFormat:void 0,responses:i.responses,context:e,responseBreadcrumbs:u,source:r}):void 0;if(a!=="POST"&&a!=="GET")return e.logger.error(`Skipping webhook ${a.toUpperCase()} ${o}: Not POST or GET`),[];let h=fo(i.requestBody)?e.resolveRequestBodyReference(i.requestBody):i.requestBody;return Object.entries(h.content).map(([y,g])=>CMe({mediaType:y,mediaTypeObject:g,description:h.description,document:n,context:e,requestBreadcrumbs:[...s,"Payload"],source:r,namespace:e.namespace})).filter(y=>y!=null).map(y=>{if(y==null||y.type!=="json"&&y.type!=="formUrlEncoded"&&y.type!=="multipart"){e.logger.error(`Skipping webhook ${o} because non-json, non-formUrlEncoded, and non-multipart request body`);return}let g,b;return y.type==="multipart"?(g={name:y.name,properties:y.properties,description:y.description,source:y.source},b=Bn.unknown({nameOverride:void 0,generatedName:HC(l,e.options.preserveSchemaIds),title:void 0,description:y.description,availability:void 0,namespace:e.namespace,groupName:void 0,example:void 0})):b=y.schema,{summary:i.summary,audiences:ni(i,wi.AUDIENCES)??[],sdkName:c,namespace:e.namespace,method:a,operationId:d,tags:e.resolveTagsToTagIds(i.tags),headers:p.headers,generatedPayloadName:HC(l,e.options.preserveSchemaIds),payload:b,multipartFormData:g,response:m?.value,description:i.description,examples:IsA(y.fullExamples),source:r}}).filter(y=>y!=null)}function IsA(e){if(e==null)return[];let t=[];for(let r of e){let n=Tgt(r.value);n!=null&&t.push({description:r.description,name:r.name,payload:n})}return t}function xsA({path:e,method:t,sdkMethodName:r}){let n=r?.methodName??jsA(e),i=(0,hBl.createHash)("sha256").update(e).digest("hex").slice(0,8);return CsA(`${n}_${t.toLowerCase()}_${i}`)}function jsA(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function CsA(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function Kas({context:e,pathItemContext:t,operation:r,convertToWebhook:n}){let i=ni(r,wi.IGNORE);if(i!=null&&i){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let o=SsA(r,e),a=QSl(e.document,r),s={...t,sdkMethodName:o,baseBreadcrumbs:BsA({operation:r,sdkMethodName:o,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:a};if(n)return{type:"webhook",value:yBl({context:e,operationContext:s,source:e.source})};let c=MSl(r);if(c==null&&DsA({operation:r,context:e})&&(c={type:"stream",format:"sse"}),c!=null){let p=mBl({context:e,operationContext:s,streamingExtension:c});return p!=null?{type:"streaming",streaming:p.streaming,nonStreaming:p.nonStreaming}:void 0}let l=FSl(r);if(l!=null){let p=lBl({context:e,operationContext:s,asyncExtension:l,source:e.source});return{type:"async",async:p.async,sync:p.sync}}return{type:"http",value:uat({context:e,operationContext:s,streamFormat:void 0,source:e.source})}}function SsA(e,t){let r=ni(e,wi.SDK_METHOD_NAME),n=ni(e,wi.SDK_GROUP_NAME)??[];if(r!=null){let i=typeof n=="string"?[n]:n;return i=t.resolveGroupName(i),{groupName:i,methodName:r}}}function BsA({sdkMethodName:e,operation:t,httpMethod:r,path:n,shouldUseIdiomaticRequestNames:i}){let o=[];if(e!=null){if(i&&o.push(e.methodName),e.groupName.length>0){let a=e.groupName[e.groupName.length-1];a!=null&&o.push(typeof a=="string"?a:a.name)}i||o.push(e.methodName)}else t.operationId!=null?o.push(t.operationId):o.push(Xi(`${r}_${n.split("/").join("_")}`));return o}function DsA({operation:e,context:t}){if(e.responses==null)return!1;for(let r of Object.values(e.responses)){let n=fo(r)?t.resolveResponseReference(r):r;if(n.content!=null&&VSl(n.content))return!0}return!1}function gBl(e,t,r,n){let i=[],o=ABl(t),a={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let s of o){if(n.filter.skipEndpoint({method:s.method,path:e})){n.logger.debug(`Skipping endpoint "${s.method} ${e}"`);continue}let c=TsA({operation:s.operation}),l=Kas({context:n,pathItemContext:{...a,method:s.method},operation:s.operation,convertToWebhook:c});l&&i.push(l)}return i}function bBl(e,t,r,n){let i=[],o=ABl(t),a={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let s of o){if(n.filter.skipEndpoint({method:s.method,path:e})){n.logger.debug(`Skipping endpoint "${s.method} ${e}"`);continue}let c=Kas({context:n,pathItemContext:{...a,method:s.method},operation:s.operation,convertToWebhook:!0});c&&i.push(c)}return i}function ABl(e){let t=[];return e.get!=null&&t.push({method:CR.Get,operation:e.get}),e.post!=null&&t.push({method:CR.Post,operation:e.post}),e.put!=null&&t.push({method:CR.Put,operation:e.put}),e.delete!=null&&t.push({method:CR.Delete,operation:e.delete}),e.patch!=null&&t.push({method:CR.Patch,operation:e.patch}),e.head!=null&&t.push({method:CR.Head,operation:e.head}),t}function TsA({operation:e}){return ni(e,[wi.WEBHOOK])??!1}function _Bl(e){let t=ni(e,wi.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=ni(e,wi.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function vBl(e){return ni(e,wi.FERN_BASIC_AUTH)}function wBl(e,t,r,n){if(fo(e)){if(n==null)throw new Error(`Converting referenced security schemes requires context: ${JSON.stringify(e)}`);let i=n.resolveSecuritySchemeReference(e);return OBl(i,t,r)}return OBl(e,t,r)}function OBl(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let n=ni(e,sz.BEARER_FORMAT),i=ni(e,wi.FERN_HEADER_AUTH);return xR.header({headerName:e.name,prefix:n!=null?"Bearer":i?.prefix,headerVariableName:i?.name??ni(e,wi.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let n=ni(e,wi.FERN_BEARER_TOKEN);return xR.bearer({tokenVariableName:n?.name??ni(e,wi.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:n?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let n=vBl(e),i=_Bl(e);return xR.basic({usernameVariableName:n?.username?.name??i.usernameVariable,usernameEnvVar:n?.username?.env,passwordVariableName:n?.password?.name??i.passwordVariable,passwordEnvVar:n?.password?.env})}else{if(e.type==="openIdConnect")return xR.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return xR.oauth({scopesEnum:RsA(e,t)})}}catch(n){r.logger.debug(`Error converting security scheme: ${n?.message}`)}r.logger.debug(`Skipping security scheme: ${JSON.stringify(e,null)} - not currently supported. Please reach out to Fern support team!`)}function RsA(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let n=Sgt({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([o,a])=>[o,{description:a}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsOptional:!1,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),i=MA(n);if(i.type==="enum")return i}}function PBl(e){return ni(e,wi.BASE_PATH)}var FsA=Lt.record(Lt.string(),Lt.object({summary:Lt.string().optional(),description:Lt.string().optional()}));function EBl({document:e,context:t}){return XYr(e,wi.GROUPS,FsA,t.logger)}function IBl({context:e,document:t}){return ni(t,wi.FERN_VERSION)??void 0}function xBl(e){let t=ni(e,wi.FERN_GLOBAL_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?ZYr({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function jBl(e){let t=ni(e,wi.FERN_IDEMPOTENCY_HEADERS),r=[];for(let n of t??[])r.push({...n,schema:n.type!=null?ZYr({fernType:n.type,description:void 0,availability:void 0,generatedName:n.name??n.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function CBl(e,t){let r=ni(e,wi.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([n,i])=>{if(i.type==="string")return[n,{nameOverride:void 0,generatedName:HC([n],t),title:i.title,schema:Ph.string({default:Tfr(i),pattern:i.pattern,format:i.format,minLength:i.minLength,maxLength:i.maxLength}),description:i.description,availability:void 0,namespace:void 0,groupName:void 0}];throw new Error(`Variable ${n} has unsupported schema ${JSON.stringify(i)}`)}))}var NsA="webhooks";function SBl(e){return ni(e,NsA)??{}}var oXr=class extends Qfr{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:a}){super({document:t,taskContext:r,authHeaders:n,options:i,source:o,namespace:a})}getDummy(){return new oLt({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,n){let i=this.discriminatedUnionReferences[t.$ref];i!=null?(i.discriminants.add(r),i.numReferences+=n):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:n}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,n){let i=this.discriminatedUnionMetadata[t.$ref];i!=null?i.discriminants.set(r,n):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,n]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function BBl(e){return ni(e,wi.RESOLUTIONS)}function DBl({openapi:e}){let t=BBl(e);if(t==null)return e;let r={};for(let n of t){let i=`#/components/schemas/${n.name}`;for(let o of n.resolutions)e=MsA({openapi:e,schemaReference:o,schemaName:n.name}),e=TBl({openapi:e,replaceReference:o,schemaReference:i,replacedReferences:r}),r={...r,...Object.fromEntries(n.resolutions.map(a=>[i,a]))}}return e}function MsA({openapi:e,schemaReference:t,schemaName:r}){let n=t.replace("#/","").split("/").map(o=>o.replaceAll("~1","/")),i=e;for(let o of n){let a=i[o];if(a==null)return e;i=a}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=i,e}function TBl({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:n}){let i=Object.keys(n).filter(c=>t.startsWith(c)).sort((c,l)=>l.length-c.length)[0];if(i!=null){let c=n[i];if(c!=null){let l=r.replace(i,c);return TBl({openapi:e,replaceReference:t,schemaReference:l,replacedReferences:{}})}}let o=t.replace("#/","").split("/").map(c=>c.replaceAll("~1","/")),a=e;for(let c of o.slice(0,-1)){let l=a[c];if(l==null)return e;a=l}let s=o[o.length-1];return s==null||(a[s]={$ref:r}),e}function FBl({openApi:e,taskContext:t,options:r,source:n,namespace:i}){e=DBl({openapi:e}),$Jn();let o=new oXr({document:e,taskContext:t,authHeaders:new Set,options:r,source:n,namespace:i}),a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([W,H])=>{let G=wBl(H,n,t,o);return G==null?null:[W,G]}).filter(W=>W!==null)),s=e.security?.filter(W=>W!=null),c=new Set(...Object.entries(a).map(([W,H])=>H.type==="basic"||H.type==="bearer"?"Authorization":H.type==="header"?H.headerName:null)),l=CBl(e,r.preserveSchemaIds),u=xBl(e),p=jBl(e),d=r.audiences??[],m=[],h=[],y=new oXr({document:e,taskContext:t,authHeaders:c,options:r,source:n,namespace:i});y.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([W,H])=>{if(H==null)return;let G=gBl(W,H,e,y);for(let ie of G){let oe=RBl({operation:ie});if(!(d.length>0&&!d.some($=>oe.includes($))))switch(ie.type){case"async":m.push(...ie.sync),m.push(...ie.async);break;case"http":m.push(...ie.value);break;case"streaming":m.push(...ie.streaming),ie.nonStreaming&&m.push(...ie.nonStreaming);break;case"webhook":h.push(...ie.value);break;default:qe(ie)}}}),Object.entries(SBl(e)).forEach(([W,H])=>{if(H==null)return;t.logger.debug(`Converting path ${W}`);let G=bBl(W,H,e,y);for(let ie of G){let oe=RBl({operation:ie});d.length>0&&!d.some($=>oe.includes($))||h.push(...ie.value)}});let g=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([W,H])=>{let G=ni(H,wi.SDK_NAMESPACE);if(!fo(H)){let ie=ni(H,wi.IGNORE);if(ie!=null&&ie)return[];if(aBl.has(W))return[W,El({...H,"x-fern-type-name":`${W}Body`},!1,!1,y,[W],n,G??i)]}return[W,El(H,!1,!1,y,[W],n,G??i)]}).filter(W=>W.length>0)),b=zsA(g,y,n),_=QsA(b,y),O=IMe(),A={};for(let[W,H]of Object.entries(_)){let G=MA(H);if(y.isSchemaExcluded(W))continue;let ie=O.getUniqueSchemaId(W,y.logger,r.resolveSchemaCollisions);A[ie]=G}let v=new Rgt(_,y.nonRequestReferencedSchemas,y),P=h.map(W=>{let G=W.examples;if(!r.disableExamples&&G.length===0){let ie=v.buildExample({schema:W.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});ie!=null&&(G=[{name:void 0,description:void 0,payload:ie}])}return{...W,payload:MA(W.payload),examples:G}}),I=new YJn(_,y,u),E=m.map(W=>{let H=W.examples,G=H;if(!r.disableExamples&&(H.length===0||H.every(nXr))){let $=I.buildEndpointExample(W);$.length>0&&(G=[...$,...H.filter(te=>!nXr(te))])}let ie=W.request,oe=W.response;return{...W,request:ie?.type==="json"||ie?.type==="formUrlEncoded"?{...ie,schema:MA(ie.schema)}:ie,response:oe?.type==="json"?{...oe,schema:MA(oe.schema)}:oe,queryParameters:W.queryParameters.map($=>({description:$.description,name:$.name,schema:MA($.schema),parameterNameOverride:$.parameterNameOverride,availability:$.availability,source:$.source})),pathParameters:W.pathParameters.map($=>({description:$.description,name:$.name,schema:MA($.schema),parameterNameOverride:$.parameterNameOverride,variableReference:$.variableReference,availability:$.availability,source:$.source})),headers:W.headers.map($=>({description:$.description,name:$.name,schema:MA($.schema),parameterNameOverride:$.parameterNameOverride,env:$.env,availability:$.availability,source:$.source})),examples:G,errors:Mi(W.errors,$=>{let te=$.fullExamples?.map(Ge=>{let Ke=Tgt(Ge.value);if(Ke!=null)return{name:Ge.name,description:Ge.description,example:Ke}}).filter(Gu);if(te?.length===0){let Ge=v.buildExample({schema:$.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Ge!=null&&te.push({name:void 0,description:void 0,example:Ge})}return{generatedName:$.generatedName,nameOverride:$.nameOverride,schema:MA($.schema),description:$.description,source:$.source,examples:te}}),retries:W.retries}});I.finalize();let x=EBl({document:e,context:y});return{apiVersion:IBl({context:y,document:e}),basePath:PBl(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(x??{}).map(([W,H])=>[W,{summary:H.summary??void 0,description:H.description??void 0}])),servers:(e.servers??[]).map(W=>sKn(W,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(W=>[W.name,{id:W.name,description:W.description}])),orderedTagIds:e.tags?.map(W=>W.name)},endpoints:E,webhooks:P,channels:{},groupedSchemas:Ffr(i,A),securitySchemes:a,security:s,hasEndpointsMarkedInternal:E.some(W=>W.internal),nonRequestReferencedSchemas:y.getReferencedSchemas(),variables:l,globalHeaders:u,idempotencyHeaders:p}}function zsA(e,t,r){if(t.options.removeDiscriminantsFromSchemas===vi.RemoveDiscriminantsFromSchemas.Never)return e;let n={};for(let[i,o]of Object.entries(e)){if(o.type!=="object"){n[i]=o;continue}let a={$ref:`#/components/schemas/${i}`},s=t.getReferencesFromDiscriminatedUnion(a);if(s==null){n[i]=o;continue}if(t.getReferencedSchemas().has(i)){n[i]=o;continue}let l={...o,type:"object",properties:o.properties.filter(p=>!s.discriminants.has(p.key)),allOfPropertyConflicts:o.allOfPropertyConflicts.filter(p=>!s.discriminants.has(p.propertyKey)),source:r};n[i]=l;let u=NBl({schema:o,schemas:e});for(let p of[...new Set(u)]){let d=n[p]??e[p];d==null||d.type!=="object"||(n[p]={...d,type:"object",properties:d.properties.filter(m=>!s.discriminants.has(m.key)),allOfPropertyConflicts:d.allOfPropertyConflicts.filter(m=>!s.discriminants.has(m.propertyKey))})}}return n}function QsA(e,t){let r={};for(let[n,i]of Object.entries(e)){if(i.type!=="object"){r[n]=i;continue}let o={$ref:`#/components/schemas/${n}`},a=t.getDiscriminatedUnionMetadata(o);if(a==null){r[n]=i;continue}let s=[];for(let l of i.properties)if(a.discriminants.has(l.key)){let u=a.discriminants.get(l.key);u!=null&&s.push({...l,schema:Bn.literal({nameOverride:void 0,generatedName:HC([i.generatedName,u],t.options.preserveSchemaIds),title:void 0,value:WP.string(u),namespace:void 0,groupName:void 0,description:void 0,availability:i.availability})})}else s.push(l);let c={...i,type:"object",properties:s};r[n]=c}return r}function NBl({schema:e,schemas:t}){let r=[];for(let n of e.allOf){r.push(n.schema);let i=t[n.schema];i!=null&&i.type==="object"&&r.push(...NBl({schema:i,schemas:t}))}return r}function fKn(e){return[...new Set(e)]}function RBl({operation:e}){let t=[];switch(e.type){case"async":t=fKn(e.async.flatMap(r=>r.audiences));break;case"http":t=fKn(e.value.flatMap(r=>r.audiences));break;case"streaming":t=fKn(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=fKn(e.value.flatMap(r=>r.audiences));break;default:qe(e)}return t}function aLt({context:e,documents:t,options:r}){let n={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},security:void 0,globalHeaders:[],idempotencyHeaders:[],groups:{}},i=0;for(let o of t)try{let a=o.source!=null?o.source:eq.openapi({file:"<memory>"});switch(o.type){case"openapi":{let s=FBl({taskContext:e,openApi:o.value,options:ore({options:o.settings,overrides:r}),source:a,namespace:o.namespace});n=LsA(n,s,ore({options:o.settings,overrides:r})),i++;break}case"asyncapi":{let s=RSl({document:o.value,taskContext:e,options:ore({options:o.settings,overrides:r}),source:a,asyncApiOptions:qsA({options:o.settings}),namespace:o.namespace});s.servers!=null&&(n.websocketServers=[...n.websocketServers,...s.servers.map(c=>({...c,audiences:void 0,description:void 0,defaultUrl:void 0,urlTemplate:void 0,variables:void 0}))]),s.channels!=null&&(n.channels={...n.channels,...s.channels}),s.groupedSchemas!=null&&(n.groupedSchemas=dKn(n.groupedSchemas,s.groupedSchemas,r)),s.basePath!=null&&(n.basePath=s.basePath),i++;break}default:qe(o)}}catch(a){e.logger.error(`Failed to parse ${o.type} document ${o.type==="openapi"?o.value.info?.title:o.source?.file}`),a instanceof Error&&e.logger.error(a.message,a.stack?`
|
|
1533
1533
|
`+a.stack:"")}return n}function qsA({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??YCl.naming}}function mKn(e){let t=String(e.description||e.name||e["x-fern-server-name"]||"default").trim(),r=t.toUpperCase();return r==="PRODUCTION"||r==="PRD"||r==="PROD"?"PRD":r==="SANDBOX"||r==="SBX"?"SBX":r==="STAGING"||r==="STG"?"STG":r==="PERFORMANCE"||r==="PRF"||r==="PERF"?"PRF":r==="E2E"||r==="E_2_E"?"E2E":r==="QAL"||r==="QUALITY"?"QAL":t}function Xas(e){try{let n=new URL(e).hostname.split("."),i=new Set(["api","www","service","services","example","com","org","net","io"]);for(let a of n){let s=a.split("-")[0],c=s&&s.length>2?s:a;if(c&&!i.has(c.toLowerCase())&&c.length>2)return c.toLowerCase()}let o=n[0];return o&&o.length>0?o.toLowerCase():"api"}catch{let t=e.match(/https?:\/\/([^./-]+)/);return t&&t[1]?t[1].toLowerCase():"api"}}function Yas(e,t){let r=e??[],n=t??[];if(r.length===0&&n.length===0)return;let i=new Map;for(let o of[...r,...n]){let a=Object.keys(o).sort(),s={};for(let l of a)s[l]=o[l]??[];let c=JSON.stringify(s);i.has(c)||i.set(c,o)}return Array.from(i.values())}function VsA(e,t){if(UsA(e))return!0;if(e.length===0||t.length===0||e.length!==t.length)return!1;let r=new Map;for(let o of e){if(o.type==="grouped")continue;let a=mKn(o);r.set(a,o.url)}let n=!0,i=!0;for(let o of t){if(o.type==="grouped")continue;let a=mKn(o),s=r.get(a);s?s===o.url&&(i=!1):n=!1}return n&&i}function Zas(e){return e.defaultUrl??e.url}function ksA(e){if(e.length===0||!e[0])return"api";let t=e[0];return t.type==="grouped"?Object.keys(t.urls)[0]??"api":Xas(Zas(t))}function UsA(e){return e.some(t=>t.type==="grouped")}function LsA(e,t,r){if(!(r?.groupMultiApiEnvironments===!0))return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:dKn(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:Yas(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}};if(VsA(e.servers,t.servers)){let o=[],a=[],s=ksA(t.servers),c=new Map;for(let p of e.servers)if(p.type==="grouped"){let d=p.name??"default";c.has(d)||c.set(d,{});let m=c.get(d);if(m)for(let[h,y]of Object.entries(p.urls))m[h]=y}else{let d=Xas(Zas(p)),m=mKn(p);c.has(m)||c.set(m,{});let h=c.get(m);h&&(h[d]={url:p.url,audiences:p.audiences,defaultUrl:p.defaultUrl,urlTemplate:p.urlTemplate,variables:p.variables})}for(let p of t.servers){let d=mKn(p);c.has(d)||c.set(d,{});let m=c.get(d);m&&(m[s]={url:p.url,audiences:p.audiences,defaultUrl:p.defaultUrl,urlTemplate:p.urlTemplate,variables:p.variables})}for(let[p,d]of c.entries()){let m={type:"grouped",name:p,description:`${p} environment`,urls:d};o.push(m)}let l=e.endpoints.map(p=>{let d=p.__apiName;if(d)return{...p,type:"multi-api",apiName:d,servers:[{name:d,url:void 0,audiences:void 0}]};let m=e.servers[0],h=m!=null&&m.type!=="grouped"?Xas(Zas(m)):"api";return{...p,type:"multi-api",apiName:h,servers:[{name:h,url:void 0,audiences:void 0}]}}),u=t.endpoints.map(p=>({...p,type:"multi-api",apiName:s,servers:[{name:s,url:void 0,audiences:void 0}]}));return a=[...l,...u],{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:o,websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:a.map(p=>{if(p.type==="multi-api"){let{type:h,apiName:y,servers:g,...b}=p;return{...b,__apiName:y,servers:g}}let{type:d,...m}=p;return m}),webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:dKn(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:Yas(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:dKn(e.groupedSchemas,t.groupedSchemas,r),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:Yas(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function dKn(e,t,r){let n=IMe(),i=r?.resolveSchemaCollisions??!1,o={...e.rootSchemas};for(let[a,s]of Object.entries(t.rootSchemas)){let c=n.getUniqueSchemaId(a,void 0,i);o[c]=s}e.rootSchemas=o;for(let[a,s]of Object.entries(t.namespacedSchemas))if(e.namespacedSchemas[a]!=null){let c=e.namespacedSchemas[a];for(let[l,u]of Object.entries(s)){let p=n.getUniqueSchemaId(l,void 0,i);c[p]=u}}else e.namespacedSchemas[a]=s;return e}var mVl=We(sei(),1),uei={config:new mVl.Config({apis:{},styleguide:{plugins:[Nas],rules:{struct:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!1};function Gxe({options:e,overrides:t}={}){return{...ore({options:e,overrides:t}),...J2t({options:e,overrides:t})}}var sTA={shouldUseTitleAsName:"useTitlesAsName",shouldUseUndiscriminatedUnionsWithLiterals:["shouldUseUndiscriminatedUnionsWithLiterals","discriminatedUnionV2"],shouldUseIdiomaticRequestNames:"shouldUseIdiomaticRequestNames",asyncApiMessageNaming:"asyncApiNaming",shouldUseOptionalAdditionalProperties:"optionalAdditionalProperties",coerceEnumsToLiterals:"coerceEnumsToLiterals",objectQueryParameters:"objectQueryParameters",respectReadonlySchemas:"respectReadonlySchemas",respectNullableSchemas:"respectNullableSchemas",onlyIncludeReferencedSchemas:"onlyIncludeReferencedSchemas",inlinePathParameters:"inlinePathParameters",useBytesForBinaryResponse:"useBytesForBinaryResponse",respectForwardCompatibleEnums:"respectForwardCompatibleEnums",filter:"filter",defaultFormParameterEncoding:"defaultFormParameterEncoding",exampleGeneration:"exampleGeneration",additionalPropertiesDefaultsTo:"additionalPropertiesDefaultsTo",typeDatesAsStrings:"typeDatesAsStrings",preserveSingleSchemaOneOf:"preserveSingleSchemaOneOf",inlineAllOfSchemas:"inlineAllOfSchemas",resolveAliases:"resolveAliases",groupMultiApiEnvironments:"groupMultiApiEnvironments",groupEnvironmentsByHost:"groupEnvironmentsByHost",wrapReferencesToNullableInOptional:"wrapReferencesToNullableInOptional",coerceOptionalSchemasToNullable:"coerceOptionalSchemasToNullable",removeDiscriminantsFromSchemas:"removeDiscriminantsFromSchemas",defaultIntegerFormat:"defaultIntegerFormat",pathParameterOrder:"pathParameterOrder",resolveSchemaCollisions:"resolveSchemaCollisions"};function uTA(e,t,r){r!==void 0&&(e[t]=r)}function cei(e){let t={};if(e!=null)for(let[r,n]of Object.entries(sTA)){let i=e[r],o=Array.isArray(n)?n:[n];for(let a of o)uTA(t,a,i)}return Gxe({options:t})}function kdr(e){if(e.settings==null&&e.apiOverride?.auth==null&&e.apiOverride?.["auth-schemes"]==null)return;let t={detectGlobalHeaders:!0};return e.settings?.unions==="v1"&&(t.discriminatedUnionV2=!0),e.apiOverride?.auth!=null&&(t.auth=e.apiOverride.auth),e.apiOverride?.["auth-schemes"]!=null&&(t.authSchemes=e.apiOverride["auth-schemes"]),t}function MLt(e){return e.swagger!=null}function Qfs(e){return e.openapi!=null}function lbt(e,t={}){return{...Object.fromEntries(Cx(e.namedDefinitionFiles).map(([r,n])=>[r,{...n,defaultUrl:t.defaultURL}])),...Cx(e.importedDefinitions).reduce((r,[n,i])=>({...r,...c7r(lbt(i.definition,{defaultURL:i.url}),(o,a)=>jj(n,eu.of(a)))}),{})}}function _Zr(e,t={}){return{...Object.fromEntries(Cx(e.packageMarkers).map(([r,n])=>[r,{...n,defaultUrl:t.defaultURL}])),...Cx(e.importedDefinitions).reduce((r,[n,i])=>({...r,...c7r(_Zr(i.definition,{defaultURL:i.url}),(o,a)=>jj(n,eu.of(a)))}),{})}}function xat(e){return{..._Zr(e),...lbt(e)}}function hre(e,t){return xat(e.definition)[t]?.contents}function KC(e,t){for(let[r,n]of Cx(xat(e.definition)))t(r,n.contents,{isPackageMarker:zIe(r)===Ky,defaultUrl:n.defaultUrl})}function zLt(e,t){for(let[r,n]of Cx(_Zr(e.definition)))t(r,n.contents)}var hVl=We(require("path"),1);async function lei({schema:e,value:t,context:r,filepathBeingParsed:n}){let i=await e.safeParseAsync(t);if(i.success)return i.data;let o=i.error.errors.map(s=>{let c=s.path.length>0?`${s.message} at "${cTA(s.path)}"`:s.message;return WIe({content:c,prefix:" - "})}),a=[`Failed to parse file: ${hVl.default.relative(process.cwd(),n)}`,...o].join(`
|
|
1534
1534
|
`);return r.failAndThrow(a)}function cTA(e){return e.reduce((t,r)=>typeof r=="number"?t+"["+r+"]":t+(t===""?"":".")+r,"")}var yVl=We(require("path"),1),lTA={dependencies:{}};async function gVl({absolutePathToWorkspace:e,rawDependenciesConfiguration:t,context:r}){if(t==null)return lTA;let n={};for(let[i,o]of Object.entries(t.dependencies))if(fTA(o)){let a=xr.of(yVl.default.join(e,o));await un(a)?n[i]={type:"local",absoluteFilepath:a,path:o}:r.failWithoutThrowing(`Path to ${i} dependency does not exist: ${a}`)}else{let s=i.substring(1).split("/"),c=s[0],l=s[1];c!=null&&l!=null?n[i]={type:"version",organization:c,apiName:l,version:o}:r.failWithoutThrowing(`Failed to parse dependency: ${i}`)}return r.getResult()===p_.Failure&&r.failAndThrow(),{dependencies:n}}var pTA=/^\.\.\/.*$/;function fTA(e){return pTA.test(e)}var AVl=require("fs/promises");var bVl=Lt.object({dependencies:Lt.record(Lt.string(),Lt.string())});async function _Vl({absolutePathToWorkspace:e,context:t}){let r=vt(e,Xe.of(vIl));if(!await un(r))return;let n=await(0,AVl.readFile)(r),i=Un.load(n.toString());return await lei({schema:bVl,value:i,context:t,filepathBeingParsed:r})}async function qfs({absolutePathToWorkspace:e,context:t}){let r=await _Vl({absolutePathToWorkspace:e,context:t});return gVl({absolutePathToWorkspace:e,rawDependenciesConfiguration:r,context:t})}vPn();function vVl(e={accentPrimary:void 0,background:void 0},t){e.accentPrimary=e.accentPrimary??e.accentPrimaryDeprecated;let r=fei(e);switch(r){case"dark":return{type:"dark",...pei(e,t,"dark")};case"light":return{type:"light",...pei(e,t,"light")};case"darkAndLight":return{type:"darkAndLight",dark:pei(e,t,"dark"),light:pei(e,t,"light")};default:qe(r)}}function fei({background:e,accentPrimary:t,accentPrimaryDeprecated:r}){if(t=t??r,typeof e=="string"&&typeof t=="string")return ss(e).isDark()?"dark":"light";if(e!=null){if(typeof e=="string")return ss(e).isDark()?"dark":"light";if(e.dark!=null&&e.light!=null)return"darkAndLight"}if(t!=null){if(typeof t=="string")return ss(t).isLight()?"dark":"light";if(t.dark!=null&&t.light!=null)return"darkAndLight"}if(t!=null&&e!=null){if(e.dark!=null&&t.dark!=null)return"dark";if(e.light!=null&&t.light!=null)return"light"}return"darkAndLight"}function pei(e,t,r){let n=Udr(e.accentPrimary??e.accentPrimaryDeprecated,t,"accent-primary",r)??ss.random(),i=Udr(e.background,t,"background",r);return{accentPrimary:n.toRgb(),background:i?.toRgb(),border:Udr(e.border,t,"border",r)?.toRgb(),sidebarBackground:Udr(e.sidebarBackground,t,"sidebar-background",r)?.toRgb(),headerBackground:Udr(e.headerBackground,t,"header-background",r)?.toRgb(),cardBackground:Udr(e.cardBackground,t,"card-background",r)?.toRgb(),logo:void 0,backgroundImage:void 0}}function vZr(e,t,r){if(e==null)return;let n=typeof e=="string"?e:e[r];if(n==null&&t==="accent-primary"&&typeof e!="string"&&(n=e[r==="dark"?"light":"dark"]),n!=null)return n}function Udr(e,t,r,n){let i=vZr(e,r,n);if(i==null)return;let o=ss(i);return o.isValid()||t.failAndThrow(`'${typeof e=="string"?r:`colors.${r}.${n}`}' should be a hex color of the format #FFFFFF`),o}BP();var Tei=require("fs/promises");var GUl=We(require("path"),1);var wVl=require("fs/promises");var OVl=100;async function dTA({files:e,absolutePathToFernFolder:t}){let r=await Promise.all(e.map(async n=>{let i=await(0,wVl.readFile)(n,"utf-8");return[hB(t,n),i]}));return Object.fromEntries(r)}async function PVl({files:e,absolutePathToFernFolder:t}){let r={};for(let n=0;n<e.length;n+=OVl){let i=e.slice(n,n+OVl),o=await dTA({files:i,absolutePathToFernFolder:t});Object.assign(r,o)}return r}function mei({landingPage:e,navigation:t}){return Yee([e?.absolutePath,...mTA(t)])}function mTA(e){switch(e.type){case"tabbed":return e.items.flatMap(t=>t.child.type==="layout"?t.child.layout.flatMap(r=>dei({item:r})):t.child.type==="variants"?t.child.variants.flatMap(r=>r.layout.flatMap(n=>dei({item:n}))):t.child.type==="changelog"?t.child.changelog:[]);case"untabbed":return e.items.flatMap(t=>dei({item:t}));case"versioned":return e.versions.flatMap(t=>mei({landingPage:t.landingPage,navigation:t.navigation}));case"productgroup":return e.products.flatMap(t=>t.type==="external"?[]:mei({landingPage:t.landingPage,navigation:t.navigation}));default:qe(e)}}function dei({item:e}){switch(e.type){case"apiSection":return Yee([e.overviewAbsolutePath,...e.navigation.flatMap(t=>EVl({item:t}))]);case"link":return[];case"page":return[e.absolutePath];case"section":return Yee([e.overviewAbsolutePath,...e.contents.flatMap(t=>dei({item:t}))]);case"changelog":return e.changelog;case"pythonDocsSection":return[];case"librarySection":return[];default:qe(e)}}function EVl({item:e}){return e.type==="page"?[e.absolutePath]:e.type==="package"||e.type==="section"?Yee([e.overviewAbsolutePath,...e.contents.flatMap(t=>EVl({item:t}))]):[]}var Cei=require("fs/promises"),nds=We(kMe(),1);function Iei({name:e}){return e.replace(/\.(md|mdx)$/i,"").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}function xei({name:e}){return e.replace(/\.(md|mdx)$/i,"").replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase())}async function LUl({absolutePath:e,readFileFn:t=(r,n)=>(0,Cei.readFile)(r,n)}){try{let r=await t(e,"utf-8"),{data:n}=(0,nds.default)(r);if(n.position==null)return;let i=typeof n.position=="string"?parseFloat(n.position):n.position;return typeof i=="number"&&Number.isFinite(i)?i:void 0}catch{return}}async function jei({absolutePath:e,readFileFn:t=(r,n)=>(0,Cei.readFile)(r,n)}){try{let r=await t(e,"utf-8"),{data:n}=(0,nds.default)(r);return typeof n.title=="string"&&n.title.trim().length>0?n.title.trim():void 0}catch{return}}async function ids({directoryPath:e,titleSource:t,getDir:r=Cj,readFileFn:n=(i,o)=>(0,Cei.readFile)(i,o)}){let i=await r(e),o=t==="frontmatter",a=i.filter(m=>m.type==="file"&&(m.name.toLowerCase().endsWith(".md")||m.name.toLowerCase().endsWith(".mdx"))),s=i.filter(m=>m.type==="directory"),[c,l]=await Promise.all([Promise.all(a.map(m=>LUl({absolutePath:m.absolutePath,readFileFn:n}))),o?Promise.all(a.map(m=>jei({absolutePath:m.absolutePath,readFileFn:n}))):Promise.resolve(a.map(()=>{}))]),u=a.map((m,h)=>({type:"page",title:l[h]??xei({name:m.name}),absolutePath:m.absolutePath,slug:Iei({name:m.name}),icon:void 0,hidden:void 0,noindex:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0})),p=await Promise.all(s.map(async m=>{let h=await ids({directoryPath:m.absolutePath,titleSource:t,getDir:r,readFileFn:n}),y=h.find(A=>A.type==="page"&&(A.slug==="index"||A.absolutePath.toLowerCase().endsWith("/index.mdx")||A.absolutePath.toLowerCase().endsWith("/index.md"))),g=y?h.filter(A=>A!==y):h,_=(o&&y?.type==="page"?await jei({absolutePath:y.absolutePath,readFileFn:n}):void 0)??xei({name:m.name}),O=y?.type==="page"?await LUl({absolutePath:y.absolutePath,readFileFn:n}):void 0;return{section:{type:"section",title:_,slug:Iei({name:m.name}),icon:void 0,contents:g,collapsed:void 0,hidden:void 0,skipUrlSlug:!1,overviewAbsolutePath:y?.type==="page"?y.absolutePath:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0},position:O}})),d=[...u.map((m,h)=>({item:m,title:m.type==="page"?m.title:"",position:c[h]})),...p.map(m=>({item:m.section,title:m.section.type==="section"?m.section.title:"",position:m.position}))];return d.sort((m,h)=>{let y=typeof m.position=="number",g=typeof h.position=="number";if(y&&!g)return-1;if(!y&&g)return 1;if(typeof m.position=="number"&&typeof h.position=="number"){let b=m.position-h.position;return b!==0?b:m.title.localeCompare(h.title,void 0,{sensitivity:"base"})}return m.title.localeCompare(h.title,void 0,{sensitivity:"base"})}),d.map(m=>m.item)}function IFA(e){return!e||e.startsWith("<")?!1:e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function $I(e,t){if(e)return IFA(e)?Fx(e,t):e}async function cds({rawDocsConfiguration:e,absolutePathToFernFolder:t,absoluteFilepathToDocsConfig:r,context:n}){let{instances:i,title:o,tabs:a,products:s,versions:c,navigation:l,navbarLinks:u,footerLinks:p,defaultLanguage:d,metadata:m,redirects:h,logo:y,favicon:g,backgroundImage:b,colors:_,typography:O,layout:A,integrations:v,css:P,js:I,aiChat:E,aiSearch:x,pageActions:T,experimental:W}=e,H=SZr(e.landingPage,r),G=e.settings?.folderTitleSource,ie=QFA({tabs:a,products:s,versions:c,navigation:l,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:G}),oe=ie.then(mt=>PVl({files:mei({navigation:mt,landingPage:H}),absolutePathToFernFolder:t})),$=xFA(y,r),te=Fx(g,r),Ge=jFA(b,r),Ke=O!=null?qFA({rawTypography:O,absoluteFilepathToDocsConfig:r}):void 0,Z=CFA(P,r),Y=DFA(I,r),Be=lNA(m,r),[Pe,ke,Ye,Oe,he,pt]=await Promise.all([ie,oe,Ke,Z,Y,Be]);return{title:o,instances:i,roles:e.roles,libraries:eNA(e.libraries),pages:ke,landingPage:H,navigation:Pe,navbarLinks:uNA(u,r),footerLinks:cNA(p),defaultLanguage:d,languages:e.languages,announcement:e.announcement,metadata:pt,redirects:h?.map(mt=>({...mt,permanent:mt?.permanent})),logo:$,favicon:te,backgroundImage:Ge,colors:vVl(_,n),typography:Ye,layout:zFA(A),settings:MFA(e.settings),theme:NFA(e.theme),analyticsConfig:{...e.analytics,intercom:e.analytics?.intercom?{...e.analytics.intercom,appId:e.analytics.intercom.appId,apiBase:e.analytics.intercom.apiBase}:void 0,fullstory:e.analytics?.fullstory,posthog:e.analytics?.posthog?{...e.analytics.posthog,apiKey:e.analytics.posthog.apiKey,endpoint:e.analytics.posthog.endpoint}:void 0,segment:e.analytics?.segment,gtm:e.analytics?.gtm,ga4:e.analytics?.ga4,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},integrations:{...v,intercom:v?.intercom?v.intercom:void 0},css:Oe,js:he,aiChatConfig:x??E,pageActions:TFA(T,r),header:Fx(e.header,r),footer:Fx(e.footer,r),experimental:W}}function xFA(e,t){return e!=null?{dark:Fx(e.dark,t),light:Fx(e.light,t),height:e.height,href:e.href!=null?bn.Url(e.href):void 0,rightText:e.rightText}:void 0}function jFA(e,t){if(e!=null)if(typeof e=="string"){let r=Fx(e,t);return{dark:r,light:r}}else{let r=Fx(e.dark,t),n=Fx(e.light,t);return{dark:r,light:n}}}async function CFA(e,t){if(e==null)return;let r=typeof e=="string"?[e]:e;return{inline:await Promise.all(r.map(async n=>(await(0,Tei.readFile)(Fx(n,t))).toString()))}}function SFA(e){return Object.hasOwn(e,"url")}function BFA(e){return Object.hasOwn(e,"path")}async function DFA(e,t){let r=[],n=[];if(e==null)return{files:[]};let i=Array.isArray(e)?e:[e];for(let o of i)typeof o=="string"?n.push({absolutePath:Fx(o,t)}):SFA(o)?r.push({strategy:o.strategy,url:bn.Url(o.url)}):BFA(o)&&n.push({absolutePath:Fx(o.path,t),strategy:o.strategy});return{remote:r,files:n}}function TFA(e,t){return e==null?void 0:{default:e.default!=null?RFA(e.default):void 0,options:{askAi:e.options?.askAi??!0,copyPage:e.options?.copyPage??!0,viewAsMarkdown:e.options?.viewAsMarkdown??!0,openAi:e.options?.chatgpt??!0,claude:e.options?.claude??!0,cursor:e.options?.cursor??!0,vscode:e.options?.vscode??!1,custom:(e.options?.custom??[]).map(n=>FFA(n,t))}}}function RFA(e){switch(e){case"copy-page":return bn.docs.v1.commons.PageActionOption.CopyPage;case"view-as-markdown":return bn.docs.v1.commons.PageActionOption.ViewAsMarkdown;case"ask-ai":return bn.docs.v1.commons.PageActionOption.AskAi;case"chatgpt":return bn.docs.v1.commons.PageActionOption.OpenAi;case"claude":return bn.docs.v1.commons.PageActionOption.Claude;case"cursor":return bn.docs.v1.commons.PageActionOption.Cursor;case"vscode":return bn.docs.v1.commons.PageActionOption.Vscode;default:qe(e)}}function FFA(e,t){return{title:e.title,subtitle:e.subtitle,url:e.url,icon:$I(e.icon,t),default:e.default}}function NFA(e){if(e!=null)return{sidebar:e.sidebar??"default",tabs:e.tabs??"default",body:e.body??"default",pageActions:e.pageActions??"default",footerNav:e.footerNav??"default",languageSwitcher:e.languageSwitcher??"default",productSwitcher:e.productSwitcher??"default"}}function MFA(e){if(e!=null)return{darkModeCode:e.darkModeCode??!1,defaultSearchFilters:e.defaultSearchFilters??!1,language:e.language??"en",disableSearch:e.disableSearch??!1,hide404Page:e.hide404Page??!1,httpSnippets:e.httpSnippets??!0,searchText:e.searchText??void 0,useJavascriptAsTypescript:e.useJavascriptAsTypescript??!1,disableExplorerProxy:e.disableExplorerProxy??!1,disableAnalytics:e.disableAnalytics??!1}}function zFA(e){if(e!=null)return{pageWidth:e.pageWidth?.trim().toLowerCase()==="full"?{type:"full"}:Sei(e.pageWidth),contentWidth:Sei(e.contentWidth),sidebarWidth:Sei(e.sidebarWidth),headerHeight:Sei(e.headerHeight),searchbarPlacement:e.searchbarPlacement==="header"?bn.docs.v1.commons.SearchbarPlacement.Header:e.searchbarPlacement==="header-tabs"?bn.docs.v1.commons.SearchbarPlacement.HeaderTabs:bn.docs.v1.commons.SearchbarPlacement.Sidebar,switcherPlacement:!e.switcherPlacement||e.switcherPlacement==="header"?bn.docs.v1.commons.SwitcherPlacement.Header:bn.docs.v1.commons.SwitcherPlacement.Sidebar,tabsPlacement:e.tabsPlacement==="header"?bn.docs.v1.commons.TabsPlacement.Header:bn.docs.v1.commons.TabsPlacement.Sidebar,contentAlignment:e.contentAlignment==="left"?bn.docs.v1.commons.ContentAlignment.Left:bn.docs.v1.commons.ContentAlignment.Center,headerPosition:e.headerPosition==="static"?bn.docs.v1.commons.HeaderPosition.Absolute:bn.docs.v1.commons.HeaderPosition.Fixed,disableHeader:e.disableHeader??!1,hideNavLinks:e.hideNavLinks??!1,hideFeedback:e.hideFeedback??!1}}function Sei(e){if(e==null)return;let t=e.trim().toLowerCase(),r=t.match(/^(\d+)px$/);if(r!=null&&r[1]!=null)return{type:"px",value:parseFloat(r[1])};let n=t.match(/^(\d+)rem$/);if(n!=null&&n[1]!=null)return{type:"rem",value:parseFloat(n[1])}}async function WUl({versions:e,absolutePathToFernFolder:t,context:r,folderTitleSource:n}){let i=[];for(let o of e){let a=Ys(t,o.path),s=Un.load((await(0,Tei.readFile)(a)).toString()),c=[],l=Zee(s,[],c);c.length>0&&r.logger.warn(`Version file ${o.path} contained null/undefined sections that were ignored: ${c.map(d=>d.join(".")).join(", ")}`);let u=B5.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(l),p=await uds({tabs:u.tabs,rawNavigationConfig:u.navigation,absolutePathToFernFolder:t,absolutePathToConfig:a,context:r,folderTitleSource:n});i.push({landingPage:SZr(u.landingPage,a),version:o.displayName,navigation:p,availability:o.availability,slug:o.slug,hidden:o.hidden,viewers:NR(o.viewers),orphaned:o.orphaned,featureFlags:FR(o.featureFlag),announcement:o.announcement})}return{type:"versioned",versions:i}}async function QFA({tabs:e,products:t,versions:r,navigation:n,absolutePathToFernFolder:i,absolutePathToConfig:o,context:a,folderTitleSource:s}){if(n!=null)return await uds({tabs:e,rawNavigationConfig:n,absolutePathToFernFolder:i,absolutePathToConfig:o,context:a,folderTitleSource:s});if(t!=null){let c=[];for(let l of t){let u=l.image!=null?Ys(i,l.image):void 0;if("path"in l){let p,d=Ys(i,l.path),m=Un.load((await(0,Tei.readFile)(d)).toString()),h=[],y=Zee(m,[],h);h.length>0&&a.logger.warn(`Product file ${l.path} contained null/undefined sections that were ignored: ${h.map(b=>b.join(".")).join(", ")}`);let g=B5.RawSchemas.Serializer.ProductFileConfig.parseOrThrow(y);l.versions!=null&&l.versions.length>0?p=await WUl({versions:l.versions,absolutePathToFernFolder:i,context:a,folderTitleSource:s}):p=await uds({tabs:g.tabs,rawNavigationConfig:g.navigation,absolutePathToFernFolder:i,absolutePathToConfig:d,context:a,folderTitleSource:s}),c.push({type:"internal",landingPage:SZr(g.landingPage,d),product:l.displayName,navigation:p,slug:l.slug,subtitle:l.subtitle,icon:$I(l.icon,o)||"fa-solid fa-code",image:u,viewers:NR(l.viewers),orphaned:l.orphaned,featureFlags:FR(l.featureFlag),announcement:l.announcement})}else if("href"in l&&l.href!=null)c.push({type:"external",product:l.displayName,href:l.href,target:l.target,subtitle:l.subtitle,icon:$I(l.icon,o)||"fa-solid fa-code",image:u,viewers:NR(l.viewers),orphaned:l.orphaned,featureFlags:FR(l.featureFlag)});else throw new Error("Invalid product configuration: product must have either 'path' or valid 'href' property")}return{type:"productgroup",products:c}}else if(r!=null)return await WUl({versions:r,absolutePathToFernFolder:i,context:a,folderTitleSource:s});throw new Error("Unexpected. Docs have neither navigation or versions defined.")}function FR(e){if(e!=null)return typeof e=="string"?[{flag:e,match:!0,fallbackValue:void 0}]:Array.isArray(e)?e.map(t=>({flag:t.flag,match:t.match,fallbackValue:t.fallbackValue})):[{flag:e.flag,match:e.match??!0,fallbackValue:e.fallbackValue}]}async function qFA({rawTypography:e,absoluteFilepathToDocsConfig:t}){return{headingsFont:e.headingsFont!=null?await ods({rawFontConfig:e.headingsFont,absoluteFilepathToDocsConfig:t}):void 0,bodyFont:e.bodyFont!=null?await ods({rawFontConfig:e.bodyFont,absoluteFilepathToDocsConfig:t}):void 0,codeFont:e.codeFont!=null?await ods({rawFontConfig:e.codeFont,absoluteFilepathToDocsConfig:t}):void 0}}async function ods({rawFontConfig:e,absoluteFilepathToDocsConfig:t}){return{name:e.name,variants:await VFA(e,t),display:e.display,fallback:e.fallback,fontVariationSettings:e.fontVariationSettings}}function VFA(e,t){let r=[];return e.path!=null&&r.push({path:e.path,weight:e.weight,style:e.style}),e.paths?.forEach(n=>{typeof n=="string"?r.push({path:n,weight:e.weight,style:e.style}):r.push({path:n.path,weight:n.weight??e.weight,style:n.style??e.style})}),Promise.all(r.map(async n=>({absolutePath:Fx(n.path,t),weight:kFA(n.weight),style:n.style})))}function kFA(e){return e==null?void 0:typeof e=="number"?[e.toString()]:e.split(/\D+/).filter(r=>r!==""&&["100","200","300","400","500","600","700","800","900"].includes(r))}async function UFA({tabs:e,item:t,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o}){let a=e[t.tab];if(a==null)throw new Error(`Tab ${t.tab} is not defined in the tabs config.`);if(sNA(t)){let s=await Promise.all(t.variants.map(async c=>{let l=await Promise.all(c.layout.map(u=>Dei({rawConfig:u,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})));return{title:c.title,subtitle:c.subtitle,icon:$I(c.icon,n),layout:l,slug:c.slug,skipUrlSlug:c.skipSlug,hidden:c.hidden,default:c.default,viewers:NR(c.viewers),orphaned:c.orphaned,featureFlags:FR(c.featureFlag)}}));return{title:a.displayName,icon:$I(a.icon,n),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"variants",variants:s},viewers:NR(a.viewers),orphaned:a.orphaned,featureFlags:FR(a.featureFlag)}}if(aNA(t)){let s=await Promise.all(t.layout.map(c=>Dei({rawConfig:c,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})));return{title:a.displayName,icon:$I(a.icon,n),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"layout",layout:s},viewers:NR(a.viewers),orphaned:a.orphaned,featureFlags:FR(a.featureFlag)}}if(a.href!=null)return{title:a.displayName,icon:$I(a.icon,n),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"link",href:a.href,target:a.target},viewers:NR(a.viewers),orphaned:a.orphaned,featureFlags:FR(a.featureFlag)};if(a.changelog!=null)return{title:a.displayName,icon:$I(a.icon,n),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"changelog",changelog:await SM(Fx(a.changelog,n),"{md,mdx}")},viewers:NR(a.viewers),orphaned:a.orphaned,featureFlags:FR(a.featureFlag)};qe(a)}async function uds({tabs:e={},rawNavigationConfig:t,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o}){return oNA(t)?{type:"tabbed",items:await Promise.all(t.map(s=>UFA({tabs:e,item:s,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})))}:{type:"untabbed",items:await Promise.all(t.map(a=>Dei({rawConfig:a,absolutePathToFernFolder:r,absolutePathToConfig:n,context:i,folderTitleSource:o})))}}var LFA="Changelog";async function WFA({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i}){let o=Fx(e.folder,r);await un(o)||n.failAndThrow(`Folder not found: ${e.folder}`);let a=e.titleSource??i,s=await ids({directoryPath:o,titleSource:a}),c=s.find(h=>h.type==="page"&&(h.slug==="index"||h.absolutePath.toLowerCase().endsWith("/index.mdx")||h.absolutePath.toLowerCase().endsWith("/index.md"))),l=c?s.filter(h=>h!==c):s,u=GUl.default.basename(o),p=a==="frontmatter"&&c?.type==="page"?await jei({absolutePath:c.absolutePath}):void 0,d=e.title??p??xei({name:u}),m=e.slug??Iei({name:u});return{type:"section",title:d,icon:$I(e.icon,r),contents:l,slug:m,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:c?.type==="page"?c.absolutePath:void 0,viewers:NR(e.viewers),orphaned:e.orphaned,featureFlags:FR(e.featureFlag),availability:e.availability}}async function Dei({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i}){if(HUl(e))return SZr(e,r);if(HFA(e))return{type:"section",title:e.section,icon:$I(e.icon,r),contents:await Promise.all(e.contents.map(o=>Dei({rawConfig:o,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i}))),slug:e.slug??void 0,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:Fx(e.path,r),viewers:NR(e.viewers),orphaned:e.orphaned,featureFlags:FR(e.featureFlag),availability:e.availability};if($FA(e))return{type:"apiSection",openrpc:e.openrpc,title:e.api,icon:$I(e.icon,r),apiName:e.apiName??void 0,audiences:e.audiences!=null?{type:"select",audiences:BZr(e.audiences)??[]}:{type:"all"},availability:e.availability,showErrors:e.displayErrors??!0,tagDescriptionPages:e.tagDescriptionPages??!1,snippetsConfiguration:e.snippets!=null?GFA({rawConfig:e.snippets}):void 0,postman:e.postman,navigation:e.layout?.flatMap(o=>Bei(o,r))??[],overviewAbsolutePath:Fx(e.summary,r),collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,slug:e.slug,skipUrlSlug:e.skipSlug??!1,flattened:e.flattened??!1,alphabetized:e.alphabetized??!1,paginated:e.paginated??!1,playground:e.playground,viewers:NR(e.viewers),orphaned:e.orphaned,featureFlags:FR(e.featureFlag)};if($Ul(e))return{type:"link",text:e.link,url:e.href,icon:$I(e.icon,r),target:e.target};if(JFA(e))return{type:"changelog",changelog:await SM(Fx(e.changelog,r),"{md,mdx}"),hidden:e.hidden??!1,icon:$I(e.icon,r),title:e.title??LFA,slug:e.slug,viewers:NR(e.viewers),orphaned:e.orphaned,featureFlags:FR(e.featureFlag)};if(KFA(e))return await WFA({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:n,folderTitleSource:i});if(YFA(e))return{type:"pythonDocsSection",githubUrl:e.pythonDocs,title:e.title??void 0,slug:e.slug??void 0};if(XFA(e))return{type:"librarySection",libraryName:e.library,title:e.title??void 0,slug:e.slug??void 0,viewers:NR(e.viewers),orphaned:e.orphaned,featureFlags:FR(e.featureFlag)};qe(e)}function SZr(e,t){if(e!=null)return{type:"page",title:e.page,absolutePath:Fx(e.path,t),slug:e.slug,icon:$I(e.icon,t),hidden:e.hidden,noindex:e.noindex,viewers:NR(e.viewers),orphaned:e.orphaned,featureFlags:FR(e.featureFlag),availability:e.availability}}function Bei(e,t){return typeof e=="string"?[{type:"item",value:e}]:HUl(e)?[SZr(e,t)]:$Ul(e)?[{type:"link",text:e.link,url:e.href,icon:$I(e.icon,t),target:e.target}]:tNA(e)?[{type:"section",title:e.section,referencedSubpackages:e.referencedPackages??[],overviewAbsolutePath:Fx(e.summary,t),contents:e.contents?.flatMap(r=>Bei(r,t))??[],slug:e.slug,hidden:e.hidden,skipUrlSlug:e.skipSlug,availability:e.availability,icon:$I(e.icon,t),playground:e.playground,viewers:NR(e.viewers),orphaned:e.orphaned,featureFlags:FR(e.featureFlag)}]:rNA(e)?[{type:"endpoint",endpoint:e.endpoint,title:e.title,icon:$I(e.icon,t),slug:e.slug,hidden:e.hidden,availability:e.availability,playground:e.playground,viewers:NR(e.viewers),orphaned:e.orphaned,featureFlags:FR(e.featureFlag)}]:nNA(e)?[{type:"operation",operation:e.operation,title:e.title,slug:e.slug,hidden:e.hidden,availability:e.availability,viewers:NR(e.viewers),orphaned:e.orphaned,featureFlags:FR(e.featureFlag)}]:Object.entries(e).map(([r,n])=>iNA(n)?{type:"package",title:n.title,package:r,overviewAbsolutePath:Fx(n.summary,t),contents:n.contents?.flatMap(i=>Bei(i,t))??[],slug:n.slug,hidden:n.hidden,skipUrlSlug:n.skipSlug,icon:$I(n.icon,t),playground:n.playground,availability:n.availability,viewers:NR(n.viewers),orphaned:n.orphaned,featureFlags:FR(n.featureFlag)}:{type:"package",title:void 0,package:r,overviewAbsolutePath:void 0,contents:n.flatMap(i=>Bei(i,t)),hidden:!1,slug:void 0,skipUrlSlug:!1,icon:void 0,playground:void 0,availability:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}function GFA({rawConfig:e}){return{python:e.python,typescript:e.typescript,go:e.go,java:e.java,ruby:e.ruby,csharp:e.csharp,php:e.php,swift:e.swift}}function HUl(e){return Hc(e)&&typeof e.page=="string"&&typeof e.path=="string"}function HFA(e){return e.section!=null}function $FA(e){return e.api!=null}function $Ul(e){return B5.RawSchemas,Hc(e)&&typeof e.link=="string"&&typeof e.href=="string"}function JFA(e){return Hc(e)&&typeof e.changelog=="string"}function KFA(e){return Hc(e)&&typeof e.folder=="string"}function YFA(e){return Hc(e)&&typeof e.pythonDocs=="string"}function XFA(e){return Hc(e)&&typeof e.library=="string"}function ZFA(e){return"git"in e}function eNA(e){if(e==null)return;let t={};for(let[r,n]of Object.entries(e)){if(!ZFA(n.input))throw new Error(`Library '${r}' uses 'path' input which is not yet supported. Please use 'git' input.`);t[r]={input:{git:n.input.git,subpath:n.input.subpath},output:{path:n.output.path},lang:n.lang}}return t}function tNA(e){return Hc(e)&&typeof e.section=="string"&&Array.isArray(e.contents)}function rNA(e){return Hc(e)&&typeof e.endpoint=="string"}function nNA(e){return Hc(e)&&typeof e.operation=="string"}function iNA(e){return!Array.isArray(e)}function Fx(e,t){if(e!=null)return Ys(Fi(t),e)}function oNA(e){return Array.isArray(e)&&e.length>0&&e[0].tab!=null}function aNA(e){return"layout"in e&&Array.isArray(e.layout)}function sNA(e){return"variants"in e&&Array.isArray(e.variants)}function uNA(e,t){return e?.map(r=>{if(r.type==="github"){let i=r.value;return typeof i=="string"?{type:"github",url:bn.Url(i),viewers:void 0,target:void 0}:{type:"github",url:bn.Url(i.url),viewers:ads(i.viewers),target:i.target}}let n=ads(r.viewers);return r.type==="dropdown"?{type:"dropdown",text:r.text,icon:$I(r.icon,t),rightIcon:$I(r.rightIcon,t),rounded:r.rounded,viewers:n,links:r.links?.map(i=>({href:i.href,target:i.target,url:bn.Url(i.url??i.href??"/"),text:i.text,icon:$I(i.icon,t),rightIcon:$I(i.rightIcon,t),rounded:i.rounded,viewers:ads(i.viewers)}))??[]}:{type:r.type,text:r.text,url:bn.Url(r.href??r.url??"/"),target:r.target,icon:$I(r.icon,t),rightIcon:$I(r.rightIcon,t),rounded:r.rounded,viewers:n}})}function ads(e){if(e!=null)return Array.isArray(e)?e.map(t=>bn.RoleId(t)):[bn.RoleId(e)]}function cNA(e){if(e==null)return;let t=[];if(Object.keys(e).forEach(r=>{let n=e[r];n!=null&&t.push({type:r,value:bn.Url(n)})}),t.length!==0)return t}async function lNA(e,t){if(e!=null)return{"og:site_name":e.ogSiteName,"og:title":e.ogTitle,"og:description":e.ogDescription,"og:url":e.ogUrl,"og:image":await sds(e.ogImage,t),"og:image:width":e.ogImageWidth,"og:image:height":e.ogImageHeight,"og:locale":e.ogLocale,"og:logo":await sds(e.ogLogo,t),"twitter:title":e.twitterTitle,"twitter:description":e.twitterDescription,"twitter:image":await sds(e.twitterImage,t),"twitter:handle":e.twitterHandle,"twitter:site":e.twitterSite,"twitter:url":e.twitterUrl,"twitter:card":e.twitterCard,nofollow:void 0,noindex:void 0,canonicalHost:e.canonicalHost}}async function sds(e,t){if(e==null)return;if(e.startsWith("http"))return{type:"url",value:e};let r=Fx(e,t);return await un(r)?{type:"filepath",value:r}:{type:"url",value:e}}function NR(e){if(e!=null){if(typeof e=="string")return[bn.RoleId(e)];if(e.length!==0)return e.map(bn.RoleId)}}function BZr(e){if(e!=null){if(typeof e=="string")return[e];if(e.length!==0)return e}}var KUl=require("fs/promises");var JUl=Lt.strictObject({organization:Lt.string(),version:Lt.string()});async function nK({directory:e,context:t}){let r=vt(e,Xe.of(Vj)),n=await(0,KUl.readFile)(r),i=JSON.parse(n.toString()),o=await lei({schema:JUl,value:i,context:t,filepathBeingParsed:r});return{_absolutePath:r,rawConfig:o,organization:o.organization,version:o.version}}var w={TYPESCRIPT:"fernapi/fern-typescript",TYPESCRIPT_SDK:"fernapi/fern-typescript-sdk",TYPESCRIPT_NODE_SDK:"fernapi/fern-typescript-node-sdk",TYPESCRIPT_BROWSER_SDK:"fernapi/fern-typescript-browser-sdk",TYPESCRIPT_EXPRESS:"fernapi/fern-typescript-express",JAVA:"fernapi/fern-java",JAVA_MODEL:"fernapi/fern-java-model",JAVA_SDK:"fernapi/fern-java-sdk",JAVA_SPRING:"fernapi/fern-java-spring",PYTHON_FASTAPI:"fernapi/fern-fastapi-server",PYTHON_PYDANTIC:"fernapi/fern-pydantic-model",PYTHON_SDK:"fernapi/fern-python-sdk",GO_MODEL:"fernapi/fern-go-model",GO_SDK:"fernapi/fern-go-sdk",GO_FIBER:"fernapi/fern-go-fiber",RUBY_MODEL:"fernapi/fern-ruby-model",RUBY_SDK:"fernapi/fern-ruby-sdk",CSHARP_MODEL:"fernapi/fern-csharp-model",CSHARP_SDK:"fernapi/fern-csharp-sdk",SWIFT_MODEL:"fernapi/fern-swift-model",SWIFT_SDK:"fernapi/fern-swift-sdk",PHP_MODEL:"fernapi/fern-php-model",PHP_SDK:"fernapi/fern-php-sdk",RUST_MODEL:"fernapi/fern-rust-model",RUST_SDK:"fernapi/fern-rust-sdk",OPENAPI:"fernapi/fern-openapi",STOPLIGHT:"fernapi/fern-stoplight",POSTMAN:"fernapi/fern-postman",OPENAPI_PYTHON_CLIENT:"fernapi/openapi-python-client"};var DZr={[w.JAVA]:{version:"2.38.1"},[w.TYPESCRIPT_EXPRESS]:{version:"0.18.4",output:{location:"local-file-system",path:"../src/fern"}},[w.JAVA_MODEL]:{version:"1.0.0"},[w.JAVA_SDK]:{version:"2.38.1",output:{location:"local-file-system",path:"../sdks/java/src/main/java/"}},[w.JAVA_SPRING]:{version:"0.9.2",output:{location:"local-file-system",path:"../src/main/java/com/fern"}},[w.TYPESCRIPT]:{version:"0.0.247"},[w.TYPESCRIPT_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[w.TYPESCRIPT_NODE_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[w.TYPESCRIPT_BROWSER_SDK]:{version:"1.0.0",output:{location:"local-file-system",path:"../sdks/typescript"}},[w.PYTHON_PYDANTIC]:{version:"1.4.7"},[w.PYTHON_FASTAPI]:{version:"1.7.0",output:{location:"local-file-system",path:"../src/fern"}},[w.PYTHON_SDK]:{version:"4.23.2",output:{location:"local-file-system",path:"../sdks/python"}},[w.GO_FIBER]:{version:"0.23.5"},[w.GO_MODEL]:{version:"0.23.5"},[w.GO_SDK]:{version:"1.4.0",output:{location:"local-file-system",path:"../sdks/go"},config:{module:{path:"sdk"}}},[w.RUBY_MODEL]:{version:"0.0.8"},[w.RUBY_SDK]:{version:"0.8.2",output:{location:"local-file-system",path:"../sdks/ruby"}},[w.OPENAPI]:{version:"0.1.7",config:{format:"yaml"},output:{location:"local-file-system",path:"../openapi"}},[w.STOPLIGHT]:{version:"0.0.28",config:{format:"yaml"}},[w.POSTMAN]:{version:"0.4.0",output:{location:"local-file-system",path:"../postman"}},[w.OPENAPI_PYTHON_CLIENT]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/python"},config:{format:"yaml"}},[w.CSHARP_MODEL]:{version:"0.0.1"},[w.CSHARP_SDK]:{version:"2.0.2",output:{location:"local-file-system",path:"../sdks/csharp"}},[w.SWIFT_MODEL]:{version:"0.0.0"},[w.SWIFT_SDK]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/swift/sdk"}},[w.PHP_MODEL]:{version:"0.0.0"},[w.PHP_SDK]:{version:"1.16.3",output:{location:"local-file-system",path:"../sdks/php/sdk"}},[w.RUST_MODEL]:{version:"0.0.1",output:{location:"local-file-system",path:"../models/rust"}},[w.RUST_SDK]:{version:"0.0.1",output:{location:"local-file-system",path:"../sdks/rust"}}};var YUl="fernapi";function MR(e){return e.includes("/")?e:`${YUl}/${e}`}function lds(e){let t=`${YUl}/`;return e.startsWith(t)?e.slice(t.length):e}function pds(e,t){let r=GLt(e);return r??t.failAndThrow("Unrecognized generator: "+e)}var pNA={"fernapi/java-model":w.JAVA_MODEL,"fernapi/fern-typescript-node-sdk":w.TYPESCRIPT_SDK};function GLt(e){e=MR(e);let t=pNA[e];if(t!=null&&(e=t),fNA(e))return e}function fNA(e){return Object.values(w).includes(e)}var Rei=We(iGr(),1),XUl=We(Y3(),1);async function Hxe({generatorName:e,cliVersion:t,channel:r,currentGeneratorVersion:n,includeMajor:i,context:o}){let a=XUl.default.parse(n),s=new Rei.FernRegistryClient({environment:"https://registry.buildwithfern.com"});o?.logger.debug(`Getting latest version for ${e} with CLI version ${t}, includeMajor: ${i}, prior version: ${a}`);let c={generator:dNA(e,o),releaseTypes:[r??Rei.FernRegistry.generators.ReleaseType.Ga],cliVersion:t==="0.0.0"?void 0:t};!i&&a!=null&&(c.generatorMajorVersion=a.major);let l=await s.generators.versions.getLatestGeneratorRelease(c);if(l.ok)return l.body.version}function dNA(e,t){switch(e.startsWith("fernapi/")&&(e=e.replace("fernapi/","")),e){case"fern-python-sdk":return"python-sdk";case"fern-pydantic-model":return"pydantic";case"fern-fastapi-server":return"fastapi";case"fern-typescript":case"fern-typescript-browser-sdk":case"fern-typescript-node-sdk":case"fern-typescript-sdk":return"ts-sdk";case"fern-typescript-express":return"ts-express";case"fern-java-sdk":return"java-sdk";case"fern-java-model":case"java-model":return"java-model";case"fern-java-spring":return"java-spring";case"fern-go-sdk":return"go-sdk";case"fern-go-model":return"go-model";case"fern-go-fiber":return"go-fiber";case"fern-csharp-sdk":return"csharp-sdk";case"fern-csharp-model":return"csharp-model";case"fern-ruby-sdk":return"ruby-sdk";case"fern-ruby-model":return"ruby-model";case"fern-postman":return"postman";case"fern-openapi":return"openapi";case"fern-php-sdk":return"php-sdk";case"fern-php-model":return"php-model";case"fern-rust-sdk":return"rust-sdk";case"fern-rust-model":return"rust-model";case"fern-swift-sdk":return"swift-sdk";case"fern-swift-model":return"swift-model";default:return t?.logger.warn(`Unrecognized generator name found, attempting to parse manually: ${e}`),e.startsWith("fern-")?e.replace("fern-",""):e}}async function ZUl({generatorsConfiguration:e,groupName:t=e[vi.DEFAULT_GROUP_GENERATORS_CONFIG_KEY],context:r,update:n}){if(t==null)return r.failAndThrow("No group specified.");let i=e.groups??={},o=i[t];if(o==null){let a=i[t]??={generators:[]};await n(a,t)}else await n(o,t);return e}async function fds({generatorName:e,generatorsConfiguration:t,groupName:r=t[ipr],context:n,cliVersion:i}){let o=pds(e,n),a=lds(o),s=DZr[o];return await ZUl({generatorsConfiguration:t,groupName:r,context:n,update:async c=>{c.generators.some(l=>MR(l.name)===o)&&n.failAndThrow(`${e} is already installed in group ${r}.`),c.generators.push({name:a,...s,version:await Hxe({cliVersion:i,generatorName:o,context:n,channel:void 0})??s.version})}})}var $xe=require("fs/promises"),YLt=We(require("path"),1);var F4l=require("buffer"),Hei=We(t4l(),1),Lei=We(zI(),1),E2l=require("child_process"),uLl=We(mds(),1),ALl=require("path"),emr=We(mds(),1),NLl=require("events"),Fds=Object.defineProperty,_NA=Object.getOwnPropertyDescriptor,Nds=Object.getOwnPropertyNames,vNA=Object.prototype.hasOwnProperty,pa=(e,t)=>function(){return e&&(t=(0,e[Nds(e)[0]])(e=0)),t},ONA=(e,t)=>function(){return t||(0,e[Nds(e)[0]])((t={exports:{}}).exports,t),t.exports},XC=(e,t)=>{for(var r in t)Fds(e,r,{get:t[r],enumerable:!0})},wNA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Nds(t))!vNA.call(e,i)&&i!==r&&Fds(e,i,{get:()=>t[i],enumerable:!(n=_NA(t,i))||n.enumerable});return e},Wj=e=>wNA(Fds({},"__esModule",{value:!0}),e);function PNA(...e){let t=new String(e);return Gei.set(t,e),t}function Vei(e){return e instanceof String&&Gei.has(e)}function r4l(e){return Gei.get(e)||[]}var Gei,NZr=pa({"src/lib/args/pathspec.ts"(){"use strict";Gei=new WeakMap}}),Bat,mbt=pa({"src/lib/errors/git-error.ts"(){"use strict";Bat=class extends Error{constructor(e,t){super(t),this.task=e,Object.setPrototypeOf(this,new.target.prototype)}}}}),MZr,rmr=pa({"src/lib/errors/git-response-error.ts"(){"use strict";mbt(),MZr=class extends Bat{constructor(e,t){super(void 0,t||String(e)),this.git=e}}}}),T4l,R4l=pa({"src/lib/errors/task-configuration-error.ts"(){"use strict";mbt(),T4l=class extends Bat{constructor(e){super(void 0,e)}}}});function N4l(e){return typeof e!="function"?KLt:e}function M4l(e){return typeof e=="function"&&e!==KLt}function z4l(e,t){let r=e.indexOf(t);return r<=0?[e,""]:[e.substr(0,r),e.substr(r+1)]}function Q4l(e,t=0){return q4l(e)&&e.length>t?e[t]:void 0}function JLt(e,t=0){if(q4l(e)&&e.length>t)return e[e.length-1-t]}function q4l(e){return Yei(e)}function zZr(e="",t=!0,r=`
|
|
1535
1535
|
`){return e.split(r).reduce((n,i)=>{let o=t?i.trim():i;return o&&n.push(o),n},[])}function Mds(e,t){return zZr(e,!0).map(r=>t(r))}function zds(e){return(0,Hei.exists)(e,Hei.FOLDER)}function Mv(e,t){return Array.isArray(e)?e.includes(t)||e.push(t):e.add(t),t}function V4l(e,t){return Array.isArray(e)&&!e.includes(t)&&e.push(t),e}function $ei(e,t){if(Array.isArray(e)){let r=e.indexOf(t);r>=0&&e.splice(r,1)}else e.delete(t);return t}function UMe(e){return Array.isArray(e)?e:[e]}function k4l(e){return e.replace(/[\s-]+(.)/g,(t,r)=>r.toUpperCase())}function nmr(e){return UMe(e).map(t=>t instanceof String?t:String(t))}function HP(e,t=0){if(e==null)return t;let r=parseInt(e,10);return Number.isNaN(r)?t:r}function RZr(e,t){let r=[];for(let n=0,i=e.length;n<i;n++)r.push(t,e[n]);return r}function FZr(e){return(Array.isArray(e)?F4l.Buffer.concat(e):e).toString("utf-8")}function U4l(e,t){let r={};return t.forEach(n=>{e[n]!==void 0&&(r[n]=e[n])}),r}function vds(e=0){return new Promise(t=>setTimeout(t,e))}function Ods(e){if(e!==!1)return e}var tmr,KLt,QZr,Jei=pa({"src/lib/utils/util.ts"(){"use strict";Qds(),tmr="\0",KLt=()=>{},QZr=Object.prototype.toString.call.bind(Object.prototype.toString)}});function aK(e,t,r){return t(e)?e:arguments.length>2?r:void 0}function wds(e,t){let r=Vei(e)?"string":typeof e;return/number|string|boolean/.test(r)&&(!t||!t.includes(r))}function Kei(e){return!!e&&QZr(e)==="[object Object]"}function L4l(e){return typeof e=="function"}var qZr,W4l,zR,kei,Yei,Qds=pa({"src/lib/utils/argument-filters.ts"(){"use strict";NZr(),Jei(),qZr=e=>Array.isArray(e),W4l=e=>typeof e=="number",zR=e=>typeof e=="string",kei=e=>zR(e)||Array.isArray(e)&&e.every(zR),Yei=e=>e==null||"number|boolean|function".includes(typeof e)?!1:typeof e.length=="number"}}),Pds,ENA=pa({"src/lib/utils/exit-codes.ts"(){"use strict";Pds=(e=>(e[e.SUCCESS=0]="SUCCESS",e[e.ERROR=1]="ERROR",e[e.NOT_FOUND=-2]="NOT_FOUND",e[e.UNCLEAN=128]="UNCLEAN",e))(Pds||{})}}),Uei,INA=pa({"src/lib/utils/git-output-streams.ts"(){"use strict";Uei=class G4l{constructor(t,r){this.stdOut=t,this.stdErr=r}asStrings(){return new G4l(this.stdOut.toString("utf8"),this.stdErr.toString("utf8"))}}}});function xNA(){throw new Error("LineParser:useMatches not implemented")}var rm,dbt,jNA=pa({"src/lib/utils/line-parser.ts"(){"use strict";rm=class{constructor(e,t){this.matches=[],this.useMatches=xNA,this.parse=(r,n)=>(this.resetMatches(),this._regExp.every((i,o)=>this.addMatch(i,o,r(o)))?this.useMatches(n,this.prepareMatches())!==!1:!1),this._regExp=Array.isArray(e)?e:[e],t&&(this.useMatches=t)}resetMatches(){this.matches.length=0}prepareMatches(){return this.matches}addMatch(e,t,r){let n=r&&e.exec(r);return n&&this.pushMatch(t,n),!!n}pushMatch(e,t){this.matches.push(...t.slice(1))}},dbt=class extends rm{addMatch(e,t,r){return/^remote:\s/.test(String(r))&&super.addMatch(e,t,r)}pushMatch(e,t){(e>0||t.length>1)&&super.pushMatch(e,t)}}}});function H4l(...e){let t=process.cwd(),r=Object.assign({baseDir:t,...$4l},...e.filter(n=>typeof n=="object"&&n));return r.baseDir=r.baseDir||t,r.trimmed=r.trimmed===!0,r}var $4l,CNA=pa({"src/lib/utils/simple-git-options.ts"(){"use strict";$4l={binary:"git",maxConcurrentProcesses:5,config:[],trimmed:!1}}});function qds(e,t=[]){return Kei(e)?Object.keys(e).reduce((r,n)=>{let i=e[n];if(Vei(i))r.push(i);else if(wds(i,["boolean"]))r.push(n+"="+i);else if(Array.isArray(i))for(let o of i)wds(o,["string","number"])||r.push(n+"="+o);else r.push(n);return r},t):t}function W5(e,t=0,r=!1){let n=[];for(let i=0,o=t<0?e.length:t;i<o;i++)"string|number".includes(typeof e[i])&&n.push(String(e[i]));return qds(Vds(e),n),r||n.push(...SNA(e)),n}function SNA(e){let t=typeof JLt(e)=="function";return nmr(aK(JLt(e,t?1:0),qZr,[]))}function Vds(e){let t=L4l(JLt(e));return aK(JLt(e,t?1:0),Kei)}function Gj(e,t=!0){let r=N4l(JLt(e));return t||M4l(r)?r:void 0}var BNA=pa({"src/lib/utils/task-options.ts"(){"use strict";Qds(),Jei(),NZr()}});function Eds(e,t){return e(t.stdOut,t.stdErr)}function H5(e,t,r,n=!0){return UMe(r).forEach(i=>{for(let o=zZr(i,n),a=0,s=o.length;a<s;a++){let c=(l=0)=>{if(!(a+l>=s))return o[a+l]};t.some(({parse:l})=>l(c,e))}}),e}var DNA=pa({"src/lib/utils/task-parser.ts"(){"use strict";Jei()}}),J4l={};XC(J4l,{ExitCodes:()=>Pds,GitOutputStreams:()=>Uei,LineParser:()=>rm,NOOP:()=>KLt,NULL:()=>tmr,RemoteLineParser:()=>dbt,append:()=>Mv,appendTaskOptions:()=>qds,asArray:()=>UMe,asCamelCase:()=>k4l,asFunction:()=>N4l,asNumber:()=>HP,asStringArray:()=>nmr,bufferToString:()=>FZr,callTaskParser:()=>Eds,createInstanceConfig:()=>H4l,delay:()=>vds,filterArray:()=>qZr,filterFunction:()=>L4l,filterHasLength:()=>Yei,filterNumber:()=>W4l,filterPlainObject:()=>Kei,filterPrimitives:()=>wds,filterString:()=>zR,filterStringOrStringArray:()=>kei,filterType:()=>aK,first:()=>Q4l,folderExists:()=>zds,forEachLineWithContent:()=>Mds,getTrailingOptions:()=>W5,including:()=>V4l,isUserFunction:()=>M4l,last:()=>JLt,objectToString:()=>QZr,orVoid:()=>Ods,parseStringResponse:()=>H5,pick:()=>U4l,prefixedArray:()=>RZr,remove:()=>$ei,splitOn:()=>z4l,toLinesWithContent:()=>zZr,trailingFunctionArgument:()=>Gj,trailingOptionsArgument:()=>Vds});var Sf=pa({"src/lib/utils/index.ts"(){"use strict";Qds(),ENA(),INA(),jNA(),CNA(),BNA(),DNA(),Jei()}}),K4l={};XC(K4l,{CheckRepoActions:()=>Ids,checkIsBareRepoTask:()=>X4l,checkIsRepoRootTask:()=>Y4l,checkIsRepoTask:()=>TNA});function TNA(e){switch(e){case"bare":return X4l();case"root":return Y4l()}return{commands:["rev-parse","--is-inside-work-tree"],format:"utf-8",onError:Xei,parser:kds}}function Y4l(){return{commands:["rev-parse","--git-dir"],format:"utf-8",onError:Xei,parser(t){return/^\.(git)?$/.test(t.trim())}}}function X4l(){return{commands:["rev-parse","--is-bare-repository"],format:"utf-8",onError:Xei,parser:kds}}function RNA(e){return/(Not a git repository|Kein Git-Repository)/i.test(String(e))}var Ids,Xei,kds,Z4l=pa({"src/lib/tasks/check-is-repo.ts"(){"use strict";Sf(),Ids=(e=>(e.BARE="bare",e.IN_TREE="tree",e.IS_REPO_ROOT="root",e))(Ids||{}),Xei=({exitCode:e},t,r,n)=>{if(e===128&&RNA(t))return r(Buffer.from("false"));n(t)},kds=e=>e.trim()==="true"}});function FNA(e,t){let r=new e2l(e),n=e?r2l:t2l;return zZr(t).forEach(i=>{let o=i.replace(n,"");r.paths.push(o),(n2l.test(o)?r.folders:r.files).push(o)}),r}var e2l,t2l,r2l,n2l,NNA=pa({"src/lib/responses/CleanSummary.ts"(){"use strict";Sf(),e2l=class{constructor(e){this.dryRun=e,this.paths=[],this.files=[],this.folders=[]}},t2l=/^[a-z]+\s*/i,r2l=/^[a-z]+\s+[a-z]+\s*/i,n2l=/\/$/}}),xds={};XC(xds,{EMPTY_COMMANDS:()=>Zei,adhocExecTask:()=>i2l,configurationErrorTask:()=>G5,isBufferTask:()=>a2l,isEmptyTask:()=>s2l,straightThroughBufferTask:()=>o2l,straightThroughStringTask:()=>WU});function i2l(e){return{commands:Zei,format:"empty",parser:e}}function G5(e){return{commands:Zei,format:"empty",parser(){throw typeof e=="string"?new T4l(e):e}}}function WU(e,t=!1){return{commands:e,format:"utf-8",parser(r){return t?String(r).trim():r}}}function o2l(e){return{commands:e,format:"buffer",parser(t){return t}}}function a2l(e){return e.format==="buffer"}function s2l(e){return e.format==="empty"||!e.commands.length}var Zei,YC=pa({"src/lib/tasks/task.ts"(){"use strict";R4l(),Zei=[]}}),u2l={};XC(u2l,{CONFIG_ERROR_INTERACTIVE_MODE:()=>Uds,CONFIG_ERROR_MODE_REQUIRED:()=>Lds,CONFIG_ERROR_UNKNOWN_OPTION:()=>Wds,CleanOptions:()=>Mei,cleanTask:()=>c2l,cleanWithOptionsTask:()=>MNA,isCleanOptionsArray:()=>zNA});function MNA(e,t){let{cleanMode:r,options:n,valid:i}=QNA(e);return r?i.options?(n.push(...t),n.some(kNA)?G5(Uds):c2l(r,n)):G5(Wds+JSON.stringify(e)):G5(Lds)}function c2l(e,t){return{commands:["clean",`-${e}`,...t],format:"utf-8",parser(n){return FNA(e==="n",n)}}}function zNA(e){return Array.isArray(e)&&e.every(t=>Gds.has(t))}function QNA(e){let t,r=[],n={cleanMode:!1,options:!0};return e.replace(/[^a-z]i/g,"").split("").forEach(i=>{qNA(i)?(t=i,n.cleanMode=!0):n.options=n.options&&VNA(r[r.length]=`-${i}`)}),{cleanMode:t,options:r,valid:n}}function qNA(e){return e==="f"||e==="n"}function VNA(e){return/^-[a-z]$/i.test(e)&&Gds.has(e.charAt(1))}function kNA(e){return/^-[^\-]/.test(e)?e.indexOf("i")>0:e==="--interactive"}var Uds,Lds,Wds,Mei,Gds,l2l=pa({"src/lib/tasks/clean.ts"(){"use strict";NNA(),Sf(),YC(),Uds="Git clean interactive mode is not supported",Lds='Git clean mode parameter ("n" or "f") is required',Wds="Git clean unknown option found in: ",Mei=(e=>(e.DRY_RUN="n",e.FORCE="f",e.IGNORED_INCLUDED="x",e.IGNORED_ONLY="X",e.EXCLUDING="e",e.QUIET="q",e.RECURSIVE="d",e))(Mei||{}),Gds=new Set(["i",...nmr(Object.values(Mei))])}});function UNA(e){let t=new f2l;for(let r of p2l(e))t.addValue(r.file,String(r.key),r.value);return t}function LNA(e,t){let r=null,n=[],i=new Map;for(let o of p2l(e,t))o.key===t&&(n.push(r=o.value),i.has(o.file)||i.set(o.file,[]),i.get(o.file).push(r));return{key:t,paths:Array.from(i.keys()),scopes:i,value:r,values:n}}function WNA(e){return e.replace(/^(file):/,"")}function*p2l(e,t=null){let r=e.split("\0");for(let n=0,i=r.length-1;n<i;){let o=WNA(r[n++]),a=r[n++],s=t;if(a.includes(`
|
|
@@ -2628,7 +2628,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
|
|
|
2628
2628
|
Run ${tt.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
|
|
2629
2629
|
Run ${tt.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),bur(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function f8u({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!Ruy(e))return;let i=t??"",o=e.filter(s=>s.isUpgradeAvailable);r!=null&&(o=o.slice(0,r+1));let a=o.sort((s,c)=>s.generatorName.localeCompare(c.generatorName)||s.currentVersion.localeCompare(c.currentVersion));for(let s of a)i+=`
|
|
2630
2630
|
${await NRx(s.generatorName)} (${s.apiName!=null?"API: "+s.apiName+", ":""}Group: ${s.generatorGroup}) `+tt.dim(s.currentVersion)+tt.reset(" \u2192 ")+tt.green(s.latestVersion);return i+=`
|
|
2631
|
-
`,n?bur(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function NRx(e){let r=await new Tuy.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 MRx({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let s={type:"singleApi",versions:{}};return await Nuy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,l,u,p)=>{s.versions[l]==null&&(s.versions[l]={});let d=GLt(u.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${u.name}`);return}let m=await Hxe({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:o,context:p});m!=null&&(s.versions[l][u.name]={previousVersion:u.version,latestVersion:m})},generatorFilter:r,groupFilter:n}),s}let a={type:"multiApi",versions:{}};return await Nuy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(s,c,l,u)=>{if(s==null)return;a.versions[s]==null&&(a.versions[s]={}),a.versions[s][c]==null&&(a.versions[s][c]={});let p=GLt(l.name);if(p==null){u.logger.debug(`Skipping unknown generator: ${l.name}`);return}let d=await Hxe({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:u});d!=null&&(a.versions[s][c][l.name]={previousVersion:l.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),a}async function Nuy({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async a=>{let s=await sK({absolutePathToWorkspace:o.absoluteFilePath,context:a});if(s==null||s.groups==null)return;let c=n!=null?MR(n):void 0;for(let l of s.groups)if(!(i!=null&&l.groupName!==i))for(let u of l.generators)c!=null&&u.name!==c||await r(o.workspaceName,l.groupName,u,a)})}))}function Muy(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[a,s]of Object.entries(o)){r.debug(`Checking if ${a} in group ${i} has an upgrade available...`);let c=K5(s.latestVersion,s.previousVersion);r.debug(`Latest version: ${s.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:a,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:s.previousVersion,latestVersion:s.latestVersion})}return n}async function Awa({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let a=[];if(e!=null){let s=await MRx({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(s.type==="multiApi")for(let[c,l]of Object.entries(s.versions))a.push(...Muy(l,c,t.logger));else a.push(...Muy(s.versions,void 0,t.logger))}return a}async function XQt({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:uYr(e.packageName,{version:t?"prerelease":"latest"})}var zuy=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],_wa=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ho.Info;isLocal;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new R4t(t,r),this.isLocal=n??!1;let i=this.getPackageName(),o=this.getPackageVersion(),a=this.getCliName();(i==null||o==null||a==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:o,cliName:a}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.72.
|
|
2631
|
+
`,n?bur(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function NRx(e){let r=await new Tuy.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 MRx({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let s={type:"singleApi",versions:{}};return await Nuy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,l,u,p)=>{s.versions[l]==null&&(s.versions[l]={});let d=GLt(u.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${u.name}`);return}let m=await Hxe({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:o,context:p});m!=null&&(s.versions[l][u.name]={previousVersion:u.version,latestVersion:m})},generatorFilter:r,groupFilter:n}),s}let a={type:"multiApi",versions:{}};return await Nuy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(s,c,l,u)=>{if(s==null)return;a.versions[s]==null&&(a.versions[s]={}),a.versions[s][c]==null&&(a.versions[s][c]={});let p=GLt(l.name);if(p==null){u.logger.debug(`Skipping unknown generator: ${l.name}`);return}let d=await Hxe({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:u});d!=null&&(a.versions[s][c][l.name]={previousVersion:l.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),a}async function Nuy({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async a=>{let s=await sK({absolutePathToWorkspace:o.absoluteFilePath,context:a});if(s==null||s.groups==null)return;let c=n!=null?MR(n):void 0;for(let l of s.groups)if(!(i!=null&&l.groupName!==i))for(let u of l.generators)c!=null&&u.name!==c||await r(o.workspaceName,l.groupName,u,a)})}))}function Muy(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[a,s]of Object.entries(o)){r.debug(`Checking if ${a} in group ${i} has an upgrade available...`);let c=K5(s.latestVersion,s.previousVersion);r.debug(`Latest version: ${s.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:a,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:s.previousVersion,latestVersion:s.latestVersion})}return n}async function Awa({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let a=[];if(e!=null){let s=await MRx({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(s.type==="multiApi")for(let[c,l]of Object.entries(s.versions))a.push(...Muy(l,c,t.logger));else a.push(...Muy(s.versions,void 0,t.logger))}return a}async function XQt({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:uYr(e.packageName,{version:t?"prerelease":"latest"})}var zuy=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],_wa=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ho.Info;isLocal;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new R4t(t,r),this.isLocal=n??!1;let i=this.getPackageName(),o=this.getPackageVersion(),a=this.getCliName();(i==null||o==null||a==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:o,cliName:a}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.72.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${tt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new QP}failWithoutThrowing(t,r){this.didSucceed=!1,X$r({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await cur()).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 Fuy({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
2632
2632
|
`)||(r+=`
|
|
2633
2633
|
`),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=W4a(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 R_n(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(o){throw o.message.includes("globalThis")?(n.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),n.failWithoutThrowing()):n.failWithoutThrowing(void 0,o),new QP}finally{n.finish()}return i}async instrumentPostHogEvent(t){this.isLocal||(await cur()).sendEvent(t)}logger=gU((t,...r)=>this.log(t,...r));stderr=gU((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=Quy(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?Quy(this.longestWorkspaceName):r).length,i=r.padEnd(n),o=zuy[this.numTasks++%zuy.length],a=tt.hex(o)(i);return{...this.constructTaskInit(),logPrefix:a}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===p_.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=>VM.indexOf(i.level)>=VM.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===ho.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 XQt({cliEnvironment:this.environment,includePreReleases:t}),n=K5(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},o=await Awa({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:o}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await l8u({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:tt.yellow("?"),style:{answer:i=>tt.cyan(i),message:i=>tt.bold(i),highlight:i=>tt.cyan(i)}}})}catch(n){throw n?.name==="ExitPromptError"?(this.logger.info(`
|
|
2634
2634
|
Cancelled by user.`),new QP):n}}async getInput(t){return await s8u({message:t.message,default:t.default})}};function Quy(e){return`[${e}]:`}var quy=require("fs/promises");async function d8u({context:e,nameOverride:t,...r}){let n=await fI(t);return n==null?e.failAndThrow(`Directory "${t??dP}" not found.`):await Vuy({absolutePathToFernDirectory:n,context:e,nameOverride:t,...r})}async function Vuy({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:n,defaultToAllApiWorkspaces:i,context:o}){let a=[];(await un(vt(e,Xe.of(BU)))||await un(vt(e,Xe.of(uI)))||await un(vt(e,Xe.of(cI)))||await un(vt(e,Xe.of(npr)))||await un(vt(e,Xe.of(gYr)))||await un(vt(e,Xe.of(His))))&&(a=await kuy({cliName:t,fernDirectory:e,cliVersion:r,context:o,commandLineApiWorkspace:n,defaultToAllApiWorkspaces:i}));let s=await D1u({fernDirectory:e,context:o});return a.length===0&&s==null?o.failAndThrow(`No SDK specifications or docs specifications found. Please ensure one of the following .yml (not .yaml) files is present:
|
|
@@ -2664,7 +2664,7 @@ The generator configuration must be an object with a 'name' property, but the cu
|
|
|
2664
2664
|
|
|
2665
2665
|
Please check your generators.yml file and ensure the generator is properly configured.`);let a=i,s=await Kuy({generatorName:t,logger:o});if(s==null)return;let c=QRx({migrations:s.migrations,from:r,to:n,logger:o});if(c.length!==0)return Yuy({migrations:c,config:a,logger:o})}function Xuy(e){return{"fernapi/fern-typescript-sdk":"https://buildwithfern.com/learn/sdks/generators/typescript/changelog","fernapi/fern-typescript-node-sdk":"https://buildwithfern.com/learn/sdks/generators/typescript/changelog","fernapi/fern-python-sdk":"https://buildwithfern.com/learn/sdks/generators/python/changelog","fernapi/fern-go-sdk":"https://buildwithfern.com/learn/sdks/generators/go/changelog","fernapi/fern-java-sdk":"https://buildwithfern.com/learn/sdks/generators/java/changelog","fernapi/fern-csharp-sdk":"https://buildwithfern.com/learn/sdks/generators/csharp/changelog","fernapi/fern-php-sdk":"https://buildwithfern.com/learn/sdks/generators/php/changelog","fernapi/fern-ruby-sdk":"https://buildwithfern.com/learn/sdks/generators/ruby/changelog","fernapi/fern-swift-sdk":"https://buildwithfern.com/learn/sdks/generators/swift/changelog"}[e]}async function VRx({absolutePathToWorkspace:e,context:t,generatorFilter:r,groupFilter:n,includeMajor:i,channel:o,cliVersion:a}){let s=await ybt({absolutePathToWorkspace:e});if(s==null||!await un(s))return t.logger.debug("Generators configuration file was not found, no generators to upgrade."),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};let c=await(0,wwa.readFile)(s);t.logger.debug(`Found generators: ${c.toString()}`);let l=i3r.default.parseDocument(c.toString()),u=l.get("groups");if(u==null)return t.logger.debug("No groups were found within the generators configuration, no generators to upgrade."),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};if(!i3r.default.isMap(u))return t.failAndThrow(`Expected 'groups' to be a map in ${N_n.default.relative(process.cwd(),s)}`),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};t.logger.debug(`Groups found: ${u.toString()}`);let p=[],d=[],m=[];for(let h of u.items){let y=h.key.value,g=h.value;if(!i3r.default.isMap(g)){t.failAndThrow(`Expected group ${y} to be a map in ${N_n.default.relative(process.cwd(),s)}`);continue}if(n!=null&&n!==y){t.logger.debug(`Skipping group ${y} as it does not match the filter: ${n}`);continue}let b=g.get("generators");if(!i3r.default.isSeq(b)){t.failAndThrow(`Expected group ${y} to have a 'generators' key in ${N_n.default.relative(process.cwd(),s)}`);continue}t.logger.debug(`Generators found: ${b.toString()}`);for(let _ of b.items){i3r.default.isMap(_)||t.failAndThrow(`Expected generator in group ${y} to be a map in ${N_n.default.relative(process.cwd(),s)}`);let O=_.get("name"),A=GLt(O);if(A==null){t.logger.warn(`Skipping unrecognized generator: ${O}. The generator will not be upgraded.`);continue}let v=r!=null?MR(r):void 0;if(v!=null&&A!==v){t.logger.debug(`Skipping generator ${O} as it does not match the filter: ${r}`);continue}let P=_.get("version"),I=await Hxe({generatorName:A,cliVersion:a,currentGeneratorVersion:P,channel:o,includeMajor:i,context:t}),E=I??P;if(I!=null)if(I!==P){t.logger.debug(tt.green(`Upgrading ${O} from ${P} to ${I}`)),_.set("version",I);let x=0,T=[],W=_.toJSON(),H=await m8u({generatorName:A,from:P,to:I,config:W,logger:t.logger});if(H!=null){x=H.migrationsApplied,T=H.appliedVersions;let G=new Set(Object.keys(W)),ie=new Set(Object.keys(H.config));for(let oe of G)ie.has(oe)||_.delete(oe);for(let[oe,$]of Object.entries(H.config))_.set(oe,$);t.logger.debug(tt.dim(`Applied ${x} migration(s): ${T.join(", ")}`))}d.push({generatorName:O,groupName:y,previousVersion:P,newVersion:I,migrationsApplied:x>0?x:void 0,migrationVersions:T.length>0?T:void 0})}else t.logger.debug(tt.gray(`${O} is already on the latest version: ${P}`)),m.push({generatorName:O,groupName:y,version:P});if(!i){let x=await Hxe({generatorName:A,cliVersion:a,currentGeneratorVersion:E,channel:o,includeMajor:!0,context:t});if(x!=null){let T=h8u.default.parse(E),W=h8u.default.parse(x);T!=null&&W!=null&&W.major>T.major&&p.push({generatorName:O,currentVersion:E,latestMajorVersion:x})}}}}return{updatedConfiguration:l.toString(),skippedMajorUpgrades:p,appliedUpgrades:d,alreadyUpToDate:m}}async function Zuy({cliContext:e,generator:t,group:r,project:{apiWorkspaces:n},includeMajor:i,channel:o}){let a=[],s=[],c=[];if(await Promise.all(n.map(async l=>{await e.runTaskForWorkspace(l,async u=>{let p=await imr({absolutePathToWorkspace:l.absoluteFilePath,context:u})??{};if(p==null||p.groups==null){u.logger.debug("No groups were found within the generators configuration, no generators to upgrade.");return}l.workspaceName==null?u.logger.info("Upgrading generators."):u.logger.info(`Upgrading generators in workspace: ${l.workspaceName}.`);let d=await VRx({absolutePathToWorkspace:l.absoluteFilePath,context:u,generatorFilter:t,groupFilter:r,includeMajor:i,channel:o,cliVersion:e.environment.packageVersion}),m=await ybt({absolutePathToWorkspace:l.absoluteFilePath});m!=null&&d.updatedConfiguration!=null&&await(0,wwa.writeFile)(m,d.updatedConfiguration),a.push(...d.skippedMajorUpgrades),d.appliedUpgrades.length>0&&s.push({workspace:l.workspaceName,upgrades:d.appliedUpgrades}),d.alreadyUpToDate.length>0&&c.push({workspace:l.workspaceName,upToDate:d.alreadyUpToDate})})})),s.length>0){e.logger.info(""),e.logger.info(tt.green("Successfully upgraded generators:"));for(let{workspace:l,upgrades:u}of s){let p=new Map;for(let d of u){let m=p.get(d.groupName)??[];m.push(d),p.set(d.groupName,m)}for(let[d,m]of p){let h=l!=null?`[${l}] `:"";e.logger.info(tt.green(`${h}Group ${d}:`));for(let y of m){e.logger.info(tt.green(` - ${y.generatorName}: ${tt.dim(y.previousVersion)} \u2192 ${y.newVersion}`)),y.migrationsApplied!=null&&y.migrationsApplied>0&&e.logger.info(tt.dim(` Applied ${y.migrationsApplied} migration(s): ${y.migrationVersions?.join(", ")??""}`));let g=Xuy(MR(y.generatorName));g!=null&&e.logger.info(tt.dim(` Changelog: ${g}`))}}}}if(c.length>0){e.logger.info(""),e.logger.info(tt.dim("Generators already on latest version:"));for(let{workspace:l,upToDate:u}of c){let p=new Map;for(let d of u){let m=p.get(d.groupName)??[];m.push(d),p.set(d.groupName,m)}for(let[d,m]of p){let h=l!=null?`[${l}] `:"";e.logger.info(tt.dim(`${h}Group ${d}:`));for(let y of m)e.logger.info(tt.dim(` - ${y.generatorName}: ${y.version} (latest)`))}}}if(s.length===0&&c.length===0){let l=r!=null?` for group ${r}`:t!=null?` for generator ${t}`:"";e.logger.info(""),e.logger.info(tt.gray(`No generators found${l}.`))}if(a.length>0){e.logger.info(""),e.logger.info(tt.yellow("Major version upgrades available:"));for(let l of a){e.logger.info(tt.yellow(` - ${l.generatorName}: ${l.currentVersion} \u2192 ${l.latestMajorVersion}`));let u=t!=null?`fern generator upgrade --generator ${l.generatorName} --include-major`:"fern generator upgrade --include-major";e.logger.info(tt.yellow(` Run: ${u}`));let p=Xuy(MR(l.generatorName));p!=null&&e.logger.info(tt.yellow(` Changelog: ${p}`))}}}function rcy(e,t){e.command("organization",!1,r=>r.option("output",{string:!0,alias:"o",description:"The location to output the organization name as a text file, defaults to standard out."}),async r=>{await t.instrumentPostHogEvent({command:"fern organization",properties:{outputLocation:r.output}}),await $uy({project:await ob(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),context:t,outputLocation:r.output})})}function ncy(e,t){e.command("generator","Operate on the generators within your Fern configuration",r=>{r.command("list",!1,n=>n.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generators",{string:!0,type:"array",description:"The type of generator to include in the list, ex: `fern-typescript-node-sdk`. If omitted, all generators will be listed."}).option("groups",{type:"array",string:!0,description:"The groups to include generators from, if group is not specified, the all generators of the specified type will be listed."}).option("apis",{type:"array",string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("api-fallback",{string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("include-mode",{choices:Object.values(n3r),type:"array",description:"The generator output modes to include within the outputted list."}).option("exclude-mode",{choices:Object.values(n3r),type:"array",description:"The generator output modes to exclude within the outputted list."}),async n=>{await t.instrumentPostHogEvent({command:"fern generator list",properties:{outputLocation:n.output}}),await Wuy({project:await ob(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),generatorFilter:n.generators?new Set(n.generators):void 0,groupFilter:n.groups?new Set(n.groups):void 0,apiFilter:n.apis?new Set(n.apis):void 0,apiKeyFallback:n.apiFallback,cliContext:t,outputLocation:n.output,includedModes:n["include-mode"]?new Set(n["include-mode"]):void 0,excludedModes:n["exclude-mode"]?new Set(n["exclude-mode"]):void 0})}).command("upgrade",`Upgrades the specified generator in ${cI} to the latest stable version.`,n=>n.option("generator",{string:!0,description:"The type of generator to upgrade, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,description:"The group in which the generator is located, if group is not specified, the all generators of the specified type will be upgraded."}).option("api",{string:!0,description:"The API to upgrade the generator for. If not specified, the generator will be upgraded for all APIs."}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to any prompts that may appear during the upgrade process."}).option("include-major",{boolean:!0,default:!1,description:"Whether or not to include major versions within the upgrade. Defaults to false, meaning major versions will be skipped."}).option("channel",{demandOption:!1,choices:Object.values(ecy.FernRegistry.generators.ReleaseType)}).option("list",{demandOption:!1,boolean:!0,default:!1,description:"When specified, a list of available upgrades will be displayed, but no upgrade will be taken."}),async n=>{await t.instrumentPostHogEvent({command:"fern generator upgrade",properties:{generator:n.generator,version:n.version,api:n.api,group:n.group,includeMajor:n.includeMajor,rc:n.rc}});let i=await ob(t,{commandLineApiWorkspace:n.api,defaultToAllApiWorkspaces:!0});if(n.list){t.suppressUpgradeMessage();let o=await Awa({cliContext:t,project:i,generatorFilter:n.generator,groupFilter:n.group,includeMajor:n.includeMajor,channel:n.channel}),a=await f8u({generatorUpgradeInfo:o,header:`Generator Upgrades
|
|
2666
2666
|
`,includeBoxen:!0});a!=null&&t.logger.info(a)}else await Zuy({cliContext:t,generator:n.generator,group:n.group,project:await ob(t,{commandLineApiWorkspace:n.api,defaultToAllApiWorkspaces:!0}),includeMajor:n.includeMajor,channel:n.channel})}).command("get",!1,n=>n.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generator",{string:!0,demandOption:!0,description:"The name of the generator to get, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,demandOption:!0,description:"The group in which the generator is located."}).option("api",{string:!0,description:"The API in which the generator is located."}).option("version",{boolean:!0,default:!1,description:"Get the version of the specified generator."}).option("language",{boolean:!0,default:!1,description:"Get the language of the specified generator."}).option("repository",{boolean:!0,default:!1,description:"Get repository for the generator invocation, if one is specified."}),async n=>{await t.instrumentPostHogEvent({command:"fern generator get",properties:{generator:n.generator,version:n.version,api:n.api,group:n.group,includeMajor:n.includeMajor}});let i=await Guy({cliContext:t,generatorFilter:n.generator,groupFilter:n.group,apiFilter:n.api,project:await ob(t,{commandLineApiWorkspace:n.api,defaultToAllApiWorkspaces:!0})});if(i==null){let a=n.api?` for API ${n.api}`:"";t.failAndThrow(`Generator ${n.generator}, in group ${n.group}${a} was not found.`)}let o={};if(n.version&&(o.version=i.version,n.output==null)){process.stdout.write(i.version);return}if(n.language)if(i.language!=null){if(o.language=i.language,n.output==null){process.stdout.write(i.language);return}}else t.logger.warn(`Language information is not available for generator ${i.name} in group ${n.group}`);if(n.repository){let a=i.outputMode.type==="github"?i.outputMode.repo:i.outputMode.type==="githubV2"?i.outputMode.githubV2.repo:void 0;if(a!=null){if(o.repository=a,n.output==null){process.stdout.write(o.repository);return}}else t.logger.warn(`Repository information is not available for generator ${i.name} in group ${n.group}`)}if(n.output)try{await(0,tcy.writeFile)(n.output,JSON.stringify(o,null,2))}catch(a){t.failAndThrow(`Could not write file to the specified location: ${n.output}`,a)}})})}var icy=require("fs/promises");async function ocy({project:{apiWorkspaces:e},generatorName:t,groupName:r,cliContext:n}){await Promise.all(e.map(async i=>{await n.runTaskForWorkspace(i,async o=>{let a=await imr({absolutePathToWorkspace:i.absoluteFilePath,context:o})??{},s=await fds({generatorName:t,generatorsConfiguration:a,groupName:r,context:o,cliVersion:n.environment.packageVersion}),c=i.generatorsConfiguration?.absolutePathToConfiguration??await ybt({absolutePathToWorkspace:i.absoluteFilePath});c!=null&&(await(0,icy.writeFile)(c,`# yaml-language-server: $schema=https://schema.buildwithfern.dev/generators-yml.json
|
|
2667
|
-
`+Un.dump(s)),o.logger.info(tt.green(`Added ${t} generator`)))})}))}var scy=require("fs/promises"),ucy=We(Y3(),1);async function ccy({context:e,from:t,to:r,fromVersion:n,generatorVersions:i}){let o=new HZr,a=kRx(await o.check({from:await acy({context:e,filepath:t,flagName:"from"}),to:await acy({context:e,filepath:r,flagName:"to"})})),s=WRx(e,i),{bump:c,errors:l}=URx(a,s);if(n==null)return{bump:c??"patch",errors:l};if(c==="no_change")return{bump:"no_change",nextVersion:n,errors:l};let u=c??"patch",p=ucy.default.inc(n,u);if(!p)throw e.failWithoutThrowing(`Invalid current version: ${n}`),new QP;return{bump:u,nextVersion:p,errors:l}}async function acy({context:e,filepath:t,flagName:r}){let n=xr.of(Ys(pb(),t));if(!await un(n,"file"))throw e.failWithoutThrowing(`File not found: ${n}`),new QP;let i=await(0,scy.readFile)(n,"utf-8"),o=Vo.IntermediateRepresentation.parse(JSON.parse(i));if(!o.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new QP;return o.value}function kRx(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function URx(e,t){return{bump:LRx(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function LRx(e,t){if(!(e===void 0&&t===void 0))return e==="no_change"&&(t===void 0||t==="no_change")||t==="no_change"&&(e===void 0||e==="no_change")?"no_change":e===void 0?t:t===void 0?e:e==="no_change"?t:t==="no_change"?e:e==="major"||t==="major"?"major":e==="minor"||t==="minor"?"minor":"patch"}function WRx(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:n}=t;try{let i=GRx(C2a(r,n)),o=[];return i==="major"&&o.push("Generator version changed by major version."),{bump:i,errors:o}}catch(i){throw e.failWithoutThrowing(`Error diffing generator versions ${r} and ${n}: ${i}`),new QP}}function GRx(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}BP();var fyy=We(b8u(),1),dyy=We(uPa(),1),zPa=require("fs/promises"),myy=We(require("http"),1),hyy=We(require("path"),1);var omy=require("events"),dPa=We(require("fs"),1),Uer=We(require("path"),1);var Vdy=We(require("os"),1),kdy=300,oqt=20,svn=1e7,Udy=Vdy.default.platform();var nkx=Udy==="darwin",M6u=Udy==="win32",aqt=nkx||M6u,Ldy=3e3,Wdy=2e4,z6u=1250;var jrt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(jrt||(jrt={}));var ker;(function(e){e.CHANGE="change",e.RENAME="rename"})(ker||(ker={}));var uvn;(function(e){e.CHANGE="change",e.ERROR="error"})(uvn||(uvn={}));var Nl;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Nl||(Nl={}));var KL;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(KL||(KL={}));var ikx=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),a,s,c=0,l=0,u=()=>{let A=Date.now(),v=A-c,P=A-l,I=v>=t||P>=o;return[A,I]},p=A=>{if(l=A,!a)return;let v=a;a=void 0,e.apply(void 0,v)},d=()=>{_(0)},m=()=>{s&&(d(),p(Date.now()))},h=A=>{if(l=A,n)return p(A)},y=A=>{if(i&&a)return p(A);a=void 0},g=()=>{s=void 0;let[A,v]=u();return v?y(A):b(A)},b=A=>{let v=A-c,P=A-l,I=t-v,E=o-P,x=Math.min(I,E);return _(x)},_=A=>{s&&clearTimeout(s),!(A<=0)&&(s=setTimeout(g,A))},O=(...A)=>{let[v,P]=u(),I=!!s;if(a=A,c=v,(P||!s)&&_(t),P)return I?p(v):h(v)};return O.cancel=d,O.flush=m,O},cPa=ikx;var k6u=We(require("fs"),1),pPa=We(require("path"),1);var t_=We(require("fs"),1),gQ=require("util");var Bft=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},Crt=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var Q6u=We(require("process"),1),Gdy=Q6u.default.getuid?!Q6u.default.getuid():!1,Hdy=1e4,X$=()=>{};var cvn={isChangeErrorOk:e=>{if(!cvn.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Gdy&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!cvn.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!cvn.isNodeError(e))throw e;if(!cvn.isChangeErrorOk(e))throw e}},YS=cvn;var q6u=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Hdy,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},$dy=new q6u;var Dft=(e,t)=>function(n){return function i(...o){return $dy.schedule().then(a=>{let s=l=>(a(),l),c=l=>{if(a(),Date.now()>=n)throw l;if(t(l)){let u=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,u)).then(()=>i.apply(void 0,o))}throw l};return e.apply(void 0,o).then(s,c)})}},Tft=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(a){if(Date.now()>n)throw a;if(t(a))return i.apply(void 0,o);throw a}}};var okx={attempt:{chmod:Bft((0,gQ.promisify)(t_.default.chmod),YS.onChangeError),chown:Bft((0,gQ.promisify)(t_.default.chown),YS.onChangeError),close:Bft((0,gQ.promisify)(t_.default.close),X$),fsync:Bft((0,gQ.promisify)(t_.default.fsync),X$),mkdir:Bft((0,gQ.promisify)(t_.default.mkdir),X$),realpath:Bft((0,gQ.promisify)(t_.default.realpath),X$),stat:Bft((0,gQ.promisify)(t_.default.stat),X$),unlink:Bft((0,gQ.promisify)(t_.default.unlink),X$),chmodSync:Crt(t_.default.chmodSync,YS.onChangeError),chownSync:Crt(t_.default.chownSync,YS.onChangeError),closeSync:Crt(t_.default.closeSync,X$),existsSync:Crt(t_.default.existsSync,X$),fsyncSync:Crt(t_.default.fsync,X$),mkdirSync:Crt(t_.default.mkdirSync,X$),realpathSync:Crt(t_.default.realpathSync,X$),statSync:Crt(t_.default.statSync,X$),unlinkSync:Crt(t_.default.unlinkSync,X$)},retry:{close:Dft((0,gQ.promisify)(t_.default.close),YS.isRetriableError),fsync:Dft((0,gQ.promisify)(t_.default.fsync),YS.isRetriableError),open:Dft((0,gQ.promisify)(t_.default.open),YS.isRetriableError),readFile:Dft((0,gQ.promisify)(t_.default.readFile),YS.isRetriableError),rename:Dft((0,gQ.promisify)(t_.default.rename),YS.isRetriableError),stat:Dft((0,gQ.promisify)(t_.default.stat),YS.isRetriableError),write:Dft((0,gQ.promisify)(t_.default.write),YS.isRetriableError),writeFile:Dft((0,gQ.promisify)(t_.default.writeFile),YS.isRetriableError),closeSync:Tft(t_.default.closeSync,YS.isRetriableError),fsyncSync:Tft(t_.default.fsyncSync,YS.isRetriableError),openSync:Tft(t_.default.openSync,YS.isRetriableError),readFileSync:Tft(t_.default.readFileSync,YS.isRetriableError),renameSync:Tft(t_.default.renameSync,YS.isRetriableError),statSync:Tft(t_.default.statSync,YS.isRetriableError),writeSync:Tft(t_.default.writeSync,YS.isRetriableError),writeFileSync:Tft(t_.default.writeFileSync,YS.isRetriableError)}},Jdy=okx;var lPa=We(require("fs"),1),lvn=We(require("path"),1);var V6u=()=>{};var akx=()=>{let e=V6u,t=V6u,r=!1,n=!1;return{promise:new Promise((c,l)=>{e=u=>(r=!0,c(u)),t=u=>(n=!0,l(u))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},Kdy=akx;var skx=()=>{let{promise:e,resolve:t,isPending:r}=Kdy(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},Ydy=skx;var Xdy={then:e=>{e()}};var Zdy=e=>Array.isArray(e)?e:[e],emy=e=>typeof e=="function";var ukx=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],a=Zdy(o).map(Z=>emy(Z)?Z:Y=>Z.test(Y)),s=Z=>a.some(Y=>Y(Z)),c=t?.signal??{aborted:!1},l=t?.onDirents||(()=>{}),u=[],p=new Set,d={},m=[],h=new Set,y={},g=[],b=new Set,_={},O={},A=new Set,v={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},P={directories:u,directoriesNames:p,directoriesNamesToPaths:d,files:m,filesNames:h,filesNamesToPaths:y,symlinks:g,symlinksNames:b,symlinksNamesToPaths:_,map:O},{promise:I,increment:E,decrement:x}=Ydy(),T=0,W=(Z,Y,Be,Pe)=>{A.has(Y)||T>=i||(T+=1,Z.directories.push(Y),Z.directoriesNames.add(Be),u.push(Y),p.add(Be),d.propertyIsEnumerable(Be)||(d[Be]=[]),d[Be].push(Y),A.add(Y),!(Pe>=n)&&(T>=i||te(Y,Pe+1)))},H=(Z,Y,Be)=>{A.has(Y)||T>=i||(T+=1,Z.files.push(Y),Z.filesNames.add(Be),m.push(Y),h.add(Be),y.propertyIsEnumerable(Be)||(y[Be]=[]),y[Be].push(Y),A.add(Y))},G=(Z,Y,Be,Pe)=>{A.has(Y)||T>=i||(T+=1,Z.symlinks.push(Y),Z.symlinksNames.add(Be),g.push(Y),b.add(Be),_.propertyIsEnumerable(Be)||(_[Be]=[]),_[Be].push(Y),A.add(Y),r&&(Pe>=n||T>=i||Ge(Y,Pe+1)))},ie=(Z,Y,Be,Pe,ke)=>{c.aborted||s(Y)||(Pe.isDirectory()?W(Z,Y,Be,ke):Pe.isFile()?H(Z,Y,Be):Pe.isSymbolicLink()&&G(Z,Y,Be,ke))},oe=(Z,Y,Be,Pe)=>{if(c.aborted)return;let ke=Y===lvn.default.sep?"":lvn.default.sep,Ye=Be.name,Oe=`${Y}${ke}${Ye}`;s(Oe)||(Be.isDirectory()?W(Z,Oe,Ye,Pe):Be.isFile()?H(Z,Oe,Ye):Be.isSymbolicLink()&&G(Z,Oe,Ye,Pe))},$=(Z,Y,Be,Pe)=>{for(let ke=0,Ye=Be.length;ke<Ye;ke++)oe(Z,Y,Be[ke],Pe)},te=(Z,Y)=>{c.aborted||Y>n||T>=i||(E(),lPa.default.readdir(Z,{withFileTypes:!0},(Be,Pe)=>{if(Be||c.aborted||!Pe.length)return x();(l(Pe)||Xdy).then(()=>{let Ye=O[Z]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};$(Ye,Z,Pe,Y),x()})}))},Ge=(Z,Y)=>{E(),lPa.default.realpath(Z,(Be,Pe)=>{if(Be||c.aborted)return x();lPa.default.stat(Pe,(ke,Ye)=>{if(ke||c.aborted)return x();let Oe=lvn.default.basename(Pe),he=O[Z]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};ie(he,Pe,Oe,Ye,Y),x()})})};return(async(Z,Y=1)=>(Z=lvn.default.normalize(Z),A.add(Z),te(Z,Y),await I,c.aborted?v:P))(e)},tmy=ukx;var Srt={lang:{debounce:cPa,attempt:e=>{try{return e()}catch(t){return Srt.lang.castError(t)}},castArray:e=>Srt.lang.isArray(e)?e:[e],castError:e=>Srt.lang.isError(e)?e:Srt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(Srt.lang.isNaN(e))return Srt.lang.isNaN(t);if(Srt.lang.isPrimitive(e)||Srt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(pPa.default.sep).length-1),getRealPath:(e,t)=>{try{return t?k6u.default.realpathSync.native(e):k6u.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===pPa.default.sep&&t.length-e.length>pPa.default.sep.length,poll:(e,t=Wdy)=>Jdy.retry.stat(t)(e,{bigint:!0}).catch(Srt.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let a=o[e];return[a.directories,a.files]}else{let a=await tmy(e,{depth:r,limit:n,ignore:t,signal:i});return[a.directories,a.files]}}}},Qm=Srt;var fPa=We(require("path"),1);var U6u=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Qm.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=kdy){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(s,c)=>{let l=this.options.ignoreInitial?[]:s,u=await this.eventsPopulate([...c]),p=this.eventsDeduplicate([...l,...u]);this.onTargetEvents(p)},a=Qm.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(s,c="",l=!1)=>{l?await this.eventsPopulate([c],n,!0):i.add(c),r.then(a)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,a]=i,s=r[a];return o===s||o===Nl.CHANGE&&s===Nl.ADD||(r[a]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async a=>{r.push([a,i]),a===Nl.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):a===Nl.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??oqt:Math.min(1,this.options.depth??oqt),a=this.options.limit??svn,[s,c]=await Qm.fs.readdir(r,this.options.ignore,o,a,this.watcher._closeSignal),l=[...s,...c];return await Promise.all(l.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())Qm.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Nl.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!aqt&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Nl.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Nl.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(fPa.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Nl.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(fPa.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Nl.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Nl.ADD?this.onTargetAdd(n):r===Nl.ADD_DIR?this.onTargetAddDir(n):r===Nl.CHANGE?this.onTargetChange(n):r===Nl.UNLINK?this.onTargetUnlink(n):r===Nl.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=ker.CHANGE,r){if(this.watcher.isClosed())return;let n=fPa.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){M6u&&t.code==="EPERM"?this.onWatcherChange(ker.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(uvn.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(uvn.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(ker.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&aqt&&this.options.native!==!1?this.options.depth??oqt:Math.min(1,this.options.depth??oqt),n=this.options.limit??svn,[i,o]=await Qm.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),a=[this.folderPath,...i,...o];await Promise.all(a.map(s=>{if(!this.watcher._poller.stats.has(s)&&!this.watcher.isIgnored(s,this.options.ignore))return this.onWatcherEvent(ker.CHANGE,s,t)}))}}},rmy=U6u;var YL={interval:100,intervalId:void 0,fns:new Map,init:()=>{YL.intervalId||(YL.intervalId=setInterval(YL.resolve,YL.interval))},reset:()=>{YL.intervalId&&(clearInterval(YL.intervalId),delete YL.intervalId)},add:(e,t)=>{YL.fns.set(e,Date.now()+t),YL.init()},remove:e=>{YL.fns.delete(e)},resolve:()=>{if(!YL.fns.size)return YL.reset();let e=Date.now();for(let[t,r]of YL.fns)r>=e||(YL.remove(t),t())}},pvn=YL;var fvn=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=z6u){let{ino:n,targetPath:i,events:o,locks:a}=t,s=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(Qm.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return s();let c=()=>{a.add.delete(n),pvn.remove(l)},l=()=>{c(),s()};pvn.add(l,r);let u=()=>{let p=a.unlink.get(n);if(!p)return;c();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};a.add.set(n,u),u()}getLockUnlink(t,r=z6u){let{ino:n,targetPath:i,events:o,locks:a}=t,s=()=>{this._watcher.event(o.unlink,i)};if(!n)return s();let c=()=>{a.unlink.delete(n),pvn.remove(l)},l=()=>{c(),s()};pvn.add(l,r);let u=()=>(c(),i);a.unlink.set(n,u),a.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Nl.ADD,jrt.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,Nl.ADD_DIR,jrt.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,Nl.UNLINK,jrt.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,Nl.UNLINK_DIR,jrt.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};fvn.DIR_EVENTS={add:Nl.ADD_DIR,rename:Nl.RENAME_DIR,unlink:Nl.UNLINK_DIR};fvn.FILE_EVENTS={add:Nl.ADD,change:Nl.CHANGE,rename:Nl.RENAME,unlink:Nl.UNLINK};var nmy=fvn;var L6u=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Qm.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(Qm.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(Qm.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(Qm.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return Qm.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);Qm.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},W6u=L6u;var G6u=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},imy=G6u;var H6u=class{constructor(){this.inos={},this.paths=new W6u,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await Qm.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new imy(n)}reset(){this.inos={},this.paths=new W6u,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,Nl.ADD,i),[Nl.ADD];if(i.isDirectory())return this.updateIno(t,Nl.ADD_DIR,i),[Nl.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Nl.UNLINK,n),[Nl.UNLINK];if(n.isDirectory())return this.updateIno(t,Nl.UNLINK_DIR,n),[Nl.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Nl.CHANGE,i),[Nl.CHANGE]);if(i.isDirectory())return this.updateIno(t,Nl.UNLINK,n),this.updateIno(t,Nl.ADD_DIR,i),[Nl.UNLINK,Nl.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Nl.UNLINK_DIR,n),this.updateIno(t,Nl.ADD,i),[Nl.UNLINK_DIR,Nl.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Nl.UNLINK_DIR,n),this.updateIno(t,Nl.ADD_DIR,i),[Nl.UNLINK_DIR,Nl.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?jrt.FILE:jrt.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},$6u=H6u;var J6u=class e extends omy.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(KL.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(KL.CLOSE,i)),this._readyWait=new Promise(i=>this.on(KL.READY,i)),this._locker=new nmy(this),this._roots=new Set,this._poller=new $6u,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Qm.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(KL.CLOSE))}error(t){if(this.isClosed())return!1;let r=Qm.lang.castError(t);return this.emit(KL.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(KL.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(KL.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&Qm.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&Qm.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)Qm.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new rmy(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Qm.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(s=>s.handler===n&&(!s.filePath||s.filePath===i)&&s.options.ignore===r.ignore&&!!s.options.native==!!r.native&&(!r.recursive||s.options.recursive)))return!0;let a=Uer.default.dirname(t);for(let s=1;s<1/0;s++){if(this._watchers[a]?.find(u=>(s===1||u.options.recursive&&s<=(u.options.depth??oqt))&&u.handler===n&&(!u.filePath||u.filePath===i)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&aqt&&u.options.native!==!1)))return!0;if(!aqt)break;let l=Uer.default.dirname(t);if(a===l)break;a=l}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=Qm.lang.uniq(t).sort();let a;for(let s of t)if(!this.isIgnored(s,r.ignore)&&!this.watcherExists(s,r,n,i))try{let c=!r.recursive||aqt&&r.native!==!1?r:{...r,recursive:!1},u={watcher:dPa.default.watch(s,c),handler:n,options:r,folderPath:s,filePath:i},p=a=await this.watcherAdd(u,o);if(this._roots.has(i||s)){let m={...r,ignoreInitial:!0,recursive:!1},h=Uer.default.dirname(s),y=s;await this.watchDirectories([h],m,n,y,p)}}catch(c){this.error(c)}return a}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||aqt&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let a=r.depth??oqt,s=r.limit??svn,[c]=await Qm.fs.readdir(t,r.ignore,a,s,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let l=await this.watchDirectories([t],r,n,i,o);if(c.length){let u=Qm.fs.getDepth(t);for(let p of c){let d=Qm.fs.getDepth(p),m=Math.max(0,a-(d-u)),h={...r,depth:m};await this.watchDirectories([p],h,n,i,o||l)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(l,u)=>{u===t&&(c(),n())},a=new e(o),s=()=>{this._subwatchers.add(i),this.on(KL.CLOSE,c),a.watchFile(t,r,o)},c=()=>{this._subwatchers.delete(i),this.removeListener(KL.CLOSE,c),a.close()};return s()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=Uer.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new $6u,a=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,a(),n())})}async watchPolling(t,r,n){if(this.isClosed())return Qm.lang.noop;if(this.pollerExists(t,r))return Qm.lang.noop;let i={...r,interval:r.pollingInterval??Ldy},o={targetPath:t,options:r},a=()=>{this._pollers.add(o),this.on(KL.CLOSE,s),dPa.default.watchFile(t,i,n)},s=()=>{this._pollers.delete(o),this.removeListener(KL.CLOSE,s),dPa.default.unwatchFile(t,n)};return Qm.lang.attempt(a),()=>Qm.lang.attempt(s)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=Qm.lang.uniq(t).sort(),t.every((o,a)=>t.every((s,c)=>c===a||!Qm.fs.isSubPath(o,s))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=Uer.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await Qm.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=Uer.default.dirname(t);return(await Qm.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=Qm.lang.noop){if(Qm.lang.isFunction(t))return this.watch([],{},t);if(Qm.lang.isUndefined(t))return this.watch([],r,n);if(Qm.lang.isFunction(r))return this.watch(t,{},r);if(Qm.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=Qm.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==Qm.lang.noop&&this.on(KL.ALL,n),r.readdirMap=void 0,this.ready())}},mPa=J6u;$_a();var _3r=require("fs/promises"),amy=require("os"),smy=We(require("path"),1),ckx=".fern",lkx="logs";function pkx(){return"cli@3.72.0"}var dvn=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=vt(xr.of((0,amy.homedir)()),Xe.of(ckx)),r=vt(t,Xe.of(lkx));await un(r)||await(0,_3r.mkdir)(r,{recursive:!0});let i=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=vt(r,Xe.of(i));let o=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${smy.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2667
|
+
`+Un.dump(s)),o.logger.info(tt.green(`Added ${t} generator`)))})}))}var scy=require("fs/promises"),ucy=We(Y3(),1);async function ccy({context:e,from:t,to:r,fromVersion:n,generatorVersions:i}){let o=new HZr,a=kRx(await o.check({from:await acy({context:e,filepath:t,flagName:"from"}),to:await acy({context:e,filepath:r,flagName:"to"})})),s=WRx(e,i),{bump:c,errors:l}=URx(a,s);if(n==null)return{bump:c??"patch",errors:l};if(c==="no_change")return{bump:"no_change",nextVersion:n,errors:l};let u=c??"patch",p=ucy.default.inc(n,u);if(!p)throw e.failWithoutThrowing(`Invalid current version: ${n}`),new QP;return{bump:u,nextVersion:p,errors:l}}async function acy({context:e,filepath:t,flagName:r}){let n=xr.of(Ys(pb(),t));if(!await un(n,"file"))throw e.failWithoutThrowing(`File not found: ${n}`),new QP;let i=await(0,scy.readFile)(n,"utf-8"),o=Vo.IntermediateRepresentation.parse(JSON.parse(i));if(!o.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new QP;return o.value}function kRx(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function URx(e,t){return{bump:LRx(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function LRx(e,t){if(!(e===void 0&&t===void 0))return e==="no_change"&&(t===void 0||t==="no_change")||t==="no_change"&&(e===void 0||e==="no_change")?"no_change":e===void 0?t:t===void 0?e:e==="no_change"?t:t==="no_change"?e:e==="major"||t==="major"?"major":e==="minor"||t==="minor"?"minor":"patch"}function WRx(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:n}=t;try{let i=GRx(C2a(r,n)),o=[];return i==="major"&&o.push("Generator version changed by major version."),{bump:i,errors:o}}catch(i){throw e.failWithoutThrowing(`Error diffing generator versions ${r} and ${n}: ${i}`),new QP}}function GRx(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}BP();var fyy=We(b8u(),1),dyy=We(uPa(),1),zPa=require("fs/promises"),myy=We(require("http"),1),hyy=We(require("path"),1);var omy=require("events"),dPa=We(require("fs"),1),Uer=We(require("path"),1);var Vdy=We(require("os"),1),kdy=300,oqt=20,svn=1e7,Udy=Vdy.default.platform();var nkx=Udy==="darwin",M6u=Udy==="win32",aqt=nkx||M6u,Ldy=3e3,Wdy=2e4,z6u=1250;var jrt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(jrt||(jrt={}));var ker;(function(e){e.CHANGE="change",e.RENAME="rename"})(ker||(ker={}));var uvn;(function(e){e.CHANGE="change",e.ERROR="error"})(uvn||(uvn={}));var Nl;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Nl||(Nl={}));var KL;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(KL||(KL={}));var ikx=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),a,s,c=0,l=0,u=()=>{let A=Date.now(),v=A-c,P=A-l,I=v>=t||P>=o;return[A,I]},p=A=>{if(l=A,!a)return;let v=a;a=void 0,e.apply(void 0,v)},d=()=>{_(0)},m=()=>{s&&(d(),p(Date.now()))},h=A=>{if(l=A,n)return p(A)},y=A=>{if(i&&a)return p(A);a=void 0},g=()=>{s=void 0;let[A,v]=u();return v?y(A):b(A)},b=A=>{let v=A-c,P=A-l,I=t-v,E=o-P,x=Math.min(I,E);return _(x)},_=A=>{s&&clearTimeout(s),!(A<=0)&&(s=setTimeout(g,A))},O=(...A)=>{let[v,P]=u(),I=!!s;if(a=A,c=v,(P||!s)&&_(t),P)return I?p(v):h(v)};return O.cancel=d,O.flush=m,O},cPa=ikx;var k6u=We(require("fs"),1),pPa=We(require("path"),1);var t_=We(require("fs"),1),gQ=require("util");var Bft=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},Crt=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var Q6u=We(require("process"),1),Gdy=Q6u.default.getuid?!Q6u.default.getuid():!1,Hdy=1e4,X$=()=>{};var cvn={isChangeErrorOk:e=>{if(!cvn.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Gdy&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!cvn.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!cvn.isNodeError(e))throw e;if(!cvn.isChangeErrorOk(e))throw e}},YS=cvn;var q6u=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Hdy,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},$dy=new q6u;var Dft=(e,t)=>function(n){return function i(...o){return $dy.schedule().then(a=>{let s=l=>(a(),l),c=l=>{if(a(),Date.now()>=n)throw l;if(t(l)){let u=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,u)).then(()=>i.apply(void 0,o))}throw l};return e.apply(void 0,o).then(s,c)})}},Tft=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(a){if(Date.now()>n)throw a;if(t(a))return i.apply(void 0,o);throw a}}};var okx={attempt:{chmod:Bft((0,gQ.promisify)(t_.default.chmod),YS.onChangeError),chown:Bft((0,gQ.promisify)(t_.default.chown),YS.onChangeError),close:Bft((0,gQ.promisify)(t_.default.close),X$),fsync:Bft((0,gQ.promisify)(t_.default.fsync),X$),mkdir:Bft((0,gQ.promisify)(t_.default.mkdir),X$),realpath:Bft((0,gQ.promisify)(t_.default.realpath),X$),stat:Bft((0,gQ.promisify)(t_.default.stat),X$),unlink:Bft((0,gQ.promisify)(t_.default.unlink),X$),chmodSync:Crt(t_.default.chmodSync,YS.onChangeError),chownSync:Crt(t_.default.chownSync,YS.onChangeError),closeSync:Crt(t_.default.closeSync,X$),existsSync:Crt(t_.default.existsSync,X$),fsyncSync:Crt(t_.default.fsync,X$),mkdirSync:Crt(t_.default.mkdirSync,X$),realpathSync:Crt(t_.default.realpathSync,X$),statSync:Crt(t_.default.statSync,X$),unlinkSync:Crt(t_.default.unlinkSync,X$)},retry:{close:Dft((0,gQ.promisify)(t_.default.close),YS.isRetriableError),fsync:Dft((0,gQ.promisify)(t_.default.fsync),YS.isRetriableError),open:Dft((0,gQ.promisify)(t_.default.open),YS.isRetriableError),readFile:Dft((0,gQ.promisify)(t_.default.readFile),YS.isRetriableError),rename:Dft((0,gQ.promisify)(t_.default.rename),YS.isRetriableError),stat:Dft((0,gQ.promisify)(t_.default.stat),YS.isRetriableError),write:Dft((0,gQ.promisify)(t_.default.write),YS.isRetriableError),writeFile:Dft((0,gQ.promisify)(t_.default.writeFile),YS.isRetriableError),closeSync:Tft(t_.default.closeSync,YS.isRetriableError),fsyncSync:Tft(t_.default.fsyncSync,YS.isRetriableError),openSync:Tft(t_.default.openSync,YS.isRetriableError),readFileSync:Tft(t_.default.readFileSync,YS.isRetriableError),renameSync:Tft(t_.default.renameSync,YS.isRetriableError),statSync:Tft(t_.default.statSync,YS.isRetriableError),writeSync:Tft(t_.default.writeSync,YS.isRetriableError),writeFileSync:Tft(t_.default.writeFileSync,YS.isRetriableError)}},Jdy=okx;var lPa=We(require("fs"),1),lvn=We(require("path"),1);var V6u=()=>{};var akx=()=>{let e=V6u,t=V6u,r=!1,n=!1;return{promise:new Promise((c,l)=>{e=u=>(r=!0,c(u)),t=u=>(n=!0,l(u))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},Kdy=akx;var skx=()=>{let{promise:e,resolve:t,isPending:r}=Kdy(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},Ydy=skx;var Xdy={then:e=>{e()}};var Zdy=e=>Array.isArray(e)?e:[e],emy=e=>typeof e=="function";var ukx=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],a=Zdy(o).map(Z=>emy(Z)?Z:Y=>Z.test(Y)),s=Z=>a.some(Y=>Y(Z)),c=t?.signal??{aborted:!1},l=t?.onDirents||(()=>{}),u=[],p=new Set,d={},m=[],h=new Set,y={},g=[],b=new Set,_={},O={},A=new Set,v={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},P={directories:u,directoriesNames:p,directoriesNamesToPaths:d,files:m,filesNames:h,filesNamesToPaths:y,symlinks:g,symlinksNames:b,symlinksNamesToPaths:_,map:O},{promise:I,increment:E,decrement:x}=Ydy(),T=0,W=(Z,Y,Be,Pe)=>{A.has(Y)||T>=i||(T+=1,Z.directories.push(Y),Z.directoriesNames.add(Be),u.push(Y),p.add(Be),d.propertyIsEnumerable(Be)||(d[Be]=[]),d[Be].push(Y),A.add(Y),!(Pe>=n)&&(T>=i||te(Y,Pe+1)))},H=(Z,Y,Be)=>{A.has(Y)||T>=i||(T+=1,Z.files.push(Y),Z.filesNames.add(Be),m.push(Y),h.add(Be),y.propertyIsEnumerable(Be)||(y[Be]=[]),y[Be].push(Y),A.add(Y))},G=(Z,Y,Be,Pe)=>{A.has(Y)||T>=i||(T+=1,Z.symlinks.push(Y),Z.symlinksNames.add(Be),g.push(Y),b.add(Be),_.propertyIsEnumerable(Be)||(_[Be]=[]),_[Be].push(Y),A.add(Y),r&&(Pe>=n||T>=i||Ge(Y,Pe+1)))},ie=(Z,Y,Be,Pe,ke)=>{c.aborted||s(Y)||(Pe.isDirectory()?W(Z,Y,Be,ke):Pe.isFile()?H(Z,Y,Be):Pe.isSymbolicLink()&&G(Z,Y,Be,ke))},oe=(Z,Y,Be,Pe)=>{if(c.aborted)return;let ke=Y===lvn.default.sep?"":lvn.default.sep,Ye=Be.name,Oe=`${Y}${ke}${Ye}`;s(Oe)||(Be.isDirectory()?W(Z,Oe,Ye,Pe):Be.isFile()?H(Z,Oe,Ye):Be.isSymbolicLink()&&G(Z,Oe,Ye,Pe))},$=(Z,Y,Be,Pe)=>{for(let ke=0,Ye=Be.length;ke<Ye;ke++)oe(Z,Y,Be[ke],Pe)},te=(Z,Y)=>{c.aborted||Y>n||T>=i||(E(),lPa.default.readdir(Z,{withFileTypes:!0},(Be,Pe)=>{if(Be||c.aborted||!Pe.length)return x();(l(Pe)||Xdy).then(()=>{let Ye=O[Z]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};$(Ye,Z,Pe,Y),x()})}))},Ge=(Z,Y)=>{E(),lPa.default.realpath(Z,(Be,Pe)=>{if(Be||c.aborted)return x();lPa.default.stat(Pe,(ke,Ye)=>{if(ke||c.aborted)return x();let Oe=lvn.default.basename(Pe),he=O[Z]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};ie(he,Pe,Oe,Ye,Y),x()})})};return(async(Z,Y=1)=>(Z=lvn.default.normalize(Z),A.add(Z),te(Z,Y),await I,c.aborted?v:P))(e)},tmy=ukx;var Srt={lang:{debounce:cPa,attempt:e=>{try{return e()}catch(t){return Srt.lang.castError(t)}},castArray:e=>Srt.lang.isArray(e)?e:[e],castError:e=>Srt.lang.isError(e)?e:Srt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(Srt.lang.isNaN(e))return Srt.lang.isNaN(t);if(Srt.lang.isPrimitive(e)||Srt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(pPa.default.sep).length-1),getRealPath:(e,t)=>{try{return t?k6u.default.realpathSync.native(e):k6u.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===pPa.default.sep&&t.length-e.length>pPa.default.sep.length,poll:(e,t=Wdy)=>Jdy.retry.stat(t)(e,{bigint:!0}).catch(Srt.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let a=o[e];return[a.directories,a.files]}else{let a=await tmy(e,{depth:r,limit:n,ignore:t,signal:i});return[a.directories,a.files]}}}},Qm=Srt;var fPa=We(require("path"),1);var U6u=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Qm.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=kdy){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(s,c)=>{let l=this.options.ignoreInitial?[]:s,u=await this.eventsPopulate([...c]),p=this.eventsDeduplicate([...l,...u]);this.onTargetEvents(p)},a=Qm.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(s,c="",l=!1)=>{l?await this.eventsPopulate([c],n,!0):i.add(c),r.then(a)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,a]=i,s=r[a];return o===s||o===Nl.CHANGE&&s===Nl.ADD||(r[a]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async a=>{r.push([a,i]),a===Nl.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):a===Nl.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??oqt:Math.min(1,this.options.depth??oqt),a=this.options.limit??svn,[s,c]=await Qm.fs.readdir(r,this.options.ignore,o,a,this.watcher._closeSignal),l=[...s,...c];return await Promise.all(l.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())Qm.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Nl.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!aqt&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Nl.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Nl.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(fPa.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Nl.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(fPa.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Nl.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Nl.ADD?this.onTargetAdd(n):r===Nl.ADD_DIR?this.onTargetAddDir(n):r===Nl.CHANGE?this.onTargetChange(n):r===Nl.UNLINK?this.onTargetUnlink(n):r===Nl.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=ker.CHANGE,r){if(this.watcher.isClosed())return;let n=fPa.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){M6u&&t.code==="EPERM"?this.onWatcherChange(ker.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(uvn.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(uvn.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(ker.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&aqt&&this.options.native!==!1?this.options.depth??oqt:Math.min(1,this.options.depth??oqt),n=this.options.limit??svn,[i,o]=await Qm.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),a=[this.folderPath,...i,...o];await Promise.all(a.map(s=>{if(!this.watcher._poller.stats.has(s)&&!this.watcher.isIgnored(s,this.options.ignore))return this.onWatcherEvent(ker.CHANGE,s,t)}))}}},rmy=U6u;var YL={interval:100,intervalId:void 0,fns:new Map,init:()=>{YL.intervalId||(YL.intervalId=setInterval(YL.resolve,YL.interval))},reset:()=>{YL.intervalId&&(clearInterval(YL.intervalId),delete YL.intervalId)},add:(e,t)=>{YL.fns.set(e,Date.now()+t),YL.init()},remove:e=>{YL.fns.delete(e)},resolve:()=>{if(!YL.fns.size)return YL.reset();let e=Date.now();for(let[t,r]of YL.fns)r>=e||(YL.remove(t),t())}},pvn=YL;var fvn=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=z6u){let{ino:n,targetPath:i,events:o,locks:a}=t,s=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(Qm.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return s();let c=()=>{a.add.delete(n),pvn.remove(l)},l=()=>{c(),s()};pvn.add(l,r);let u=()=>{let p=a.unlink.get(n);if(!p)return;c();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};a.add.set(n,u),u()}getLockUnlink(t,r=z6u){let{ino:n,targetPath:i,events:o,locks:a}=t,s=()=>{this._watcher.event(o.unlink,i)};if(!n)return s();let c=()=>{a.unlink.delete(n),pvn.remove(l)},l=()=>{c(),s()};pvn.add(l,r);let u=()=>(c(),i);a.unlink.set(n,u),a.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Nl.ADD,jrt.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,Nl.ADD_DIR,jrt.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,Nl.UNLINK,jrt.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,Nl.UNLINK_DIR,jrt.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};fvn.DIR_EVENTS={add:Nl.ADD_DIR,rename:Nl.RENAME_DIR,unlink:Nl.UNLINK_DIR};fvn.FILE_EVENTS={add:Nl.ADD,change:Nl.CHANGE,rename:Nl.RENAME,unlink:Nl.UNLINK};var nmy=fvn;var L6u=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Qm.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(Qm.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(Qm.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(Qm.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return Qm.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);Qm.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},W6u=L6u;var G6u=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},imy=G6u;var H6u=class{constructor(){this.inos={},this.paths=new W6u,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await Qm.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new imy(n)}reset(){this.inos={},this.paths=new W6u,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,Nl.ADD,i),[Nl.ADD];if(i.isDirectory())return this.updateIno(t,Nl.ADD_DIR,i),[Nl.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Nl.UNLINK,n),[Nl.UNLINK];if(n.isDirectory())return this.updateIno(t,Nl.UNLINK_DIR,n),[Nl.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Nl.CHANGE,i),[Nl.CHANGE]);if(i.isDirectory())return this.updateIno(t,Nl.UNLINK,n),this.updateIno(t,Nl.ADD_DIR,i),[Nl.UNLINK,Nl.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Nl.UNLINK_DIR,n),this.updateIno(t,Nl.ADD,i),[Nl.UNLINK_DIR,Nl.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Nl.UNLINK_DIR,n),this.updateIno(t,Nl.ADD_DIR,i),[Nl.UNLINK_DIR,Nl.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?jrt.FILE:jrt.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},$6u=H6u;var J6u=class e extends omy.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(KL.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(KL.CLOSE,i)),this._readyWait=new Promise(i=>this.on(KL.READY,i)),this._locker=new nmy(this),this._roots=new Set,this._poller=new $6u,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Qm.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(KL.CLOSE))}error(t){if(this.isClosed())return!1;let r=Qm.lang.castError(t);return this.emit(KL.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(KL.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(KL.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&Qm.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&Qm.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)Qm.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new rmy(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Qm.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(s=>s.handler===n&&(!s.filePath||s.filePath===i)&&s.options.ignore===r.ignore&&!!s.options.native==!!r.native&&(!r.recursive||s.options.recursive)))return!0;let a=Uer.default.dirname(t);for(let s=1;s<1/0;s++){if(this._watchers[a]?.find(u=>(s===1||u.options.recursive&&s<=(u.options.depth??oqt))&&u.handler===n&&(!u.filePath||u.filePath===i)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&aqt&&u.options.native!==!1)))return!0;if(!aqt)break;let l=Uer.default.dirname(t);if(a===l)break;a=l}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=Qm.lang.uniq(t).sort();let a;for(let s of t)if(!this.isIgnored(s,r.ignore)&&!this.watcherExists(s,r,n,i))try{let c=!r.recursive||aqt&&r.native!==!1?r:{...r,recursive:!1},u={watcher:dPa.default.watch(s,c),handler:n,options:r,folderPath:s,filePath:i},p=a=await this.watcherAdd(u,o);if(this._roots.has(i||s)){let m={...r,ignoreInitial:!0,recursive:!1},h=Uer.default.dirname(s),y=s;await this.watchDirectories([h],m,n,y,p)}}catch(c){this.error(c)}return a}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||aqt&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let a=r.depth??oqt,s=r.limit??svn,[c]=await Qm.fs.readdir(t,r.ignore,a,s,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let l=await this.watchDirectories([t],r,n,i,o);if(c.length){let u=Qm.fs.getDepth(t);for(let p of c){let d=Qm.fs.getDepth(p),m=Math.max(0,a-(d-u)),h={...r,depth:m};await this.watchDirectories([p],h,n,i,o||l)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(l,u)=>{u===t&&(c(),n())},a=new e(o),s=()=>{this._subwatchers.add(i),this.on(KL.CLOSE,c),a.watchFile(t,r,o)},c=()=>{this._subwatchers.delete(i),this.removeListener(KL.CLOSE,c),a.close()};return s()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=Uer.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new $6u,a=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,a(),n())})}async watchPolling(t,r,n){if(this.isClosed())return Qm.lang.noop;if(this.pollerExists(t,r))return Qm.lang.noop;let i={...r,interval:r.pollingInterval??Ldy},o={targetPath:t,options:r},a=()=>{this._pollers.add(o),this.on(KL.CLOSE,s),dPa.default.watchFile(t,i,n)},s=()=>{this._pollers.delete(o),this.removeListener(KL.CLOSE,s),dPa.default.unwatchFile(t,n)};return Qm.lang.attempt(a),()=>Qm.lang.attempt(s)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=Qm.lang.uniq(t).sort(),t.every((o,a)=>t.every((s,c)=>c===a||!Qm.fs.isSubPath(o,s))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=Uer.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await Qm.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=Uer.default.dirname(t);return(await Qm.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=Qm.lang.noop){if(Qm.lang.isFunction(t))return this.watch([],{},t);if(Qm.lang.isUndefined(t))return this.watch([],r,n);if(Qm.lang.isFunction(r))return this.watch(t,{},r);if(Qm.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=Qm.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==Qm.lang.noop&&this.on(KL.ALL,n),r.readdirMap=void 0,this.ready())}},mPa=J6u;$_a();var _3r=require("fs/promises"),amy=require("os"),smy=We(require("path"),1),ckx=".fern",lkx="logs";function pkx(){return"cli@3.72.1"}var dvn=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=vt(xr.of((0,amy.homedir)()),Xe.of(ckx)),r=vt(t,Xe.of(lkx));await un(r)||await(0,_3r.mkdir)(r,{recursive:!0});let i=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=vt(r,Xe.of(i));let o=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${smy.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2668
2668
|
`);await(0,_3r.writeFile)(this.logFilePath,o,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
|
|
2669
2669
|
`;try{await(0,_3r.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let n={timestamp:t.timestamp,source:pkx(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(n)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let n={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliDocsGeneration(t,r){let n={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliValidation(t,r){let n={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(n)}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var yWu=We(iWu(),1),iyy=We(x1u(),1),Z$=require("fs/promises"),oyy=require("os"),ayy=We(TM(),1),syy=We(ryy(),1),DPa=process.platform==="win32",hWu=tt.cyan("[docs]:"),Nkx="etag",Mkx=23,nyy=e=>e.padEnd(Mkx," "),zkx="preview",Qkx="app-preview",qkx="bundle",Vkx=".next",kkx="standalone",Ukx=".fern",Lkx="packages/fern-docs/bundle/.next/server/instrumentation.js",Wkx=".npmrc",Gkx=".pnpmfile.cjs",Hkx="pnpm-workspace.yaml",$kx='Cannot find matching keyid: {"signatures":';function Jkx(){return vt(xr.of((0,oyy.homedir)()),Xe.of(Ukx))}function v3r({app:e=!1}){return vt(Jkx(),Xe.of(e?Qkx:zkx))}function cqt({app:e=!1}){return vt(v3r({app:e}),Xe.of(e?Vkx:qkx))}function yvn({app:e=!1}){return vt(cqt({app:e}),Xe.of(kkx))}function Kkx({app:e=!1}){return vt(yvn({app:e}),Xe.of(Lkx))}function Ykx({app:e=!1}){return vt(yvn({app:e}),Xe.of(Hkx))}function Xkx({app:e=!1}){return vt(yvn({app:e}),Xe.of(Gkx))}function Zkx({app:e=!1}){return vt(yvn({app:e}),Xe.of(Wkx))}function Ger(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function eUx({app:e=!1}){return vt(v3r({app:e}),Xe.of(Nkx))}var tUx=`module.exports = {
|
|
2670
2670
|
hooks: {
|