fern-api 0.45.0-rc24 → 0.45.0-rc25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +4 -4
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1818,7 +1818,7 @@ ${l.indent}`:""}${vtl(o)}:${f.indent?" ":""}`;return u=!1,c=!0,f.objectItem=void
1818
1818
  `}),r.replaceAll(/\n$/g,"")}function r21(e){return e?nl.green(jzr.radioOn):jzr.radioOff}var Xga=Yo(fDe(),1);function HOf(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var pvi=class extends LF{_run(t){this.done=t;let r=LH(this.rl),n=r.line.pipe((0,Xga.map)(this.filterInput.bind(this))),i=this.handleSubmitEvents(n);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),r.keypress.pipe((0,Xga.takeUntil)(i.success)).forEach(this.onKeypress.bind(this)),this.render(),this}render(t){let r=this.getQuestion(),n="";r+=this.status==="answered"?this.getMaskedValue(this.answer):this.getMaskedValue(this.rl.line||""),t&&(n=`
1819
1819
  `+nl.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?nl.cyan(HOf(t,this.opt.mask)):nl.italic.dim("[hidden]"):this.opt.mask?HOf(t,this.opt.mask):nl.italic.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 y1f=Yo(h1f(),1),v1f=Yo(fDe(),1);var wvi=class extends LF{_run(t){this.done=t,this.editorResult=new v1f.Subject;let r=LH(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"?nl.dim("Received"):nl.dim("Press <enter> to launch your preferred editor."),t&&(r=nl.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),(0,y1f.editAsync)(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 D1f=Yo(m1f(),1);var w1f=Yo(require("readline"),1),j1f=Yo(P1f(),1),Brn=class{constructor(t){this.rl||=w1f.default.createInterface(J21(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 J21(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 j1f.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var jvi=class extends Brn{constructor(t={}){super(t),this.log=(0,D1f.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return avi(this.rl,this.bottomBar.split(`
1820
1820
  `).length),this}updateBottomBar(t){return avi(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+`
1821
- `}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&&Gga(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var B1f=Yo(A1f(),1),N1f=Yo(Whu(),1),z1f=Yo(q1f(),1),$C=Yo(fDe(),1),R1f=Yo(p0i(),1);var vma=Yo(fDe(),1),I1f=Yo(p0i(),1),bma=function(e,t,r){return typeof e[t]!="function"?(0,vma.of)(e):(0,vma.from)((0,I1f.default)(e[t])(r).then(n=>(e[t]=n,e)))};var Dvi={isPlainObject:B1f.default,set:z1f.default,get:N1f.default},$4n=class extends Brn{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=Dvi.isPlainObject(r)?{...r}:{},Dvi.isPlainObject(t)&&(t=Object.values(t).every(i=>Dvi.isPlainObject(i)&&i.name===void 0)?Object.entries(t).map(([i,a])=>({name:i,...a})):[t]);let n=Array.isArray(t)?(0,$C.from)(t):t;return this.process=n.pipe((0,$C.concatMap)(this.processQuestion.bind(this)),(0,$C.publish)()),this.process.connect(),this.process.pipe((0,$C.reduce)((i,a)=>(Dvi.set(i,a.name,a.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,$C.defer)(()=>(0,$C.of)(t).pipe((0,$C.concatMap)(this.setDefaultType.bind(this)),(0,$C.concatMap)(this.filterIfRunnable.bind(this)),(0,$C.concatMap)(()=>bma(t,"message",this.answers)),(0,$C.concatMap)(()=>bma(t,"default",this.answers)),(0,$C.concatMap)(()=>bma(t,"choices",this.answers)),(0,$C.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,$C.defer)(()=>(0,$C.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,$C.defer)(()=>(0,$C.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Dvi.get(this.answers,t.name)!==void 0)return(0,$C.empty)();if(t.when===!1)return(0,$C.empty)();if(typeof t.when!="function")return(0,$C.of)(t);let{answers:r}=this;return(0,$C.defer)(()=>(0,$C.from)((0,R1f.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,$C.filter)(n=>n!=null)))}};function F1f(e){let t=function(r,n){let i;try{i=new $4n(t.prompts,e)}catch(u){return Promise.reject(u)}let a=i.run(r,n);return a.ui=i,a};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",uvi),this.registerPrompt("input",Arn),this.registerPrompt("number",svi),this.registerPrompt("confirm",cvi),this.registerPrompt("rawlist",lvi),this.registerPrompt("expand",fvi),this.registerPrompt("checkbox",dvi),this.registerPrompt("password",pvi),this.registerPrompt("editor",wvi)},t.restoreDefaultPrompts(),t}var L0u=F1f();function lq1(e,t){L0u.registerPrompt(e,t)}function fq1(){L0u.restoreDefaultPrompts()}var dq1={prompt:L0u,ui:{BottomBar:jvi,Prompt:$4n},createPromptModule:F1f,registerPrompt:lq1,restoreDefaultPrompts:fq1,Separator:tae},gma=dq1;var $1f=Yo(L1f()),K1f=Yo(elu()),V0u=function(e,t){return V0u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},V0u(e,t)};function K4n(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");V0u(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}var Gg=function(){return Gg=Object.assign||function(t){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])}return t},Gg.apply(this,arguments)};function pq1(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r}function gC(e,t,r,n){function i(a){return a instanceof r?a:new r(function(u){u(a)})}return new(r||(r=Promise))(function(a,u){function f(o){try{c(n.next(o))}catch(l){u(l)}}function d(o){try{c(n.throw(o))}catch(l){u(l)}}function c(o){o.done?a(o.value):i(o.value).then(f,d)}c((n=n.apply(e,t||[])).next())})}function mC(e,t){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},n,i,a,u;return u={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(u[Symbol.iterator]=function(){return this}),u;function f(c){return function(o){return d([c,o])}}function d(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=c[0]&2?i.return:c[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,c[1])).done)return a;switch(i=0,a&&(c=[c[0]&2,a.value]),c[0]){case 0:case 1:a=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(a=r.trys,!(a=a.length>0&&a[a.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!a||c[1]>a[0]&&c[1]<a[3])){r.label=c[1];break}if(c[0]===6&&r.label<a[1]){r.label=a[1],a=c;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(c);break}a[2]&&r.ops.pop(),r.trys.pop();continue}c=t.call(e,r)}catch(o){c=[6,o],i=0}finally{n=a=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function Y1f(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,a;n<i;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}var W0u="3.1.2",pw;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties"})(pw||(pw={}));function _q1(e,t){if(!e)throw new Error(t)}function hq1(e){return e?.replace(/\/+$/,"")}function yq1(e,t){return t===void 0&&(t={}),gC(this,void 0,void 0,function(){var r,n,i,a,u,f,d,c,o,l;return mC(this,function(g){switch(g.label){case 0:r=t.retryCount,n=r===void 0?3:r,i=t.retryDelay,a=i===void 0?5e3:i,u=t.retryCheck,f=u===void 0?function(){return!0}:u,d=null,c=0,g.label=1;case 1:return c<n+1?c>0?[4,new Promise(function(O){return setTimeout(O,a)})]:[3,3]:[3,7];case 2:g.sent(),g.label=3;case 3:return g.trys.push([3,5,,6]),[4,e()];case 4:return o=g.sent(),[2,o];case 5:if(l=g.sent(),d=l,!f(l))throw l;return[3,6];case 6:return c++,[3,1];case 7:throw d}})})}function H0u(e){var t=new Date().getTime(),r=e&&e.performance&&e.performance.now&&e.performance.now()*1e3||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var i=Math.random()*16;return t>0?(i=(t+i)%16|0,t=Math.floor(t/16)):(i=(r+i)%16|0,r=Math.floor(r/16)),(n==="x"?i:i&3|8).toString(16)})}function vq1(){return new Date().getTime()}function U1f(){return new Date().toISOString()}function X1f(e,t){var r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var Evi=String.fromCharCode,V1f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",mma={};function bq1(e,t){if(!mma[e]){mma[e]={};for(var r=0;r<e.length;r++)mma[e][e.charAt(r)]=r}return mma[e][t]}var Avi={compressToBase64:function(e){if(e==null)return"";var t=Avi._compress(e,6,function(r){return V1f.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:Avi._decompress(e.length,32,function(t){return bq1(V1f,e.charAt(t))})},compress:function(e){return Avi._compress(e,16,function(t){return Evi(t)})},_compress:function(e,t,r){if(e==null)return"";var n={},i={},a=[],u,f,d="",c="",o="",l=2,g=3,O=2,P=0,j=0,M;for(M=0;M<e.length;M+=1)if(d=e.charAt(M),Object.prototype.hasOwnProperty.call(n,d)||(n[d]=g++,i[d]=!0),c=o+d,Object.prototype.hasOwnProperty.call(n,c))o=c;else{if(Object.prototype.hasOwnProperty.call(i,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)P=P<<1,j==t-1?(j=0,a.push(r(P)),P=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)P=P<<1|f,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete i[o]}else for(f=n[o],u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++),n[c]=g++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(i,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)P=P<<1,j==t-1?(j=0,a.push(r(P)),P=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)P=P<<1|f,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete i[o]}else for(f=n[o],u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++)}for(f=2,u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;for(;;)if(P=P<<1,j==t-1){a.push(r(P));break}else j++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:Avi._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){var n=[],i=[],a={val:r(0),position:t,index:1},u=4,f=4,d=3,c="",o,l,g,O,P,j,M;for(o=0;o<3;o+=1)n[o]=o;for(g=0,P=Math.pow(2,2),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;switch(g){case 0:for(g=0,P=Math.pow(2,8),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;M=Evi(g);break;case 1:for(g=0,P=Math.pow(2,16),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;M=Evi(g);break;case 2:return""}for(n[3]=M,l=M,i.push(M);;){if(a.index>e)return"";for(g=0,P=Math.pow(2,d),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;switch(M=g){case 0:for(g=0,P=Math.pow(2,8),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;n[f++]=Evi(g),M=f-1,u--;break;case 1:for(g=0,P=Math.pow(2,16),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;n[f++]=Evi(g),M=f-1,u--;break;case 2:return i.join("")}if(u==0&&(u=Math.pow(2,d),d++),n[M])c=n[M];else if(M===f)c=l+l.charAt(0);else return null;i.push(c),n[f++]=l+c.charAt(0),u--,l=c,u==0&&(u=Math.pow(2,d),d++)}}},gq1=function(){function e(){this.events={},this.events={}}return e.prototype.on=function(t,r){var n=this;return this.events[t]||(this.events[t]=[]),this.events[t].push(r),function(){n.events[t]=n.events[t].filter(function(i){return i!==r})}},e.prototype.emit=function(t,r){for(var n=0,i=this.events[t]||[];n<i.length;n++){var a=i[n];a(r)}for(var u=0,f=this.events["*"]||[];u<f.length;u++){var a=f[u];a(t,r)}},e}(),mq1=function(e){K4n(t,e);function t(r){var n=e.call(this,"HTTP error while fetching PostHog: "+r.status)||this;return n.response=r,n.name="PostHogFetchHttpError",n}return t}(Error),Oq1=function(e){K4n(t,e);function t(r){var n=e.call(this,"Network error while fetching PostHog",r instanceof Error?{cause:r}:{})||this;return n.error=r,n.name="PostHogFetchNetworkError",n}return t}(Error);function W1f(e){return typeof e=="object"&&(e.name==="PostHogFetchHttpError"||e.name==="PostHogFetchNetworkError")}var Z1f=function(){function e(t,r){var n,i,a,u,f;this.debugMode=!1,this.pendingPromises={},this.disableGeoip=!0,this._events=new gq1,_q1(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=hq1(r?.host||"https://app.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.flushInterval=(n=r?.flushInterval)!==null&&n!==void 0?n:1e4,this.captureMode=r?.captureMode||"form",this._optoutOverride=r?.enable===!1,this._retryOptions={retryCount:(i=r?.fetchRetryCount)!==null&&i!==void 0?i:3,retryDelay:(a=r?.fetchRetryDelay)!==null&&a!==void 0?a:3e3,retryCheck:W1f},this.requestTimeout=(u=r?.requestTimeout)!==null&&u!==void 0?u:1e4,this.disableGeoip=(f=r?.disableGeoip)!==null&&f!==void 0?f:!0}return e.prototype.getCommonEventProperties=function(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}},Object.defineProperty(e.prototype,"optedOut",{get:function(){var t,r;return(r=(t=this.getPersistedProperty(pw.OptedOut))!==null&&t!==void 0?t:this._optoutOverride)!==null&&r!==void 0?r:!1},enumerable:!1,configurable:!0}),e.prototype.optIn=function(){this.setPersistedProperty(pw.OptedOut,!1)},e.prototype.optOut=function(){this.setPersistedProperty(pw.OptedOut,!0)},e.prototype.on=function(t,r){return this._events.on(t,r)},e.prototype.debug=function(t){var r;t===void 0&&(t=!0),(r=this.removeDebugCallback)===null||r===void 0||r.call(this),this.debugMode=t,t&&(this.removeDebugCallback=this.on("*",function(n,i){return console.log("PostHog Debug",n,i)}))},e.prototype.buildPayload=function(t){return{distinct_id:t.distinct_id,event:t.event,properties:Gg(Gg({},t.properties||{}),this.getCommonEventProperties())}},e.prototype.identifyStateless=function(t,r,n){var i=Gg({},this.buildPayload({distinct_id:t,event:"$identify",properties:r}));return this.enqueue("identify",i,n),this},e.prototype.captureStateless=function(t,r,n,i){var a=this.buildPayload({distinct_id:t,event:r,properties:n});return this.enqueue("capture",a,i),this},e.prototype.aliasStateless=function(t,r,n,i){var a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:Gg(Gg({},n||{}),{distinct_id:r,alias:t})});return this.enqueue("alias",a,i),this},e.prototype.groupIdentifyStateless=function(t,r,n,i,a,u){var f=this.buildPayload({distinct_id:a||"$".concat(t,"_").concat(r),event:"$groupidentify",properties:Gg({$group_type:t,$group_key:r,$group_set:n||{}},u||{})});return this.enqueue("capture",f,i),this},e.prototype.getDecide=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var u,f;return mC(this,function(d){return u="".concat(this.host,"/decide/?v=3"),f={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Gg({token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i},a))},[2,this.fetchWithRetry(u,f).then(function(c){return c.json()}).catch(function(c){console.error("Error fetching feature flags",c)})]})})},e.prototype.getFeatureFlagStateless=function(t,r,n,i,a,u){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var f,d;return mC(this,function(c){switch(c.label){case 0:return[4,this.getFeatureFlagsStateless(r,n,i,a,u)];case 1:return f=c.sent(),f?(d=f[t],d===void 0&&(d=!1),[2,d]):[2,void 0]}})})},e.prototype.getFeatureFlagPayloadStateless=function(t,r,n,i,a,u){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var f,d;return mC(this,function(c){switch(c.label){case 0:return[4,this.getFeatureFlagPayloadsStateless(r,n,i,a,u)];case 1:return f=c.sent(),f?(d=f[t],d===void 0?[2,null]:[2,this._parsePayload(d)]):[2,void 0]}})})},e.prototype.getFeatureFlagPayloadsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var u,f=this;return mC(this,function(d){switch(d.label){case 0:return[4,this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a)];case 1:return u=d.sent().payloads,u?[2,Object.fromEntries(Object.entries(u).map(function(c){var o=c[0],l=c[1];return[o,f._parsePayload(l)]}))]:[2,u]}})})},e.prototype._parsePayload=function(t){try{return JSON.parse(t)}catch{return t}},e.prototype.getFeatureFlagsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){return mC(this,function(u){switch(u.label){case 0:return[4,this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a)];case 1:return[2,u.sent().flags]}})})},e.prototype.getFeatureFlagsAndPayloadsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var u,f,d,c;return mC(this,function(o){switch(o.label){case 0:return u={},(a??this.disableGeoip)&&(u.geoip_disable=!0),[4,this.getDecide(t,r,n,i,u)];case 1:return f=o.sent(),d=f?.featureFlags,c=f?.featureFlagPayloads,[2,{flags:d,payloads:c}]}})})},e.prototype.enqueue=function(t,r,n){var i=this,a;if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.enable()");return}var u=Gg(Gg({},r),{type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:U1f()}),f=(a=n?.disableGeoip)!==null&&a!==void 0?a:this.disableGeoip;f&&(u.properties||(u.properties={}),u.properties.$geoip_disable=!0),u.distinctId&&(u.distinct_id=u.distinctId,delete u.distinctId);var d=this.getPersistedProperty(pw.Queue)||[];d.push({message:u}),this.setPersistedProperty(pw.Queue,d),this._events.emit(t,u),d.length>=this.flushAt&&this.flush(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=X1f(function(){return i.flush()},this.flushInterval))},e.prototype.flushAsync=function(){var t=this;return new Promise(function(r,n){t.flush(function(i,a){return i?n(i):r(a)})})},e.prototype.flush=function(t){var r=this;this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null);var n=this.getPersistedProperty(pw.Queue)||[];if(!n.length)return t?.();var i=n.splice(0,this.flushAt);this.setPersistedProperty(pw.Queue,n);var a=i.map(function(O){return O.message}),u={api_key:this.apiKey,batch:a,sent_at:U1f()},f=H0u(),d=function(O){O&&r._events.emit("error",O),t?.(O,a),delete r.pendingPromises[f],r._events.emit("flush",a)};this.getCustomUserAgent();var c=JSON.stringify(u),o=this.captureMode==="form"?"".concat(this.host,"/e/?ip=1&_=").concat(vq1(),"&v=").concat(this.getLibraryVersion()):"".concat(this.host,"/batch/"),l=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"data=".concat(encodeURIComponent(Avi.compressToBase64(c)),"&compression=lz64")}:{method:"POST",headers:{"Content-Type":"application/json"},body:c},g=this.fetchWithRetry(o,l);this.pendingPromises[f]=g,g.then(function(){return d()}).catch(function(O){d(O)})},e.prototype.fetchWithRetry=function(t,r,n){var i,a;return gC(this,void 0,void 0,function(){var u=this;return mC(this,function(f){switch(f.label){case 0:return(i=(a=AbortSignal).timeout)!==null&&i!==void 0||(a.timeout=function(c){var o=new AbortController;return setTimeout(function(){return o.abort()},c),o.signal}),[4,yq1(function(){return gC(u,void 0,void 0,function(){var d,c;return mC(this,function(o){switch(o.label){case 0:d=null,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this.fetch(t,Gg({signal:AbortSignal.timeout(this.requestTimeout)},r))];case 2:return d=o.sent(),[3,4];case 3:throw c=o.sent(),new Oq1(c);case 4:if(d.status<200||d.status>=400)throw new mq1(d);return[2,d]}})})},Gg(Gg({},this._retryOptions),n))];case 1:return[2,f.sent()]}})})},e.prototype.shutdownAsync=function(){return gC(this,void 0,void 0,function(){var t;return mC(this,function(r){switch(r.label){case 0:clearTimeout(this._flushTimer),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.flushAsync()];case 2:return r.sent(),[4,Promise.all(Object.values(this.pendingPromises).map(function(n){return n.catch(function(){})}))];case 3:return r.sent(),[3,5];case 4:if(t=r.sent(),!W1f(t))throw t;return console.error("Error while shutting down PostHog",t),[3,5];case 5:return[2]}})})},e.prototype.shutdown=function(){this.shutdownAsync()},e}();(function(e){K4n(t,e);function t(r,n){var i=this,a,u,f,d=(a=n?.disableGeoip)!==null&&a!==void 0?a:!1;return i=e.call(this,r,Gg(Gg({},n),{disableGeoip:d}))||this,i.flagCallReported={},i.sessionProps={},i.sendFeatureFlagEvent=(u=n?.sendFeatureFlagEvent)!==null&&u!==void 0?u:!0,i._sessionExpirationTimeSeconds=(f=n?.sessionExpirationTimeSeconds)!==null&&f!==void 0?f:1800,i}return t.prototype.setupBootstrap=function(r){var n,i,a,u;if(!((n=r?.bootstrap)===null||n===void 0)&&n.distinctId&&(!((i=r?.bootstrap)===null||i===void 0)&&i.isIdentifiedId?this.setPersistedProperty(pw.DistinctId,r.bootstrap.distinctId):this.setPersistedProperty(pw.AnonymousId,r.bootstrap.distinctId)),!((a=r?.bootstrap)===null||a===void 0)&&a.featureFlags){var f=Object.keys(((u=r.bootstrap)===null||u===void 0?void 0:u.featureFlags)||{}).filter(function(d){var c,o;return!!(!((o=(c=r.bootstrap)===null||c===void 0?void 0:c.featureFlags)===null||o===void 0)&&o[d])}).reduce(function(d,c){var o,l;return d[c]=((l=(o=r.bootstrap)===null||o===void 0?void 0:o.featureFlags)===null||l===void 0?void 0:l[c])||!1,d},{});this.setKnownFeatureFlags(f),r?.bootstrap.featureFlagPayloads&&this.setKnownFeatureFlagPayloads(r?.bootstrap.featureFlagPayloads)}},Object.defineProperty(t.prototype,"props",{get:function(){return this._props||(this._props=this.getPersistedProperty(pw.Props)),this._props||{}},set:function(r){this._props=r},enumerable:!1,configurable:!0}),t.prototype.clearProps=function(){this.props=void 0,this.sessionProps={}},t.prototype.on=function(r,n){return this._events.on(r,n)},t.prototype.reset=function(r){var n=Y1f([pw.Queue],r||[],!0);this.clearProps();for(var i=0,a=Object.keys(pw);i<a.length;i++){var u=a[i];n.includes(pw[u])||this.setPersistedProperty(pw[u],null)}},t.prototype.getCommonEventProperties=function(){var r=this.getFeatureFlags(),n={};if(r)for(var i=0,a=Object.entries(r);i<a.length;i++){var u=a[i],f=u[0],d=u[1];n["$feature/".concat(f)]=d}return Gg(Gg({$active_feature_flags:r?Object.keys(r):void 0},n),e.prototype.getCommonEventProperties.call(this))},t.prototype.enrichProperties=function(r){return Gg(Gg(Gg(Gg(Gg({},this.props),this.sessionProps),r||{}),this.getCommonEventProperties()),{$session_id:this.getSessionId()})},t.prototype.getSessionId=function(){var r=this.getPersistedProperty(pw.SessionId),n=this.getPersistedProperty(pw.SessionLastTimestamp)||0;return(!r||Date.now()-n>this._sessionExpirationTimeSeconds*1e3)&&(r=H0u(globalThis),this.setPersistedProperty(pw.SessionId,r)),this.setPersistedProperty(pw.SessionLastTimestamp,Date.now()),r},t.prototype.resetSessionId=function(){this.setPersistedProperty(pw.SessionId,null)},t.prototype.getAnonymousId=function(){var r=this.getPersistedProperty(pw.AnonymousId);return r||(r=H0u(globalThis),this.setPersistedProperty(pw.AnonymousId,r)),r},t.prototype.getDistinctId=function(){return this.getPersistedProperty(pw.DistinctId)||this.getAnonymousId()},t.prototype.unregister=function(r){delete this.props[r],this.setPersistedProperty(pw.Props,this.props)},t.prototype.register=function(r){this.props=Gg(Gg({},this.props),r),this.setPersistedProperty(pw.Props,this.props)},t.prototype.registerForSession=function(r){this.sessionProps=Gg(Gg({},this.sessionProps),r)},t.prototype.unregisterForSession=function(r){delete this.sessionProps[r]},t.prototype.identify=function(r,n,i){var a=this.getDistinctId();r=r||a,n?.$groups&&this.groups(n.$groups);var u=this.enrichProperties(Gg(Gg({},n),{$anon_distinct_id:this.getAnonymousId(),$set:n}));return r!==a&&(this.setPersistedProperty(pw.AnonymousId,a),this.setPersistedProperty(pw.DistinctId,r),this.reloadFeatureFlags()),e.prototype.identifyStateless.call(this,r,u,i),this},t.prototype.capture=function(r,n,i){var a=this.getDistinctId();n?.$groups&&this.groups(n.$groups);var u=this.enrichProperties(n);return e.prototype.captureStateless.call(this,a,r,u,i),this},t.prototype.alias=function(r){var n=this.getDistinctId(),i=this.enrichProperties({});return e.prototype.aliasStateless.call(this,r,n,i),this},t.prototype.autocapture=function(r,n,i,a){i===void 0&&(i={});var u=this.getDistinctId(),f={distinct_id:u,event:"$autocapture",properties:Gg(Gg({},this.enrichProperties(i)),{$event_type:r,$elements:n})};return this.enqueue("autocapture",f,a),this},t.prototype.groups=function(r){var n=this.props.$groups||{};return this.register({$groups:Gg(Gg({},n),r)}),Object.keys(r).find(function(i){return n[i]!==r[i]})&&this.reloadFeatureFlags(),this},t.prototype.group=function(r,n,i,a){var u;return this.groups((u={},u[r]=n,u)),i&&this.groupIdentify(r,n,i,a),this},t.prototype.groupIdentify=function(r,n,i,a){var u=this.getDistinctId(),f=this.enrichProperties({});return e.prototype.groupIdentifyStateless.call(this,r,n,i,a,u,f),this},t.prototype.personProperties=function(r){var n=this.getPersistedProperty(pw.PersonProperties)||{};return this.setPersistedProperty(pw.PersonProperties,Gg(Gg({},n),r)),this},t.prototype.groupProperties=function(r){var n=this.getPersistedProperty(pw.GroupProperties)||{};return Object.keys(n).length!==0&&Object.keys(n).forEach(function(i){n[i]=Gg(Gg({},n[i]),r[i]),delete r[i]}),this.setPersistedProperty(pw.GroupProperties,Gg(Gg({},n),r)),this},t.prototype.decideAsync=function(r){return r===void 0&&(r=!0),this._decideResponsePromise?this._decideResponsePromise:this._decideAsync(r)},t.prototype._decideAsync=function(r){return r===void 0&&(r=!0),gC(this,void 0,void 0,function(){var n,i,a,u,f,d=this;return mC(this,function(c){return n=this.getDistinctId(),i=this.props.$groups||{},a=this.getPersistedProperty(pw.PersonProperties)||{},u=this.getPersistedProperty(pw.GroupProperties)||{},f={$anon_distinct_id:r?this.getAnonymousId():void 0},this._decideResponsePromise=e.prototype.getDecide.call(this,n,i,a,u,f).then(function(o){if(o?.featureFlags){var l=o.featureFlags,g=o.featureFlagPayloads;if(o.errorsWhileComputingFlags){var O=d.getPersistedProperty(pw.FeatureFlags),P=d.getPersistedProperty(pw.FeatureFlagPayloads);l=Gg(Gg({},O),o.featureFlags),g=Gg(Gg({},P),o.featureFlagPayloads)}d.setKnownFeatureFlags(l),d.setKnownFeatureFlagPayloads(g)}return o}).finally(function(){d._decideResponsePromise=void 0}),[2,this._decideResponsePromise]})})},t.prototype.setKnownFeatureFlags=function(r){this.setPersistedProperty(pw.FeatureFlags,r),this._events.emit("featureflags",r)},t.prototype.setKnownFeatureFlagPayloads=function(r){this.setPersistedProperty(pw.FeatureFlagPayloads,r)},t.prototype.getFeatureFlag=function(r){var n=this.getFeatureFlags();if(n){var i=n[r];return i===void 0&&(i=!1),this.sendFeatureFlagEvent&&!this.flagCallReported[r]&&(this.flagCallReported[r]=!0,this.capture("$feature_flag_called",{$feature_flag:r,$feature_flag_response:i})),i}},t.prototype.getFeatureFlagPayload=function(r){var n=this.getFeatureFlagPayloads();if(n){var i=n[r];return i===void 0?null:this._parsePayload(i)}},t.prototype.getFeatureFlagPayloads=function(){var r=this,n=this.getPersistedProperty(pw.FeatureFlagPayloads);return n&&Object.fromEntries(Object.entries(n).map(function(i){var a=i[0],u=i[1];return[a,r._parsePayload(u)]}))},t.prototype.getFeatureFlags=function(){var r=this.getPersistedProperty(pw.FeatureFlags),n=this.getPersistedProperty(pw.OverrideFeatureFlags);if(!n)return r;r=r||{};for(var i in n)n[i]?r[i]=n[i]:delete r[i];return r},t.prototype.getFeatureFlagsAndPayloads=function(){var r=this.getFeatureFlags(),n=this.getFeatureFlagPayloads();return{flags:r,payloads:n}},t.prototype.isFeatureEnabled=function(r){var n=this.getFeatureFlag(r);if(n!==void 0)return!!n},t.prototype.reloadFeatureFlags=function(r){this.decideAsync().then(function(n){r?.(void 0,n?.featureFlags)}).catch(function(n){r?.(n,void 0),r||console.log("[PostHog] Error reloading feature flags",n)})},t.prototype.reloadFeatureFlagsAsync=function(r){var n;return r===void 0&&(r=!0),gC(this,void 0,void 0,function(){return mC(this,function(i){switch(i.label){case 0:return[4,this.decideAsync(r)];case 1:return[2,(n=i.sent())===null||n===void 0?void 0:n.featureFlags]}})})},t.prototype.onFeatureFlags=function(r){var n=this;return this.on("featureflags",function(){return gC(n,void 0,void 0,function(){var i;return mC(this,function(a){return i=this.getFeatureFlags(),i&&r(i),[2]})})})},t.prototype.onFeatureFlag=function(r,n){var i=this;return this.on("featureflags",function(){return gC(i,void 0,void 0,function(){var a;return mC(this,function(u){return a=this.getFeatureFlag(r),a!==void 0&&n(a),[2]})})})},t.prototype.overrideFeatureFlag=function(r){return r===null?this.setPersistedProperty(pw.OverrideFeatureFlags,null):this.setPersistedProperty(pw.OverrideFeatureFlags,r)},t})(Z1f);var Pq1=function(){function e(){this._memoryStorage={}}return e.prototype.getProperty=function(t){return this._memoryStorage[t]},e.prototype.setProperty=function(t,r){this._memoryStorage[t]=r!==null?r:void 0},e}(),k1f=function(e,t){return gC(void 0,void 0,void 0,function(){var r;return mC(this,function(n){switch(n.label){case 0:return[4,K1f.default.request({url:e,headers:t.headers,method:t.method.toLowerCase(),data:t.body,signal:t.signal,validateStatus:function(){return!0}})];case 1:return r=n.sent(),[2,{status:r.status,text:function(){return gC(void 0,void 0,void 0,function(){return mC(this,function(i){return[2,r.data]})})},json:function(){return gC(void 0,void 0,void 0,function(){return mC(this,function(i){return[2,r.data]})})}}]}})})},wq1=1152921504606847e3,H1f=function(e){K4n(t,e);function t(r){var n=e.call(this)||this;return Error.captureStackTrace(n,n.constructor),n.name="ClientError",n.message=r,Object.setPrototypeOf(n,t.prototype),n}return t}(Error),nk=function(e){K4n(t,e);function t(r){var n=e.call(this,r)||this;return n.name=n.constructor.name,Error.captureStackTrace(n,n.constructor),Object.setPrototypeOf(n,t.prototype),n}return t}(Error),jq1=function(){function e(t){var r=t.pollingInterval,n=t.personalApiKey,i=t.projectApiKey,a=t.timeout,u=t.host,f=pq1(t,["pollingInterval","personalApiKey","projectApiKey","timeout","host"]);this.debugMode=!1,this.pollingInterval=r,this.personalApiKey=n,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=a,this.projectApiKey=i,this.host=u,this.poller=void 0,this.fetch=f.fetch||k1f,this.loadFeatureFlags()}return e.prototype.debug=function(t){t===void 0&&(t=!0),this.debugMode=t},e.prototype.getFeatureFlag=function(t,r,n,i,a){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var u,f,d,c,o;return mC(this,function(l){switch(l.label){case 0:return[4,this.loadFeatureFlags()];case 1:if(l.sent(),u=void 0,f=void 0,!this.loadedSuccessfullyOnce)return[2,u];for(d=0,c=this.featureFlags;d<c.length;d++)if(o=c[d],t===o.key){f=o;break}if(f!==void 0)try{u=this.computeFlagLocally(f,r,n,i,a),this.debugMode&&console.debug("Successfully computed flag locally: ".concat(t," -> ").concat(u))}catch(g){g instanceof nk?this.debugMode&&console.debug("InconclusiveMatchError when computing flag locally: ".concat(t,": ").concat(g)):g instanceof Error&&console.error("Error computing flag locally: ".concat(t,": ").concat(g))}return[2,u]}})})},e.prototype.computeFeatureFlagPayloadLocally=function(t,r){var n,i,a,u,f,d,c,o;return gC(this,void 0,void 0,function(){var l;return mC(this,function(g){switch(g.label){case 0:return[4,this.loadFeatureFlags()];case 1:return g.sent(),l=void 0,this.loadedSuccessfullyOnce?(typeof r=="boolean"?l=(u=(a=(i=(n=this.featureFlagsByKey)===null||n===void 0?void 0:n[t])===null||i===void 0?void 0:i.filters)===null||a===void 0?void 0:a.payloads)===null||u===void 0?void 0:u[r.toString()]:typeof r=="string"&&(l=(o=(c=(d=(f=this.featureFlagsByKey)===null||f===void 0?void 0:f[t])===null||d===void 0?void 0:d.filters)===null||c===void 0?void 0:c.payloads)===null||o===void 0?void 0:o[r]),l===void 0?[2,null]:[2,l]):[2,void 0]}})})},e.prototype.getAllFlagsAndPayloads=function(t,r,n,i){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var a,u,f,d=this;return mC(this,function(c){switch(c.label){case 0:return[4,this.loadFeatureFlags()];case 1:return c.sent(),a={},u={},f=this.featureFlags.length==0,this.featureFlags.map(function(o){return gC(d,void 0,void 0,function(){var l,g,O;return mC(this,function(P){switch(P.label){case 0:return P.trys.push([0,2,,3]),l=this.computeFlagLocally(o,t,r,n,i),a[o.key]=l,[4,this.computeFeatureFlagPayloadLocally(o.key,l)];case 1:return g=P.sent(),g&&(u[o.key]=g),[3,3];case 2:return O=P.sent(),O instanceof nk||O instanceof Error&&console.error("Error computing flag locally: ".concat(o.key,": ").concat(O)),f=!0,[3,3];case 3:return[2]}})})}),[2,{response:a,payloads:u,fallbackToDecide:f}]}})})},e.prototype.computeFlagLocally=function(t,r,n,i,a){if(n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),t.ensure_experience_continuity)throw new nk("Flag has experience continuity enabled");if(!t.active)return!1;var u=t.filters||{},f=u.aggregation_group_type_index;if(f!=null){var d=this.groupTypeMapping[String(f)];if(!d)throw console.warn("[FEATURE FLAGS] Unknown group type index ".concat(f," for feature flag ").concat(t.key)),new nk("Flag has unknown group type index");if(!(d in n))return console.warn("[FEATURE FLAGS] Can't compute group feature flag: ".concat(t.key," without group names passed in")),!1;var c=a[d];return this.matchFeatureFlagProperties(t,n[d],c)}else return this.matchFeatureFlagProperties(t,r,i)},e.prototype.matchFeatureFlagProperties=function(t,r,n){for(var i,a=t.filters||{},u=a.groups||[],f=!1,d=void 0,c=Y1f([],u,!0).sort(function(M,q){var B=!!M.variant,I=!!q.variant;return B&&I?0:B?-1:I?1:0}),o=function(M){try{if(l.isConditionMatch(t,r,M,n)){var q=M.variant,B=((i=a.multivariate)===null||i===void 0?void 0:i.variants)||[];return q&&B.some(function(I){return I.key===q})?d=q:d=l.getMatchingVariant(t,r)||!0,"break"}}catch(I){if(I instanceof nk)f=!0;else throw I}},l=this,g=0,O=c;g<O.length;g++){var P=O[g],j=o(P);if(j==="break")break}if(d!==void 0)return d;if(f)throw new nk("Can't determine if feature flag is enabled or not with given properties");return!1},e.prototype.isConditionMatch=function(t,r,n,i){var a=n.rollout_percentage;if((n.properties||[]).length>0){for(var u=0,f=n.properties;u<f.length;u++){var d=f[u],c=d.type,o=!1;if(c==="cohort"?o=twf(d,i,this.cohorts):o=ewf(d,i),!o)return!1}if(a==null)return!0}return!(a!=null&&Q1f(t.key,r)>a/100)},e.prototype.getMatchingVariant=function(t,r){var n=Q1f(t.key,r,"variant"),i=this.variantLookupTable(t).find(function(a){return n>=a.valueMin&&n<a.valueMax});if(i)return i.key},e.prototype.variantLookupTable=function(t){var r,n=[],i=0,a=0,u=t.filters||{},f=((r=u.multivariate)===null||r===void 0?void 0:r.variants)||[];return f.forEach(function(d){a=i+d.rollout_percentage/100,n.push({valueMin:i,valueMax:a,key:d.key}),i=a}),n},e.prototype.loadFeatureFlags=function(t){return t===void 0&&(t=!1),gC(this,void 0,void 0,function(){return mC(this,function(r){switch(r.label){case 0:return!this.loadedSuccessfullyOnce||t?[4,this._loadFeatureFlags()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[2]}})})},e.prototype._loadFeatureFlags=function(){return gC(this,void 0,void 0,function(){var t,r,n,i=this;return mC(this,function(a){switch(a.label){case 0:this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(function(){return i._loadFeatureFlags()},this.pollingInterval),a.label=1;case 1:return a.trys.push([1,4,,5]),[4,this._requestFeatureFlagDefinitions()];case 2:if(t=a.sent(),t&&t.status===401)throw new H1f("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");return t&&t.status!==200?[2]:[4,t.json()];case 3:return r=a.sent(),"flags"in r||console.error("Invalid response when getting feature flags: ".concat(JSON.stringify(r))),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce(function(u,f){return u[f.key]=f,u},{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0,[3,5];case 4:if(n=a.sent(),n instanceof H1f)throw n;return[3,5];case 5:return[2]}})})},e.prototype._requestFeatureFlagDefinitions=function(){return gC(this,void 0,void 0,function(){var t,r,n,i,a;return mC(this,function(u){switch(u.label){case 0:t="".concat(this.host,"/api/feature_flag/local_evaluation?token=").concat(this.projectApiKey,"&send_cohorts"),r={method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.personalApiKey),"user-agent":"posthog-node/".concat(W0u)}},n=null,this.timeout&&typeof this.timeout=="number"&&(i=new AbortController,n=X1f(function(){i.abort()},this.timeout),r.signal=i.signal),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,this.fetch(t,r)];case 2:return[2,u.sent()];case 3:throw a=u.sent(),a;case 4:return clearTimeout(n),[7];case 5:return[2]}})})},e.prototype.stopPoller=function(){clearTimeout(this.poller)},e}();function Q1f(e,t,r){r===void 0&&(r="");var n=(0,$1f.createHash)();return n.update("".concat(e,".").concat(t).concat(r)),parseInt(n.digest("hex").slice(0,15),16)/wq1}function ewf(e,t){var r=e.key,n=e.value,i=e.operator||"exact";if(r in t){if(i==="is_not_set")throw new nk("Operator is_not_set is not supported")}else throw new nk("Property ".concat(r," not found in propertyValues"));var a=t[r];switch(i){case"exact":return Array.isArray(n)?n.indexOf(a)!==-1:n===a;case"is_not":return Array.isArray(n)?n.indexOf(a)===-1:n!==a;case"is_set":return r in t;case"icontains":return String(a).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(a).toLowerCase().includes(String(n).toLowerCase());case"regex":return J1f(String(n))&&String(a).match(String(n))!==null;case"not_regex":return J1f(String(n))&&String(a).match(String(n))===null;case"gt":return typeof a==typeof n&&a>n;case"gte":return typeof a==typeof n&&a>=n;case"lt":return typeof a==typeof n&&a<n;case"lte":return typeof a==typeof n&&a<=n;case"is_date_after":case"is_date_before":var u=G1f(n),f=G1f(a);return i==="is_date_before"?f<u:f>u;default:return console.error("Unknown operator: ".concat(i)),!1}}function twf(e,t,r){var n=String(e.value);if(!(n in r))throw new nk("can't match cohort without a given cohort property value");var i=r[n];return rwf(i,t,r)}function rwf(e,t,r){if(!e)return!0;var n=e.type,i=e.values;if(!i||i.length===0)return!0;var a=!1;if("values"in i[0]){for(var u=0,f=i;u<f.length;u++){var d=f[u];try{var c=rwf(d,t,r);if(n==="AND"){if(!c)return!1}else if(c)return!0}catch(O){if(O instanceof nk)console.debug("Failed to compute property ".concat(d," locally: ").concat(O)),a=!0;else throw O}}if(a)throw new nk("Can't match cohort without a given cohort property value");return n==="AND"}else{for(var o=0,l=i;o<l.length;o++){var d=l[o];try{var c=void 0;d.type==="cohort"?c=twf(d,t,r):c=ewf(d,t);var g=d.negation||!1;if(n==="AND"){if(!c&&!g||c&&g)return!1}else if(c&&!g||!c&&g)return!0}catch(P){if(P instanceof nk)console.debug("Failed to compute property ".concat(d," locally: ").concat(P)),a=!0;else throw P}}if(a)throw new nk("can't match cohort without a given cohort property value");return n==="AND"}}function J1f(e){try{return new RegExp(e),!0}catch{return!1}}function G1f(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){var t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new nk("".concat(e," is in an invalid date format"))}else throw new nk("The date provided ".concat(e," must be a string, number, or date object"))}var Dq1=30*1e3,Sq1=50*1e3,Oma=function(e){K4n(t,e);function t(r,n){n===void 0&&(n={});var i=this,a;return n.captureMode=n?.captureMode||"json",i=e.call(this,r,n)||this,i._memoryStorage=new Pq1,i.options=n,n.personalApiKey&&(i.featureFlagsPoller=new jq1({pollingInterval:typeof n.featureFlagsPollingInterval=="number"?n.featureFlagsPollingInterval:Dq1,personalApiKey:n.personalApiKey,projectApiKey:r,timeout:(a=n.requestTimeout)!==null&&a!==void 0?a:1e4,host:i.host,fetch:n.fetch})),i.distinctIdHasSentFlagCalls={},i.maxCacheSize=n.maxCacheSize||Sq1,i}return t.prototype.getPersistedProperty=function(r){return this._memoryStorage.getProperty(r)},t.prototype.setPersistedProperty=function(r,n){return this._memoryStorage.setProperty(r,n)},t.prototype.fetch=function(r,n){return this.options.fetch?this.options.fetch(r,n):k1f(r,n)},t.prototype.getLibraryId=function(){return"posthog-node"},t.prototype.getLibraryVersion=function(){return W0u},t.prototype.getCustomUserAgent=function(){return"posthog-node/".concat(W0u)},t.prototype.enable=function(){return e.prototype.optIn.call(this)},t.prototype.disable=function(){return e.prototype.optOut.call(this)},t.prototype.debug=function(r){var n;r===void 0&&(r=!0),e.prototype.debug.call(this,r),(n=this.featureFlagsPoller)===null||n===void 0||n.debug(r)},t.prototype.capture=function(r){var n=this,i=r.distinctId,a=r.event,u=r.properties,f=r.groups,d=r.sendFeatureFlags,c=r.timestamp,o=r.disableGeoip,l=function(g){e.prototype.captureStateless.call(n,i,a,g,{timestamp:c,disableGeoip:o})};d?e.prototype.getFeatureFlagsStateless.call(this,i,f,void 0,void 0,o).then(function(g){var O={};if(g)for(var P=0,j=Object.entries(g);P<j.length;P++){var M=j[P],q=M[0],B=M[1];B!==!1&&(O["$feature/".concat(q)]=B)}var I=Object.keys(g||{}).filter(function(F){return g?.[F]!==!1}),C=Gg({$active_feature_flags:I||void 0},O);l(Gg(Gg(Gg({},u),{$groups:f}),C))}):l(Gg(Gg({},u),{$groups:f}))},t.prototype.identify=function(r){var n=r.distinctId,i=r.properties,a=r.disableGeoip,u=i?.$set||i;e.prototype.identifyStateless.call(this,n,{$set:u},{disableGeoip:a})},t.prototype.alias=function(r){e.prototype.aliasStateless.call(this,r.alias,r.distinctId,void 0,{disableGeoip:r.disableGeoip})},t.prototype.getFeatureFlag=function(r,n,i){var a;return gC(this,void 0,void 0,function(){var u,f,d,c,o,l,g,O,P,j,M,q;return mC(this,function(B){switch(B.label){case 0:return u=i||{},f=u.groups,d=u.personProperties,c=u.groupProperties,o=u.disableGeoip,l=i||{},g=l.onlyEvaluateLocally,O=l.sendFeatureFlagEvents,g==null&&(g=!1),O==null&&(O=!0),[4,(a=this.featureFlagsPoller)===null||a===void 0?void 0:a.getFeatureFlag(r,n,f,d,c)];case 1:return P=B.sent(),j=P!==void 0,!j&&!g?[4,e.prototype.getFeatureFlagStateless.call(this,r,n,f,d,c,o)]:[3,3];case 2:P=B.sent(),B.label=3;case 3:return M="".concat(r,"_").concat(P),O&&(!(n in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[n].includes(M))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[n])?this.distinctIdHasSentFlagCalls[n].push(M):this.distinctIdHasSentFlagCalls[n]=[M],this.capture({distinctId:n,event:"$feature_flag_called",properties:(q={$feature_flag:r,$feature_flag_response:P,locally_evaluated:j},q["$feature/".concat(r)]=P,q),groups:f,disableGeoip:o})),[2,P]}})})},t.prototype.getFeatureFlagPayload=function(r,n,i,a){var u;return gC(this,void 0,void 0,function(){var f,d,c,o,l,g,O,P,j;return mC(this,function(M){switch(M.label){case 0:return f=a||{},d=f.groups,c=f.personProperties,o=f.groupProperties,l=f.disableGeoip,g=a||{},O=g.onlyEvaluateLocally,g.sendFeatureFlagEvents,P=void 0,i?[3,2]:[4,this.getFeatureFlag(r,n,Gg(Gg({},a),{onlyEvaluateLocally:!0}))];case 1:i=M.sent(),M.label=2;case 2:return i?[4,(u=this.featureFlagsPoller)===null||u===void 0?void 0:u.computeFeatureFlagPayloadLocally(r,i)]:[3,4];case 3:P=M.sent(),M.label=4;case 4:return O==null&&(O=!1),O==null&&(O=!1),j=P!==void 0,!j&&!O?[4,e.prototype.getFeatureFlagPayloadStateless.call(this,r,n,d,c,o,l)]:[3,6];case 5:P=M.sent(),M.label=6;case 6:try{return[2,JSON.parse(P)]}catch{return[2,P]}return[2]}})})},t.prototype.isFeatureEnabled=function(r,n,i){return gC(this,void 0,void 0,function(){var a;return mC(this,function(u){switch(u.label){case 0:return[4,this.getFeatureFlag(r,n,i)];case 1:return a=u.sent(),a===void 0?[2,void 0]:[2,!!a||!1]}})})},t.prototype.getAllFlags=function(r,n){return gC(this,void 0,void 0,function(){var i;return mC(this,function(a){switch(a.label){case 0:return[4,this.getAllFlagsAndPayloads(r,n)];case 1:return i=a.sent(),[2,i.featureFlags]}})})},t.prototype.getAllFlagsAndPayloads=function(r,n){var i;return gC(this,void 0,void 0,function(){var a,u,f,d,c,o,l,g,O,P,j;return mC(this,function(M){switch(M.label){case 0:return a=n||{},u=a.groups,f=a.personProperties,d=a.groupProperties,c=a.disableGeoip,o=(n||{}).onlyEvaluateLocally,o==null&&(o=!1),[4,(i=this.featureFlagsPoller)===null||i===void 0?void 0:i.getAllFlagsAndPayloads(r,u,f,d)];case 1:return l=M.sent(),g={},O={},P=!0,l&&(g=l.response,O=l.payloads,P=l.fallbackToDecide),P&&!o?[4,e.prototype.getFeatureFlagsAndPayloadsStateless.call(this,r,u,f,d,c)]:[3,3];case 2:j=M.sent(),g=Gg(Gg({},g),j.flags||{}),O=Gg(Gg({},O),j.payloads||{}),M.label=3;case 3:return[2,{featureFlags:g,featureFlagPayloads:O}]}})})},t.prototype.groupIdentify=function(r){var n=r.groupType,i=r.groupKey,a=r.properties,u=r.distinctId,f=r.disableGeoip;e.prototype.groupIdentifyStateless.call(this,n,i,a,{disableGeoip:f},u)},t.prototype.reloadFeatureFlags=function(){var r;return gC(this,void 0,void 0,function(){return mC(this,function(n){switch(n.label){case 0:return[4,(r=this.featureFlagsPoller)===null||r===void 0?void 0:r.loadFeatureFlags(!0)];case 1:return n.sent(),[2]}})})},t.prototype.shutdown=function(){this.shutdownAsync()},t.prototype.shutdownAsync=function(){var r;return gC(this,void 0,void 0,function(){return mC(this,function(n){return(r=this.featureFlagsPoller)===null||r===void 0||r.stopPoller(),[2,e.prototype.shutdownAsync.call(this)]})})},t}(Z1f);var Pma=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Oma(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.45.0-rc24",usingAccessToken:!0}})}flush(){this.posthog.flush()}};var Mvi=class{async sendEvent(){}async identify(){}async flush(){}};var Y4n=require("fs/promises"),owf=require("os"),uwf=require("path");var nwf=Yo(require("crypto")),jma=new Uint8Array(256),wma=jma.length;function Q0u(){return wma>jma.length-16&&(nwf.default.randomFillSync(jma),wma=0),jma.slice(wma,wma+=16)}var WH=[];for(let e=0;e<256;++e)WH.push((e+256).toString(16).slice(1));function iwf(e,t=0){return WH[e[t+0]]+WH[e[t+1]]+WH[e[t+2]]+WH[e[t+3]]+"-"+WH[e[t+4]]+WH[e[t+5]]+"-"+WH[e[t+6]]+WH[e[t+7]]+"-"+WH[e[t+8]]+WH[e[t+9]]+"-"+WH[e[t+10]]+WH[e[t+11]]+WH[e[t+12]]+WH[e[t+13]]+WH[e[t+14]]+WH[e[t+15]]}var awf=Yo(require("crypto")),J0u={randomUUID:awf.default.randomUUID};function Eq1(e,t,r){if(J0u.randomUUID&&!t&&!e)return J0u.randomUUID();e=e||{};let n=e.random||(e.rng||Q0u)();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 iwf(n)}var a8r=Eq1;var Aq1="id",Mq1=".fern",xvi=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new Oma(r),this.userId=t==null?void 0:efu(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.45.0-rc24",...t,...t.properties}})}flush(){this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=yf(v_.of((0,owf.homedir)()),Ms.of(Mq1),Ms.of(Aq1));await Wh(t)||(await(0,Y4n.mkdir)((0,uwf.dirname)(t),{recursive:!0}),await(0,Y4n.writeFile)(t,a8r())),this.persistedDistinctId=(await(0,Y4n.readFile)(t)).toString()}return this.persistedDistinctId}};var G0u;async function X4n(){return G0u==null&&(G0u=await xq1()),G0u}async function xq1(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new Mvi;let r=await X_a();return r!=null?new xvi({token:r,posthogApiKey:e}):await Y_a()!=null?new Pma({posthogApiKey:e}):new xvi({token:void 0,posthogApiKey:e})}catch{return new Mvi}}function Tvi(e,t){return function(){return e.apply(t,arguments)}}var{toString:Tq1}=Object.prototype,{getPrototypeOf:Y0u}=Object,Sma=(e=>t=>{let r=Tq1.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),dIt=e=>(e=e.toLowerCase(),t=>Sma(t)===e),Ema=e=>t=>typeof t===e,{isArray:Z4n}=Array,Cvi=Ema("undefined");function Cq1(e){return e!==null&&!Cvi(e)&&e.constructor!==null&&!Cvi(e.constructor)&&dDe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var lwf=dIt("ArrayBuffer");function qq1(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&lwf(e.buffer),t}var Iq1=Ema("string"),dDe=Ema("function"),fwf=Ema("number"),Ama=e=>e!==null&&typeof e=="object",Bq1=e=>e===!0||e===!1,Dma=e=>{if(Sma(e)!=="object")return!1;let t=Y0u(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Nq1=dIt("Date"),zq1=dIt("File"),Rq1=dIt("Blob"),Fq1=dIt("FileList"),Lq1=e=>Ama(e)&&dDe(e.pipe),Uq1=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||dDe(e.append)&&((t=Sma(e))==="formdata"||t==="object"&&dDe(e.toString)&&e.toString()==="[object FormData]"))},Vq1=dIt("URLSearchParams"),[Wq1,Hq1,Qq1,Jq1]=["ReadableStream","Request","Response","Headers"].map(dIt),Gq1=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function qvi(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),Z4n(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,f;for(n=0;n<u;n++)f=a[n],t.call(null,e[f],f,e)}}function dwf(e,t){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 Nrn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,pwf=e=>!Cvi(e)&&e!==Nrn;function K0u(){let{caseless:e}=pwf(this)&&this||{},t={},r=(n,i)=>{let a=e&&dwf(t,i)||i;Dma(t[a])&&Dma(n)?t[a]=K0u(t[a],n):Dma(n)?t[a]=K0u({},n):Z4n(n)?t[a]=n.slice():t[a]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&qvi(arguments[n],r);return t}var $q1=(e,t,r,{allOwnKeys:n}={})=>(qvi(t,(i,a)=>{r&&dDe(i)?e[a]=Tvi(i,r):e[a]=i},{allOwnKeys:n}),e),Kq1=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Yq1=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},Xq1=(e,t,r,n)=>{let i,a,u,f={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)u=i[a],(!n||n(u,e,t))&&!f[u]&&(t[u]=e[u],f[u]=!0);e=r!==!1&&Y0u(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},Zq1=(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},kq1=e=>{if(!e)return null;if(Z4n(e))return e;let t=e.length;if(!fwf(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},e61=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Y0u(Uint8Array)),t61=(e,t)=>{let n=(e&&e[Symbol.iterator]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},r61=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},n61=dIt("HTMLFormElement"),i61=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),swf=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),a61=dIt("RegExp"),_wf=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};qvi(r,(i,a)=>{let u;(u=t(i,a,e))!==!1&&(n[a]=u||i)}),Object.defineProperties(e,n)},o61=e=>{_wf(e,(t,r)=>{if(dDe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(dDe(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+"'")})}})},u61=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return Z4n(e)?n(e):n(String(e).split(t)),r},s61=()=>{},c61=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,$0u="abcdefghijklmnopqrstuvwxyz",cwf="0123456789",hwf={DIGIT:cwf,ALPHA:$0u,ALPHA_DIGIT:$0u+$0u.toUpperCase()+cwf},l61=(e=16,t=hwf.ALPHA_DIGIT)=>{let r="",{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r};function f61(e){return!!(e&&dDe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var d61=e=>{let t=new Array(10),r=(n,i)=>{if(Ama(n)){if(t.indexOf(n)>=0)return;if(!("toJSON"in n)){t[i]=n;let a=Z4n(n)?[]:{};return qvi(n,(u,f)=>{let d=r(u,i+1);!Cvi(d)&&(a[f]=d)}),t[i]=void 0,a}}return n};return r(e,0)},p61=dIt("AsyncFunction"),_61=e=>e&&(Ama(e)||dDe(e))&&dDe(e.then)&&dDe(e.catch),ywf=((e,t)=>e?setImmediate:t?((r,n)=>(Nrn.addEventListener("message",({source:i,data:a})=>{i===Nrn&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),Nrn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",dDe(Nrn.postMessage)),h61=typeof queueMicrotask<"u"?queueMicrotask.bind(Nrn):typeof process<"u"&&process.nextTick||ywf,Jl={isArray:Z4n,isArrayBuffer:lwf,isBuffer:Cq1,isFormData:Uq1,isArrayBufferView:qq1,isString:Iq1,isNumber:fwf,isBoolean:Bq1,isObject:Ama,isPlainObject:Dma,isReadableStream:Wq1,isRequest:Hq1,isResponse:Qq1,isHeaders:Jq1,isUndefined:Cvi,isDate:Nq1,isFile:zq1,isBlob:Rq1,isRegExp:a61,isFunction:dDe,isStream:Lq1,isURLSearchParams:Vq1,isTypedArray:e61,isFileList:Fq1,forEach:qvi,merge:K0u,extend:$q1,trim:Gq1,stripBOM:Kq1,inherits:Yq1,toFlatObject:Xq1,kindOf:Sma,kindOfTest:dIt,endsWith:Zq1,toArray:kq1,forEachEntry:t61,matchAll:r61,isHTMLForm:n61,hasOwnProperty:swf,hasOwnProp:swf,reduceDescriptors:_wf,freezeMethods:o61,toObjectSet:u61,toCamelCase:i61,noop:s61,toFiniteNumber:c61,findKey:dwf,global:Nrn,isContextDefined:pwf,ALPHABET:hwf,generateString:l61,isSpecCompliantForm:f61,toJSONObject:d61,isAsyncFn:p61,isThenable:_61,setImmediate:ywf,asap:h61};function k4n(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Jl.inherits(k4n,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Jl.toJSONObject(this.config),code:this.code,status:this.status}}});var vwf=k4n.prototype,bwf={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{bwf[e]={value:e}});Object.defineProperties(k4n,bwf);Object.defineProperty(vwf,"isAxiosError",{value:!0});k4n.from=(e,t,r,n,i,a)=>{let u=Object.create(vwf);return Jl.toFlatObject(e,u,function(d){return d!==Error.prototype},f=>f!=="isAxiosError"),k4n.call(u,e.message,t,r,n,i),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var zy=k4n;var gwf=Yo(oNr(),1),Mma=gwf.default;function X0u(e){return Jl.isPlainObject(e)||Jl.isArray(e)}function Owf(e){return Jl.endsWith(e,"[]")?e.slice(0,-2):e}function mwf(e,t,r){return e?e.concat(t).map(function(i,a){return i=Owf(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function y61(e){return Jl.isArray(e)&&!e.some(X0u)}var v61=Jl.toFlatObject(Jl,{},null,function(t){return/^is[A-Z]/.test(t)});function b61(e,t,r){if(!Jl.isObject(e))throw new TypeError("target must be an object");t=t||new(Mma||FormData),r=Jl.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(j,M){return!Jl.isUndefined(M[j])});let n=r.metaTokens,i=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&Jl.isSpecCompliantForm(t);if(!Jl.isFunction(i))throw new TypeError("visitor must be a function");function c(P){if(P===null)return"";if(Jl.isDate(P))return P.toISOString();if(!d&&Jl.isBlob(P))throw new zy("Blob is not supported. Use a Buffer instead.");return Jl.isArrayBuffer(P)||Jl.isTypedArray(P)?d&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function o(P,j,M){let q=P;if(P&&!M&&typeof P=="object"){if(Jl.endsWith(j,"{}"))j=n?j:j.slice(0,-2),P=JSON.stringify(P);else if(Jl.isArray(P)&&y61(P)||(Jl.isFileList(P)||Jl.endsWith(j,"[]"))&&(q=Jl.toArray(P)))return j=Owf(j),q.forEach(function(I,C){!(Jl.isUndefined(I)||I===null)&&t.append(u===!0?mwf([j],C,a):u===null?j:j+"[]",c(I))}),!1}return X0u(P)?!0:(t.append(mwf(M,j,a),c(P)),!1)}let l=[],g=Object.assign(v61,{defaultVisitor:o,convertValue:c,isVisitable:X0u});function O(P,j){if(!Jl.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+j.join("."));l.push(P),Jl.forEach(P,function(q,B){(!(Jl.isUndefined(q)||q===null)&&i.call(t,q,Jl.isString(B)?B.trim():B,j,g))===!0&&O(q,j?j.concat(B):[B])}),l.pop()}}if(!Jl.isObject(e))throw new TypeError("data must be an object");return O(e),t}var o8r=b61;function Pwf(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function wwf(e,t){this._pairs=[],e&&o8r(e,this,t)}var jwf=wwf.prototype;jwf.append=function(t,r){this._pairs.push([t,r])};jwf.toString=function(t){let r=t?function(n){return t.call(this,n,Pwf)}:Pwf;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var Dwf=wwf;function g61(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function zrn(e,t,r){if(!t)return e;let n=r&&r.encode||g61,i=r&&r.serialize,a;if(i?a=i(t,r):a=Jl.isURLSearchParams(t)?t.toString():new Dwf(t,r).toString(n),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Z0u=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){Jl.forEach(this.handlers,function(n){n!==null&&t(n)})}},k0u=Z0u;var e3n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Swf=Yo(require("url"),1),Ewf=Swf.default.URLSearchParams;var Awf={isNode:!0,classes:{URLSearchParams:Ewf,FormData:Mma,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var rvu={};kc(rvu,{hasBrowserEnv:()=>tvu,hasStandardBrowserEnv:()=>m61,hasStandardBrowserWebWorkerEnv:()=>O61,navigator:()=>evu,origin:()=>P61});var tvu=typeof window<"u"&&typeof document<"u",evu=typeof navigator=="object"&&navigator||void 0,m61=tvu&&(!evu||["ReactNative","NativeScript","NS"].indexOf(evu.product)<0),O61=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",P61=tvu&&window.location.href||"http://localhost";var g6={...rvu,...Awf};function nvu(e,t){return o8r(e,new g6.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,a){return g6.isNode&&Jl.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function w61(e){return Jl.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function j61(e){let t={},r=Object.keys(e),n,i=r.length,a;for(n=0;n<i;n++)a=r[n],t[a]=e[a];return t}function D61(e){function t(r,n,i,a){let u=r[a++];if(u==="__proto__")return!0;let f=Number.isFinite(+u),d=a>=r.length;return u=!u&&Jl.isArray(i)?i.length:u,d?(Jl.hasOwnProp(i,u)?i[u]=[i[u],n]:i[u]=n,!f):((!i[u]||!Jl.isObject(i[u]))&&(i[u]=[]),t(r,n,i[u],a)&&Jl.isArray(i[u])&&(i[u]=j61(i[u])),!f)}if(Jl.isFormData(e)&&Jl.isFunction(e.entries)){let r={};return Jl.forEachEntry(e,(n,i)=>{t(w61(n),i,r,0)}),r}return null}var xma=D61;function S61(e,t,r){if(Jl.isString(e))try{return(t||JSON.parse)(e),Jl.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var ivu={transitional:e3n,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=Jl.isObject(t);if(a&&Jl.isHTMLForm(t)&&(t=new FormData(t)),Jl.isFormData(t))return i?JSON.stringify(xma(t)):t;if(Jl.isArrayBuffer(t)||Jl.isBuffer(t)||Jl.isStream(t)||Jl.isFile(t)||Jl.isBlob(t)||Jl.isReadableStream(t))return t;if(Jl.isArrayBufferView(t))return t.buffer;if(Jl.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let f;if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return nvu(t,this.formSerializer).toString();if((f=Jl.isFileList(t))||n.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return o8r(f?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),S61(t)):t}],transformResponse:[function(t){let r=this.transitional||ivu.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Jl.isResponse(t)||Jl.isReadableStream(t))return t;if(t&&Jl.isString(t)&&(n&&!this.responseType||i)){let u=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t)}catch(f){if(u)throw f.name==="SyntaxError"?zy.from(f,zy.ERR_BAD_RESPONSE,this,null,this.response):f}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:g6.classes.FormData,Blob:g6.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Jl.forEach(["delete","get","head","post","put","patch"],e=>{ivu.headers[e]={}});var t3n=ivu;var E61=Jl.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"]),Mwf=e=>{let t={},r,n,i;return e&&e.split(`
1821
+ `}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&&Gga(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var B1f=Yo(A1f(),1),N1f=Yo(Whu(),1),z1f=Yo(q1f(),1),$C=Yo(fDe(),1),R1f=Yo(p0i(),1);var vma=Yo(fDe(),1),I1f=Yo(p0i(),1),bma=function(e,t,r){return typeof e[t]!="function"?(0,vma.of)(e):(0,vma.from)((0,I1f.default)(e[t])(r).then(n=>(e[t]=n,e)))};var Dvi={isPlainObject:B1f.default,set:z1f.default,get:N1f.default},$4n=class extends Brn{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=Dvi.isPlainObject(r)?{...r}:{},Dvi.isPlainObject(t)&&(t=Object.values(t).every(i=>Dvi.isPlainObject(i)&&i.name===void 0)?Object.entries(t).map(([i,a])=>({name:i,...a})):[t]);let n=Array.isArray(t)?(0,$C.from)(t):t;return this.process=n.pipe((0,$C.concatMap)(this.processQuestion.bind(this)),(0,$C.publish)()),this.process.connect(),this.process.pipe((0,$C.reduce)((i,a)=>(Dvi.set(i,a.name,a.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,$C.defer)(()=>(0,$C.of)(t).pipe((0,$C.concatMap)(this.setDefaultType.bind(this)),(0,$C.concatMap)(this.filterIfRunnable.bind(this)),(0,$C.concatMap)(()=>bma(t,"message",this.answers)),(0,$C.concatMap)(()=>bma(t,"default",this.answers)),(0,$C.concatMap)(()=>bma(t,"choices",this.answers)),(0,$C.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,$C.defer)(()=>(0,$C.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,$C.defer)(()=>(0,$C.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Dvi.get(this.answers,t.name)!==void 0)return(0,$C.empty)();if(t.when===!1)return(0,$C.empty)();if(typeof t.when!="function")return(0,$C.of)(t);let{answers:r}=this;return(0,$C.defer)(()=>(0,$C.from)((0,R1f.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,$C.filter)(n=>n!=null)))}};function F1f(e){let t=function(r,n){let i;try{i=new $4n(t.prompts,e)}catch(u){return Promise.reject(u)}let a=i.run(r,n);return a.ui=i,a};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",uvi),this.registerPrompt("input",Arn),this.registerPrompt("number",svi),this.registerPrompt("confirm",cvi),this.registerPrompt("rawlist",lvi),this.registerPrompt("expand",fvi),this.registerPrompt("checkbox",dvi),this.registerPrompt("password",pvi),this.registerPrompt("editor",wvi)},t.restoreDefaultPrompts(),t}var L0u=F1f();function lq1(e,t){L0u.registerPrompt(e,t)}function fq1(){L0u.restoreDefaultPrompts()}var dq1={prompt:L0u,ui:{BottomBar:jvi,Prompt:$4n},createPromptModule:F1f,registerPrompt:lq1,restoreDefaultPrompts:fq1,Separator:tae},gma=dq1;var $1f=Yo(L1f()),K1f=Yo(elu()),V0u=function(e,t){return V0u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},V0u(e,t)};function K4n(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");V0u(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}var Gg=function(){return Gg=Object.assign||function(t){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])}return t},Gg.apply(this,arguments)};function pq1(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r}function gC(e,t,r,n){function i(a){return a instanceof r?a:new r(function(u){u(a)})}return new(r||(r=Promise))(function(a,u){function f(o){try{c(n.next(o))}catch(l){u(l)}}function d(o){try{c(n.throw(o))}catch(l){u(l)}}function c(o){o.done?a(o.value):i(o.value).then(f,d)}c((n=n.apply(e,t||[])).next())})}function mC(e,t){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},n,i,a,u;return u={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(u[Symbol.iterator]=function(){return this}),u;function f(c){return function(o){return d([c,o])}}function d(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=c[0]&2?i.return:c[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,c[1])).done)return a;switch(i=0,a&&(c=[c[0]&2,a.value]),c[0]){case 0:case 1:a=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(a=r.trys,!(a=a.length>0&&a[a.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!a||c[1]>a[0]&&c[1]<a[3])){r.label=c[1];break}if(c[0]===6&&r.label<a[1]){r.label=a[1],a=c;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(c);break}a[2]&&r.ops.pop(),r.trys.pop();continue}c=t.call(e,r)}catch(o){c=[6,o],i=0}finally{n=a=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function Y1f(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,a;n<i;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}var W0u="3.1.2",pw;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties"})(pw||(pw={}));function _q1(e,t){if(!e)throw new Error(t)}function hq1(e){return e?.replace(/\/+$/,"")}function yq1(e,t){return t===void 0&&(t={}),gC(this,void 0,void 0,function(){var r,n,i,a,u,f,d,c,o,l;return mC(this,function(g){switch(g.label){case 0:r=t.retryCount,n=r===void 0?3:r,i=t.retryDelay,a=i===void 0?5e3:i,u=t.retryCheck,f=u===void 0?function(){return!0}:u,d=null,c=0,g.label=1;case 1:return c<n+1?c>0?[4,new Promise(function(O){return setTimeout(O,a)})]:[3,3]:[3,7];case 2:g.sent(),g.label=3;case 3:return g.trys.push([3,5,,6]),[4,e()];case 4:return o=g.sent(),[2,o];case 5:if(l=g.sent(),d=l,!f(l))throw l;return[3,6];case 6:return c++,[3,1];case 7:throw d}})})}function H0u(e){var t=new Date().getTime(),r=e&&e.performance&&e.performance.now&&e.performance.now()*1e3||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var i=Math.random()*16;return t>0?(i=(t+i)%16|0,t=Math.floor(t/16)):(i=(r+i)%16|0,r=Math.floor(r/16)),(n==="x"?i:i&3|8).toString(16)})}function vq1(){return new Date().getTime()}function U1f(){return new Date().toISOString()}function X1f(e,t){var r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var Evi=String.fromCharCode,V1f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",mma={};function bq1(e,t){if(!mma[e]){mma[e]={};for(var r=0;r<e.length;r++)mma[e][e.charAt(r)]=r}return mma[e][t]}var Avi={compressToBase64:function(e){if(e==null)return"";var t=Avi._compress(e,6,function(r){return V1f.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:Avi._decompress(e.length,32,function(t){return bq1(V1f,e.charAt(t))})},compress:function(e){return Avi._compress(e,16,function(t){return Evi(t)})},_compress:function(e,t,r){if(e==null)return"";var n={},i={},a=[],u,f,d="",c="",o="",l=2,g=3,O=2,P=0,j=0,M;for(M=0;M<e.length;M+=1)if(d=e.charAt(M),Object.prototype.hasOwnProperty.call(n,d)||(n[d]=g++,i[d]=!0),c=o+d,Object.prototype.hasOwnProperty.call(n,c))o=c;else{if(Object.prototype.hasOwnProperty.call(i,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)P=P<<1,j==t-1?(j=0,a.push(r(P)),P=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)P=P<<1|f,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete i[o]}else for(f=n[o],u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++),n[c]=g++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(i,o)){if(o.charCodeAt(0)<256){for(u=0;u<O;u++)P=P<<1,j==t-1?(j=0,a.push(r(P)),P=0):j++;for(f=o.charCodeAt(0),u=0;u<8;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}else{for(f=1,u=0;u<O;u++)P=P<<1|f,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=0;for(f=o.charCodeAt(0),u=0;u<16;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1}l--,l==0&&(l=Math.pow(2,O),O++),delete i[o]}else for(f=n[o],u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;l--,l==0&&(l=Math.pow(2,O),O++)}for(f=2,u=0;u<O;u++)P=P<<1|f&1,j==t-1?(j=0,a.push(r(P)),P=0):j++,f=f>>1;for(;;)if(P=P<<1,j==t-1){a.push(r(P));break}else j++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:Avi._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){var n=[],i=[],a={val:r(0),position:t,index:1},u=4,f=4,d=3,c="",o,l,g,O,P,j,M;for(o=0;o<3;o+=1)n[o]=o;for(g=0,P=Math.pow(2,2),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;switch(g){case 0:for(g=0,P=Math.pow(2,8),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;M=Evi(g);break;case 1:for(g=0,P=Math.pow(2,16),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;M=Evi(g);break;case 2:return""}for(n[3]=M,l=M,i.push(M);;){if(a.index>e)return"";for(g=0,P=Math.pow(2,d),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;switch(M=g){case 0:for(g=0,P=Math.pow(2,8),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;n[f++]=Evi(g),M=f-1,u--;break;case 1:for(g=0,P=Math.pow(2,16),j=1;j!=P;)O=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),g|=(O>0?1:0)*j,j<<=1;n[f++]=Evi(g),M=f-1,u--;break;case 2:return i.join("")}if(u==0&&(u=Math.pow(2,d),d++),n[M])c=n[M];else if(M===f)c=l+l.charAt(0);else return null;i.push(c),n[f++]=l+c.charAt(0),u--,l=c,u==0&&(u=Math.pow(2,d),d++)}}},gq1=function(){function e(){this.events={},this.events={}}return e.prototype.on=function(t,r){var n=this;return this.events[t]||(this.events[t]=[]),this.events[t].push(r),function(){n.events[t]=n.events[t].filter(function(i){return i!==r})}},e.prototype.emit=function(t,r){for(var n=0,i=this.events[t]||[];n<i.length;n++){var a=i[n];a(r)}for(var u=0,f=this.events["*"]||[];u<f.length;u++){var a=f[u];a(t,r)}},e}(),mq1=function(e){K4n(t,e);function t(r){var n=e.call(this,"HTTP error while fetching PostHog: "+r.status)||this;return n.response=r,n.name="PostHogFetchHttpError",n}return t}(Error),Oq1=function(e){K4n(t,e);function t(r){var n=e.call(this,"Network error while fetching PostHog",r instanceof Error?{cause:r}:{})||this;return n.error=r,n.name="PostHogFetchNetworkError",n}return t}(Error);function W1f(e){return typeof e=="object"&&(e.name==="PostHogFetchHttpError"||e.name==="PostHogFetchNetworkError")}var Z1f=function(){function e(t,r){var n,i,a,u,f;this.debugMode=!1,this.pendingPromises={},this.disableGeoip=!0,this._events=new gq1,_q1(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=hq1(r?.host||"https://app.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.flushInterval=(n=r?.flushInterval)!==null&&n!==void 0?n:1e4,this.captureMode=r?.captureMode||"form",this._optoutOverride=r?.enable===!1,this._retryOptions={retryCount:(i=r?.fetchRetryCount)!==null&&i!==void 0?i:3,retryDelay:(a=r?.fetchRetryDelay)!==null&&a!==void 0?a:3e3,retryCheck:W1f},this.requestTimeout=(u=r?.requestTimeout)!==null&&u!==void 0?u:1e4,this.disableGeoip=(f=r?.disableGeoip)!==null&&f!==void 0?f:!0}return e.prototype.getCommonEventProperties=function(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}},Object.defineProperty(e.prototype,"optedOut",{get:function(){var t,r;return(r=(t=this.getPersistedProperty(pw.OptedOut))!==null&&t!==void 0?t:this._optoutOverride)!==null&&r!==void 0?r:!1},enumerable:!1,configurable:!0}),e.prototype.optIn=function(){this.setPersistedProperty(pw.OptedOut,!1)},e.prototype.optOut=function(){this.setPersistedProperty(pw.OptedOut,!0)},e.prototype.on=function(t,r){return this._events.on(t,r)},e.prototype.debug=function(t){var r;t===void 0&&(t=!0),(r=this.removeDebugCallback)===null||r===void 0||r.call(this),this.debugMode=t,t&&(this.removeDebugCallback=this.on("*",function(n,i){return console.log("PostHog Debug",n,i)}))},e.prototype.buildPayload=function(t){return{distinct_id:t.distinct_id,event:t.event,properties:Gg(Gg({},t.properties||{}),this.getCommonEventProperties())}},e.prototype.identifyStateless=function(t,r,n){var i=Gg({},this.buildPayload({distinct_id:t,event:"$identify",properties:r}));return this.enqueue("identify",i,n),this},e.prototype.captureStateless=function(t,r,n,i){var a=this.buildPayload({distinct_id:t,event:r,properties:n});return this.enqueue("capture",a,i),this},e.prototype.aliasStateless=function(t,r,n,i){var a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:Gg(Gg({},n||{}),{distinct_id:r,alias:t})});return this.enqueue("alias",a,i),this},e.prototype.groupIdentifyStateless=function(t,r,n,i,a,u){var f=this.buildPayload({distinct_id:a||"$".concat(t,"_").concat(r),event:"$groupidentify",properties:Gg({$group_type:t,$group_key:r,$group_set:n||{}},u||{})});return this.enqueue("capture",f,i),this},e.prototype.getDecide=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var u,f;return mC(this,function(d){return u="".concat(this.host,"/decide/?v=3"),f={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Gg({token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i},a))},[2,this.fetchWithRetry(u,f).then(function(c){return c.json()}).catch(function(c){console.error("Error fetching feature flags",c)})]})})},e.prototype.getFeatureFlagStateless=function(t,r,n,i,a,u){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var f,d;return mC(this,function(c){switch(c.label){case 0:return[4,this.getFeatureFlagsStateless(r,n,i,a,u)];case 1:return f=c.sent(),f?(d=f[t],d===void 0&&(d=!1),[2,d]):[2,void 0]}})})},e.prototype.getFeatureFlagPayloadStateless=function(t,r,n,i,a,u){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var f,d;return mC(this,function(c){switch(c.label){case 0:return[4,this.getFeatureFlagPayloadsStateless(r,n,i,a,u)];case 1:return f=c.sent(),f?(d=f[t],d===void 0?[2,null]:[2,this._parsePayload(d)]):[2,void 0]}})})},e.prototype.getFeatureFlagPayloadsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var u,f=this;return mC(this,function(d){switch(d.label){case 0:return[4,this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a)];case 1:return u=d.sent().payloads,u?[2,Object.fromEntries(Object.entries(u).map(function(c){var o=c[0],l=c[1];return[o,f._parsePayload(l)]}))]:[2,u]}})})},e.prototype._parsePayload=function(t){try{return JSON.parse(t)}catch{return t}},e.prototype.getFeatureFlagsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){return mC(this,function(u){switch(u.label){case 0:return[4,this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a)];case 1:return[2,u.sent().flags]}})})},e.prototype.getFeatureFlagsAndPayloadsStateless=function(t,r,n,i,a){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var u,f,d,c;return mC(this,function(o){switch(o.label){case 0:return u={},(a??this.disableGeoip)&&(u.geoip_disable=!0),[4,this.getDecide(t,r,n,i,u)];case 1:return f=o.sent(),d=f?.featureFlags,c=f?.featureFlagPayloads,[2,{flags:d,payloads:c}]}})})},e.prototype.enqueue=function(t,r,n){var i=this,a;if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.enable()");return}var u=Gg(Gg({},r),{type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:U1f()}),f=(a=n?.disableGeoip)!==null&&a!==void 0?a:this.disableGeoip;f&&(u.properties||(u.properties={}),u.properties.$geoip_disable=!0),u.distinctId&&(u.distinct_id=u.distinctId,delete u.distinctId);var d=this.getPersistedProperty(pw.Queue)||[];d.push({message:u}),this.setPersistedProperty(pw.Queue,d),this._events.emit(t,u),d.length>=this.flushAt&&this.flush(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=X1f(function(){return i.flush()},this.flushInterval))},e.prototype.flushAsync=function(){var t=this;return new Promise(function(r,n){t.flush(function(i,a){return i?n(i):r(a)})})},e.prototype.flush=function(t){var r=this;this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null);var n=this.getPersistedProperty(pw.Queue)||[];if(!n.length)return t?.();var i=n.splice(0,this.flushAt);this.setPersistedProperty(pw.Queue,n);var a=i.map(function(O){return O.message}),u={api_key:this.apiKey,batch:a,sent_at:U1f()},f=H0u(),d=function(O){O&&r._events.emit("error",O),t?.(O,a),delete r.pendingPromises[f],r._events.emit("flush",a)};this.getCustomUserAgent();var c=JSON.stringify(u),o=this.captureMode==="form"?"".concat(this.host,"/e/?ip=1&_=").concat(vq1(),"&v=").concat(this.getLibraryVersion()):"".concat(this.host,"/batch/"),l=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"data=".concat(encodeURIComponent(Avi.compressToBase64(c)),"&compression=lz64")}:{method:"POST",headers:{"Content-Type":"application/json"},body:c},g=this.fetchWithRetry(o,l);this.pendingPromises[f]=g,g.then(function(){return d()}).catch(function(O){d(O)})},e.prototype.fetchWithRetry=function(t,r,n){var i,a;return gC(this,void 0,void 0,function(){var u=this;return mC(this,function(f){switch(f.label){case 0:return(i=(a=AbortSignal).timeout)!==null&&i!==void 0||(a.timeout=function(c){var o=new AbortController;return setTimeout(function(){return o.abort()},c),o.signal}),[4,yq1(function(){return gC(u,void 0,void 0,function(){var d,c;return mC(this,function(o){switch(o.label){case 0:d=null,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this.fetch(t,Gg({signal:AbortSignal.timeout(this.requestTimeout)},r))];case 2:return d=o.sent(),[3,4];case 3:throw c=o.sent(),new Oq1(c);case 4:if(d.status<200||d.status>=400)throw new mq1(d);return[2,d]}})})},Gg(Gg({},this._retryOptions),n))];case 1:return[2,f.sent()]}})})},e.prototype.shutdownAsync=function(){return gC(this,void 0,void 0,function(){var t;return mC(this,function(r){switch(r.label){case 0:clearTimeout(this._flushTimer),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.flushAsync()];case 2:return r.sent(),[4,Promise.all(Object.values(this.pendingPromises).map(function(n){return n.catch(function(){})}))];case 3:return r.sent(),[3,5];case 4:if(t=r.sent(),!W1f(t))throw t;return console.error("Error while shutting down PostHog",t),[3,5];case 5:return[2]}})})},e.prototype.shutdown=function(){this.shutdownAsync()},e}();(function(e){K4n(t,e);function t(r,n){var i=this,a,u,f,d=(a=n?.disableGeoip)!==null&&a!==void 0?a:!1;return i=e.call(this,r,Gg(Gg({},n),{disableGeoip:d}))||this,i.flagCallReported={},i.sessionProps={},i.sendFeatureFlagEvent=(u=n?.sendFeatureFlagEvent)!==null&&u!==void 0?u:!0,i._sessionExpirationTimeSeconds=(f=n?.sessionExpirationTimeSeconds)!==null&&f!==void 0?f:1800,i}return t.prototype.setupBootstrap=function(r){var n,i,a,u;if(!((n=r?.bootstrap)===null||n===void 0)&&n.distinctId&&(!((i=r?.bootstrap)===null||i===void 0)&&i.isIdentifiedId?this.setPersistedProperty(pw.DistinctId,r.bootstrap.distinctId):this.setPersistedProperty(pw.AnonymousId,r.bootstrap.distinctId)),!((a=r?.bootstrap)===null||a===void 0)&&a.featureFlags){var f=Object.keys(((u=r.bootstrap)===null||u===void 0?void 0:u.featureFlags)||{}).filter(function(d){var c,o;return!!(!((o=(c=r.bootstrap)===null||c===void 0?void 0:c.featureFlags)===null||o===void 0)&&o[d])}).reduce(function(d,c){var o,l;return d[c]=((l=(o=r.bootstrap)===null||o===void 0?void 0:o.featureFlags)===null||l===void 0?void 0:l[c])||!1,d},{});this.setKnownFeatureFlags(f),r?.bootstrap.featureFlagPayloads&&this.setKnownFeatureFlagPayloads(r?.bootstrap.featureFlagPayloads)}},Object.defineProperty(t.prototype,"props",{get:function(){return this._props||(this._props=this.getPersistedProperty(pw.Props)),this._props||{}},set:function(r){this._props=r},enumerable:!1,configurable:!0}),t.prototype.clearProps=function(){this.props=void 0,this.sessionProps={}},t.prototype.on=function(r,n){return this._events.on(r,n)},t.prototype.reset=function(r){var n=Y1f([pw.Queue],r||[],!0);this.clearProps();for(var i=0,a=Object.keys(pw);i<a.length;i++){var u=a[i];n.includes(pw[u])||this.setPersistedProperty(pw[u],null)}},t.prototype.getCommonEventProperties=function(){var r=this.getFeatureFlags(),n={};if(r)for(var i=0,a=Object.entries(r);i<a.length;i++){var u=a[i],f=u[0],d=u[1];n["$feature/".concat(f)]=d}return Gg(Gg({$active_feature_flags:r?Object.keys(r):void 0},n),e.prototype.getCommonEventProperties.call(this))},t.prototype.enrichProperties=function(r){return Gg(Gg(Gg(Gg(Gg({},this.props),this.sessionProps),r||{}),this.getCommonEventProperties()),{$session_id:this.getSessionId()})},t.prototype.getSessionId=function(){var r=this.getPersistedProperty(pw.SessionId),n=this.getPersistedProperty(pw.SessionLastTimestamp)||0;return(!r||Date.now()-n>this._sessionExpirationTimeSeconds*1e3)&&(r=H0u(globalThis),this.setPersistedProperty(pw.SessionId,r)),this.setPersistedProperty(pw.SessionLastTimestamp,Date.now()),r},t.prototype.resetSessionId=function(){this.setPersistedProperty(pw.SessionId,null)},t.prototype.getAnonymousId=function(){var r=this.getPersistedProperty(pw.AnonymousId);return r||(r=H0u(globalThis),this.setPersistedProperty(pw.AnonymousId,r)),r},t.prototype.getDistinctId=function(){return this.getPersistedProperty(pw.DistinctId)||this.getAnonymousId()},t.prototype.unregister=function(r){delete this.props[r],this.setPersistedProperty(pw.Props,this.props)},t.prototype.register=function(r){this.props=Gg(Gg({},this.props),r),this.setPersistedProperty(pw.Props,this.props)},t.prototype.registerForSession=function(r){this.sessionProps=Gg(Gg({},this.sessionProps),r)},t.prototype.unregisterForSession=function(r){delete this.sessionProps[r]},t.prototype.identify=function(r,n,i){var a=this.getDistinctId();r=r||a,n?.$groups&&this.groups(n.$groups);var u=this.enrichProperties(Gg(Gg({},n),{$anon_distinct_id:this.getAnonymousId(),$set:n}));return r!==a&&(this.setPersistedProperty(pw.AnonymousId,a),this.setPersistedProperty(pw.DistinctId,r),this.reloadFeatureFlags()),e.prototype.identifyStateless.call(this,r,u,i),this},t.prototype.capture=function(r,n,i){var a=this.getDistinctId();n?.$groups&&this.groups(n.$groups);var u=this.enrichProperties(n);return e.prototype.captureStateless.call(this,a,r,u,i),this},t.prototype.alias=function(r){var n=this.getDistinctId(),i=this.enrichProperties({});return e.prototype.aliasStateless.call(this,r,n,i),this},t.prototype.autocapture=function(r,n,i,a){i===void 0&&(i={});var u=this.getDistinctId(),f={distinct_id:u,event:"$autocapture",properties:Gg(Gg({},this.enrichProperties(i)),{$event_type:r,$elements:n})};return this.enqueue("autocapture",f,a),this},t.prototype.groups=function(r){var n=this.props.$groups||{};return this.register({$groups:Gg(Gg({},n),r)}),Object.keys(r).find(function(i){return n[i]!==r[i]})&&this.reloadFeatureFlags(),this},t.prototype.group=function(r,n,i,a){var u;return this.groups((u={},u[r]=n,u)),i&&this.groupIdentify(r,n,i,a),this},t.prototype.groupIdentify=function(r,n,i,a){var u=this.getDistinctId(),f=this.enrichProperties({});return e.prototype.groupIdentifyStateless.call(this,r,n,i,a,u,f),this},t.prototype.personProperties=function(r){var n=this.getPersistedProperty(pw.PersonProperties)||{};return this.setPersistedProperty(pw.PersonProperties,Gg(Gg({},n),r)),this},t.prototype.groupProperties=function(r){var n=this.getPersistedProperty(pw.GroupProperties)||{};return Object.keys(n).length!==0&&Object.keys(n).forEach(function(i){n[i]=Gg(Gg({},n[i]),r[i]),delete r[i]}),this.setPersistedProperty(pw.GroupProperties,Gg(Gg({},n),r)),this},t.prototype.decideAsync=function(r){return r===void 0&&(r=!0),this._decideResponsePromise?this._decideResponsePromise:this._decideAsync(r)},t.prototype._decideAsync=function(r){return r===void 0&&(r=!0),gC(this,void 0,void 0,function(){var n,i,a,u,f,d=this;return mC(this,function(c){return n=this.getDistinctId(),i=this.props.$groups||{},a=this.getPersistedProperty(pw.PersonProperties)||{},u=this.getPersistedProperty(pw.GroupProperties)||{},f={$anon_distinct_id:r?this.getAnonymousId():void 0},this._decideResponsePromise=e.prototype.getDecide.call(this,n,i,a,u,f).then(function(o){if(o?.featureFlags){var l=o.featureFlags,g=o.featureFlagPayloads;if(o.errorsWhileComputingFlags){var O=d.getPersistedProperty(pw.FeatureFlags),P=d.getPersistedProperty(pw.FeatureFlagPayloads);l=Gg(Gg({},O),o.featureFlags),g=Gg(Gg({},P),o.featureFlagPayloads)}d.setKnownFeatureFlags(l),d.setKnownFeatureFlagPayloads(g)}return o}).finally(function(){d._decideResponsePromise=void 0}),[2,this._decideResponsePromise]})})},t.prototype.setKnownFeatureFlags=function(r){this.setPersistedProperty(pw.FeatureFlags,r),this._events.emit("featureflags",r)},t.prototype.setKnownFeatureFlagPayloads=function(r){this.setPersistedProperty(pw.FeatureFlagPayloads,r)},t.prototype.getFeatureFlag=function(r){var n=this.getFeatureFlags();if(n){var i=n[r];return i===void 0&&(i=!1),this.sendFeatureFlagEvent&&!this.flagCallReported[r]&&(this.flagCallReported[r]=!0,this.capture("$feature_flag_called",{$feature_flag:r,$feature_flag_response:i})),i}},t.prototype.getFeatureFlagPayload=function(r){var n=this.getFeatureFlagPayloads();if(n){var i=n[r];return i===void 0?null:this._parsePayload(i)}},t.prototype.getFeatureFlagPayloads=function(){var r=this,n=this.getPersistedProperty(pw.FeatureFlagPayloads);return n&&Object.fromEntries(Object.entries(n).map(function(i){var a=i[0],u=i[1];return[a,r._parsePayload(u)]}))},t.prototype.getFeatureFlags=function(){var r=this.getPersistedProperty(pw.FeatureFlags),n=this.getPersistedProperty(pw.OverrideFeatureFlags);if(!n)return r;r=r||{};for(var i in n)n[i]?r[i]=n[i]:delete r[i];return r},t.prototype.getFeatureFlagsAndPayloads=function(){var r=this.getFeatureFlags(),n=this.getFeatureFlagPayloads();return{flags:r,payloads:n}},t.prototype.isFeatureEnabled=function(r){var n=this.getFeatureFlag(r);if(n!==void 0)return!!n},t.prototype.reloadFeatureFlags=function(r){this.decideAsync().then(function(n){r?.(void 0,n?.featureFlags)}).catch(function(n){r?.(n,void 0),r||console.log("[PostHog] Error reloading feature flags",n)})},t.prototype.reloadFeatureFlagsAsync=function(r){var n;return r===void 0&&(r=!0),gC(this,void 0,void 0,function(){return mC(this,function(i){switch(i.label){case 0:return[4,this.decideAsync(r)];case 1:return[2,(n=i.sent())===null||n===void 0?void 0:n.featureFlags]}})})},t.prototype.onFeatureFlags=function(r){var n=this;return this.on("featureflags",function(){return gC(n,void 0,void 0,function(){var i;return mC(this,function(a){return i=this.getFeatureFlags(),i&&r(i),[2]})})})},t.prototype.onFeatureFlag=function(r,n){var i=this;return this.on("featureflags",function(){return gC(i,void 0,void 0,function(){var a;return mC(this,function(u){return a=this.getFeatureFlag(r),a!==void 0&&n(a),[2]})})})},t.prototype.overrideFeatureFlag=function(r){return r===null?this.setPersistedProperty(pw.OverrideFeatureFlags,null):this.setPersistedProperty(pw.OverrideFeatureFlags,r)},t})(Z1f);var Pq1=function(){function e(){this._memoryStorage={}}return e.prototype.getProperty=function(t){return this._memoryStorage[t]},e.prototype.setProperty=function(t,r){this._memoryStorage[t]=r!==null?r:void 0},e}(),k1f=function(e,t){return gC(void 0,void 0,void 0,function(){var r;return mC(this,function(n){switch(n.label){case 0:return[4,K1f.default.request({url:e,headers:t.headers,method:t.method.toLowerCase(),data:t.body,signal:t.signal,validateStatus:function(){return!0}})];case 1:return r=n.sent(),[2,{status:r.status,text:function(){return gC(void 0,void 0,void 0,function(){return mC(this,function(i){return[2,r.data]})})},json:function(){return gC(void 0,void 0,void 0,function(){return mC(this,function(i){return[2,r.data]})})}}]}})})},wq1=1152921504606847e3,H1f=function(e){K4n(t,e);function t(r){var n=e.call(this)||this;return Error.captureStackTrace(n,n.constructor),n.name="ClientError",n.message=r,Object.setPrototypeOf(n,t.prototype),n}return t}(Error),nk=function(e){K4n(t,e);function t(r){var n=e.call(this,r)||this;return n.name=n.constructor.name,Error.captureStackTrace(n,n.constructor),Object.setPrototypeOf(n,t.prototype),n}return t}(Error),jq1=function(){function e(t){var r=t.pollingInterval,n=t.personalApiKey,i=t.projectApiKey,a=t.timeout,u=t.host,f=pq1(t,["pollingInterval","personalApiKey","projectApiKey","timeout","host"]);this.debugMode=!1,this.pollingInterval=r,this.personalApiKey=n,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=a,this.projectApiKey=i,this.host=u,this.poller=void 0,this.fetch=f.fetch||k1f,this.loadFeatureFlags()}return e.prototype.debug=function(t){t===void 0&&(t=!0),this.debugMode=t},e.prototype.getFeatureFlag=function(t,r,n,i,a){return n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),gC(this,void 0,void 0,function(){var u,f,d,c,o;return mC(this,function(l){switch(l.label){case 0:return[4,this.loadFeatureFlags()];case 1:if(l.sent(),u=void 0,f=void 0,!this.loadedSuccessfullyOnce)return[2,u];for(d=0,c=this.featureFlags;d<c.length;d++)if(o=c[d],t===o.key){f=o;break}if(f!==void 0)try{u=this.computeFlagLocally(f,r,n,i,a),this.debugMode&&console.debug("Successfully computed flag locally: ".concat(t," -> ").concat(u))}catch(g){g instanceof nk?this.debugMode&&console.debug("InconclusiveMatchError when computing flag locally: ".concat(t,": ").concat(g)):g instanceof Error&&console.error("Error computing flag locally: ".concat(t,": ").concat(g))}return[2,u]}})})},e.prototype.computeFeatureFlagPayloadLocally=function(t,r){var n,i,a,u,f,d,c,o;return gC(this,void 0,void 0,function(){var l;return mC(this,function(g){switch(g.label){case 0:return[4,this.loadFeatureFlags()];case 1:return g.sent(),l=void 0,this.loadedSuccessfullyOnce?(typeof r=="boolean"?l=(u=(a=(i=(n=this.featureFlagsByKey)===null||n===void 0?void 0:n[t])===null||i===void 0?void 0:i.filters)===null||a===void 0?void 0:a.payloads)===null||u===void 0?void 0:u[r.toString()]:typeof r=="string"&&(l=(o=(c=(d=(f=this.featureFlagsByKey)===null||f===void 0?void 0:f[t])===null||d===void 0?void 0:d.filters)===null||c===void 0?void 0:c.payloads)===null||o===void 0?void 0:o[r]),l===void 0?[2,null]:[2,l]):[2,void 0]}})})},e.prototype.getAllFlagsAndPayloads=function(t,r,n,i){return r===void 0&&(r={}),n===void 0&&(n={}),i===void 0&&(i={}),gC(this,void 0,void 0,function(){var a,u,f,d=this;return mC(this,function(c){switch(c.label){case 0:return[4,this.loadFeatureFlags()];case 1:return c.sent(),a={},u={},f=this.featureFlags.length==0,this.featureFlags.map(function(o){return gC(d,void 0,void 0,function(){var l,g,O;return mC(this,function(P){switch(P.label){case 0:return P.trys.push([0,2,,3]),l=this.computeFlagLocally(o,t,r,n,i),a[o.key]=l,[4,this.computeFeatureFlagPayloadLocally(o.key,l)];case 1:return g=P.sent(),g&&(u[o.key]=g),[3,3];case 2:return O=P.sent(),O instanceof nk||O instanceof Error&&console.error("Error computing flag locally: ".concat(o.key,": ").concat(O)),f=!0,[3,3];case 3:return[2]}})})}),[2,{response:a,payloads:u,fallbackToDecide:f}]}})})},e.prototype.computeFlagLocally=function(t,r,n,i,a){if(n===void 0&&(n={}),i===void 0&&(i={}),a===void 0&&(a={}),t.ensure_experience_continuity)throw new nk("Flag has experience continuity enabled");if(!t.active)return!1;var u=t.filters||{},f=u.aggregation_group_type_index;if(f!=null){var d=this.groupTypeMapping[String(f)];if(!d)throw console.warn("[FEATURE FLAGS] Unknown group type index ".concat(f," for feature flag ").concat(t.key)),new nk("Flag has unknown group type index");if(!(d in n))return console.warn("[FEATURE FLAGS] Can't compute group feature flag: ".concat(t.key," without group names passed in")),!1;var c=a[d];return this.matchFeatureFlagProperties(t,n[d],c)}else return this.matchFeatureFlagProperties(t,r,i)},e.prototype.matchFeatureFlagProperties=function(t,r,n){for(var i,a=t.filters||{},u=a.groups||[],f=!1,d=void 0,c=Y1f([],u,!0).sort(function(M,q){var B=!!M.variant,I=!!q.variant;return B&&I?0:B?-1:I?1:0}),o=function(M){try{if(l.isConditionMatch(t,r,M,n)){var q=M.variant,B=((i=a.multivariate)===null||i===void 0?void 0:i.variants)||[];return q&&B.some(function(I){return I.key===q})?d=q:d=l.getMatchingVariant(t,r)||!0,"break"}}catch(I){if(I instanceof nk)f=!0;else throw I}},l=this,g=0,O=c;g<O.length;g++){var P=O[g],j=o(P);if(j==="break")break}if(d!==void 0)return d;if(f)throw new nk("Can't determine if feature flag is enabled or not with given properties");return!1},e.prototype.isConditionMatch=function(t,r,n,i){var a=n.rollout_percentage;if((n.properties||[]).length>0){for(var u=0,f=n.properties;u<f.length;u++){var d=f[u],c=d.type,o=!1;if(c==="cohort"?o=twf(d,i,this.cohorts):o=ewf(d,i),!o)return!1}if(a==null)return!0}return!(a!=null&&Q1f(t.key,r)>a/100)},e.prototype.getMatchingVariant=function(t,r){var n=Q1f(t.key,r,"variant"),i=this.variantLookupTable(t).find(function(a){return n>=a.valueMin&&n<a.valueMax});if(i)return i.key},e.prototype.variantLookupTable=function(t){var r,n=[],i=0,a=0,u=t.filters||{},f=((r=u.multivariate)===null||r===void 0?void 0:r.variants)||[];return f.forEach(function(d){a=i+d.rollout_percentage/100,n.push({valueMin:i,valueMax:a,key:d.key}),i=a}),n},e.prototype.loadFeatureFlags=function(t){return t===void 0&&(t=!1),gC(this,void 0,void 0,function(){return mC(this,function(r){switch(r.label){case 0:return!this.loadedSuccessfullyOnce||t?[4,this._loadFeatureFlags()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[2]}})})},e.prototype._loadFeatureFlags=function(){return gC(this,void 0,void 0,function(){var t,r,n,i=this;return mC(this,function(a){switch(a.label){case 0:this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(function(){return i._loadFeatureFlags()},this.pollingInterval),a.label=1;case 1:return a.trys.push([1,4,,5]),[4,this._requestFeatureFlagDefinitions()];case 2:if(t=a.sent(),t&&t.status===401)throw new H1f("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");return t&&t.status!==200?[2]:[4,t.json()];case 3:return r=a.sent(),"flags"in r||console.error("Invalid response when getting feature flags: ".concat(JSON.stringify(r))),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce(function(u,f){return u[f.key]=f,u},{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0,[3,5];case 4:if(n=a.sent(),n instanceof H1f)throw n;return[3,5];case 5:return[2]}})})},e.prototype._requestFeatureFlagDefinitions=function(){return gC(this,void 0,void 0,function(){var t,r,n,i,a;return mC(this,function(u){switch(u.label){case 0:t="".concat(this.host,"/api/feature_flag/local_evaluation?token=").concat(this.projectApiKey,"&send_cohorts"),r={method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.personalApiKey),"user-agent":"posthog-node/".concat(W0u)}},n=null,this.timeout&&typeof this.timeout=="number"&&(i=new AbortController,n=X1f(function(){i.abort()},this.timeout),r.signal=i.signal),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,this.fetch(t,r)];case 2:return[2,u.sent()];case 3:throw a=u.sent(),a;case 4:return clearTimeout(n),[7];case 5:return[2]}})})},e.prototype.stopPoller=function(){clearTimeout(this.poller)},e}();function Q1f(e,t,r){r===void 0&&(r="");var n=(0,$1f.createHash)();return n.update("".concat(e,".").concat(t).concat(r)),parseInt(n.digest("hex").slice(0,15),16)/wq1}function ewf(e,t){var r=e.key,n=e.value,i=e.operator||"exact";if(r in t){if(i==="is_not_set")throw new nk("Operator is_not_set is not supported")}else throw new nk("Property ".concat(r," not found in propertyValues"));var a=t[r];switch(i){case"exact":return Array.isArray(n)?n.indexOf(a)!==-1:n===a;case"is_not":return Array.isArray(n)?n.indexOf(a)===-1:n!==a;case"is_set":return r in t;case"icontains":return String(a).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(a).toLowerCase().includes(String(n).toLowerCase());case"regex":return J1f(String(n))&&String(a).match(String(n))!==null;case"not_regex":return J1f(String(n))&&String(a).match(String(n))===null;case"gt":return typeof a==typeof n&&a>n;case"gte":return typeof a==typeof n&&a>=n;case"lt":return typeof a==typeof n&&a<n;case"lte":return typeof a==typeof n&&a<=n;case"is_date_after":case"is_date_before":var u=G1f(n),f=G1f(a);return i==="is_date_before"?f<u:f>u;default:return console.error("Unknown operator: ".concat(i)),!1}}function twf(e,t,r){var n=String(e.value);if(!(n in r))throw new nk("can't match cohort without a given cohort property value");var i=r[n];return rwf(i,t,r)}function rwf(e,t,r){if(!e)return!0;var n=e.type,i=e.values;if(!i||i.length===0)return!0;var a=!1;if("values"in i[0]){for(var u=0,f=i;u<f.length;u++){var d=f[u];try{var c=rwf(d,t,r);if(n==="AND"){if(!c)return!1}else if(c)return!0}catch(O){if(O instanceof nk)console.debug("Failed to compute property ".concat(d," locally: ").concat(O)),a=!0;else throw O}}if(a)throw new nk("Can't match cohort without a given cohort property value");return n==="AND"}else{for(var o=0,l=i;o<l.length;o++){var d=l[o];try{var c=void 0;d.type==="cohort"?c=twf(d,t,r):c=ewf(d,t);var g=d.negation||!1;if(n==="AND"){if(!c&&!g||c&&g)return!1}else if(c&&!g||!c&&g)return!0}catch(P){if(P instanceof nk)console.debug("Failed to compute property ".concat(d," locally: ").concat(P)),a=!0;else throw P}}if(a)throw new nk("can't match cohort without a given cohort property value");return n==="AND"}}function J1f(e){try{return new RegExp(e),!0}catch{return!1}}function G1f(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){var t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new nk("".concat(e," is in an invalid date format"))}else throw new nk("The date provided ".concat(e," must be a string, number, or date object"))}var Dq1=30*1e3,Sq1=50*1e3,Oma=function(e){K4n(t,e);function t(r,n){n===void 0&&(n={});var i=this,a;return n.captureMode=n?.captureMode||"json",i=e.call(this,r,n)||this,i._memoryStorage=new Pq1,i.options=n,n.personalApiKey&&(i.featureFlagsPoller=new jq1({pollingInterval:typeof n.featureFlagsPollingInterval=="number"?n.featureFlagsPollingInterval:Dq1,personalApiKey:n.personalApiKey,projectApiKey:r,timeout:(a=n.requestTimeout)!==null&&a!==void 0?a:1e4,host:i.host,fetch:n.fetch})),i.distinctIdHasSentFlagCalls={},i.maxCacheSize=n.maxCacheSize||Sq1,i}return t.prototype.getPersistedProperty=function(r){return this._memoryStorage.getProperty(r)},t.prototype.setPersistedProperty=function(r,n){return this._memoryStorage.setProperty(r,n)},t.prototype.fetch=function(r,n){return this.options.fetch?this.options.fetch(r,n):k1f(r,n)},t.prototype.getLibraryId=function(){return"posthog-node"},t.prototype.getLibraryVersion=function(){return W0u},t.prototype.getCustomUserAgent=function(){return"posthog-node/".concat(W0u)},t.prototype.enable=function(){return e.prototype.optIn.call(this)},t.prototype.disable=function(){return e.prototype.optOut.call(this)},t.prototype.debug=function(r){var n;r===void 0&&(r=!0),e.prototype.debug.call(this,r),(n=this.featureFlagsPoller)===null||n===void 0||n.debug(r)},t.prototype.capture=function(r){var n=this,i=r.distinctId,a=r.event,u=r.properties,f=r.groups,d=r.sendFeatureFlags,c=r.timestamp,o=r.disableGeoip,l=function(g){e.prototype.captureStateless.call(n,i,a,g,{timestamp:c,disableGeoip:o})};d?e.prototype.getFeatureFlagsStateless.call(this,i,f,void 0,void 0,o).then(function(g){var O={};if(g)for(var P=0,j=Object.entries(g);P<j.length;P++){var M=j[P],q=M[0],B=M[1];B!==!1&&(O["$feature/".concat(q)]=B)}var I=Object.keys(g||{}).filter(function(F){return g?.[F]!==!1}),C=Gg({$active_feature_flags:I||void 0},O);l(Gg(Gg(Gg({},u),{$groups:f}),C))}):l(Gg(Gg({},u),{$groups:f}))},t.prototype.identify=function(r){var n=r.distinctId,i=r.properties,a=r.disableGeoip,u=i?.$set||i;e.prototype.identifyStateless.call(this,n,{$set:u},{disableGeoip:a})},t.prototype.alias=function(r){e.prototype.aliasStateless.call(this,r.alias,r.distinctId,void 0,{disableGeoip:r.disableGeoip})},t.prototype.getFeatureFlag=function(r,n,i){var a;return gC(this,void 0,void 0,function(){var u,f,d,c,o,l,g,O,P,j,M,q;return mC(this,function(B){switch(B.label){case 0:return u=i||{},f=u.groups,d=u.personProperties,c=u.groupProperties,o=u.disableGeoip,l=i||{},g=l.onlyEvaluateLocally,O=l.sendFeatureFlagEvents,g==null&&(g=!1),O==null&&(O=!0),[4,(a=this.featureFlagsPoller)===null||a===void 0?void 0:a.getFeatureFlag(r,n,f,d,c)];case 1:return P=B.sent(),j=P!==void 0,!j&&!g?[4,e.prototype.getFeatureFlagStateless.call(this,r,n,f,d,c,o)]:[3,3];case 2:P=B.sent(),B.label=3;case 3:return M="".concat(r,"_").concat(P),O&&(!(n in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[n].includes(M))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[n])?this.distinctIdHasSentFlagCalls[n].push(M):this.distinctIdHasSentFlagCalls[n]=[M],this.capture({distinctId:n,event:"$feature_flag_called",properties:(q={$feature_flag:r,$feature_flag_response:P,locally_evaluated:j},q["$feature/".concat(r)]=P,q),groups:f,disableGeoip:o})),[2,P]}})})},t.prototype.getFeatureFlagPayload=function(r,n,i,a){var u;return gC(this,void 0,void 0,function(){var f,d,c,o,l,g,O,P,j;return mC(this,function(M){switch(M.label){case 0:return f=a||{},d=f.groups,c=f.personProperties,o=f.groupProperties,l=f.disableGeoip,g=a||{},O=g.onlyEvaluateLocally,g.sendFeatureFlagEvents,P=void 0,i?[3,2]:[4,this.getFeatureFlag(r,n,Gg(Gg({},a),{onlyEvaluateLocally:!0}))];case 1:i=M.sent(),M.label=2;case 2:return i?[4,(u=this.featureFlagsPoller)===null||u===void 0?void 0:u.computeFeatureFlagPayloadLocally(r,i)]:[3,4];case 3:P=M.sent(),M.label=4;case 4:return O==null&&(O=!1),O==null&&(O=!1),j=P!==void 0,!j&&!O?[4,e.prototype.getFeatureFlagPayloadStateless.call(this,r,n,d,c,o,l)]:[3,6];case 5:P=M.sent(),M.label=6;case 6:try{return[2,JSON.parse(P)]}catch{return[2,P]}return[2]}})})},t.prototype.isFeatureEnabled=function(r,n,i){return gC(this,void 0,void 0,function(){var a;return mC(this,function(u){switch(u.label){case 0:return[4,this.getFeatureFlag(r,n,i)];case 1:return a=u.sent(),a===void 0?[2,void 0]:[2,!!a||!1]}})})},t.prototype.getAllFlags=function(r,n){return gC(this,void 0,void 0,function(){var i;return mC(this,function(a){switch(a.label){case 0:return[4,this.getAllFlagsAndPayloads(r,n)];case 1:return i=a.sent(),[2,i.featureFlags]}})})},t.prototype.getAllFlagsAndPayloads=function(r,n){var i;return gC(this,void 0,void 0,function(){var a,u,f,d,c,o,l,g,O,P,j;return mC(this,function(M){switch(M.label){case 0:return a=n||{},u=a.groups,f=a.personProperties,d=a.groupProperties,c=a.disableGeoip,o=(n||{}).onlyEvaluateLocally,o==null&&(o=!1),[4,(i=this.featureFlagsPoller)===null||i===void 0?void 0:i.getAllFlagsAndPayloads(r,u,f,d)];case 1:return l=M.sent(),g={},O={},P=!0,l&&(g=l.response,O=l.payloads,P=l.fallbackToDecide),P&&!o?[4,e.prototype.getFeatureFlagsAndPayloadsStateless.call(this,r,u,f,d,c)]:[3,3];case 2:j=M.sent(),g=Gg(Gg({},g),j.flags||{}),O=Gg(Gg({},O),j.payloads||{}),M.label=3;case 3:return[2,{featureFlags:g,featureFlagPayloads:O}]}})})},t.prototype.groupIdentify=function(r){var n=r.groupType,i=r.groupKey,a=r.properties,u=r.distinctId,f=r.disableGeoip;e.prototype.groupIdentifyStateless.call(this,n,i,a,{disableGeoip:f},u)},t.prototype.reloadFeatureFlags=function(){var r;return gC(this,void 0,void 0,function(){return mC(this,function(n){switch(n.label){case 0:return[4,(r=this.featureFlagsPoller)===null||r===void 0?void 0:r.loadFeatureFlags(!0)];case 1:return n.sent(),[2]}})})},t.prototype.shutdown=function(){this.shutdownAsync()},t.prototype.shutdownAsync=function(){var r;return gC(this,void 0,void 0,function(){return mC(this,function(n){return(r=this.featureFlagsPoller)===null||r===void 0||r.stopPoller(),[2,e.prototype.shutdownAsync.call(this)]})})},t}(Z1f);var Pma=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Oma(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.45.0-rc25",usingAccessToken:!0}})}flush(){this.posthog.flush()}};var Mvi=class{async sendEvent(){}async identify(){}async flush(){}};var Y4n=require("fs/promises"),owf=require("os"),uwf=require("path");var nwf=Yo(require("crypto")),jma=new Uint8Array(256),wma=jma.length;function Q0u(){return wma>jma.length-16&&(nwf.default.randomFillSync(jma),wma=0),jma.slice(wma,wma+=16)}var WH=[];for(let e=0;e<256;++e)WH.push((e+256).toString(16).slice(1));function iwf(e,t=0){return WH[e[t+0]]+WH[e[t+1]]+WH[e[t+2]]+WH[e[t+3]]+"-"+WH[e[t+4]]+WH[e[t+5]]+"-"+WH[e[t+6]]+WH[e[t+7]]+"-"+WH[e[t+8]]+WH[e[t+9]]+"-"+WH[e[t+10]]+WH[e[t+11]]+WH[e[t+12]]+WH[e[t+13]]+WH[e[t+14]]+WH[e[t+15]]}var awf=Yo(require("crypto")),J0u={randomUUID:awf.default.randomUUID};function Eq1(e,t,r){if(J0u.randomUUID&&!t&&!e)return J0u.randomUUID();e=e||{};let n=e.random||(e.rng||Q0u)();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 iwf(n)}var a8r=Eq1;var Aq1="id",Mq1=".fern",xvi=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new Oma(r),this.userId=t==null?void 0:efu(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.45.0-rc25",...t,...t.properties}})}flush(){this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=yf(v_.of((0,owf.homedir)()),Ms.of(Mq1),Ms.of(Aq1));await Wh(t)||(await(0,Y4n.mkdir)((0,uwf.dirname)(t),{recursive:!0}),await(0,Y4n.writeFile)(t,a8r())),this.persistedDistinctId=(await(0,Y4n.readFile)(t)).toString()}return this.persistedDistinctId}};var G0u;async function X4n(){return G0u==null&&(G0u=await xq1()),G0u}async function xq1(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new Mvi;let r=await X_a();return r!=null?new xvi({token:r,posthogApiKey:e}):await Y_a()!=null?new Pma({posthogApiKey:e}):new xvi({token:void 0,posthogApiKey:e})}catch{return new Mvi}}function Tvi(e,t){return function(){return e.apply(t,arguments)}}var{toString:Tq1}=Object.prototype,{getPrototypeOf:Y0u}=Object,Sma=(e=>t=>{let r=Tq1.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),dIt=e=>(e=e.toLowerCase(),t=>Sma(t)===e),Ema=e=>t=>typeof t===e,{isArray:Z4n}=Array,Cvi=Ema("undefined");function Cq1(e){return e!==null&&!Cvi(e)&&e.constructor!==null&&!Cvi(e.constructor)&&dDe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var lwf=dIt("ArrayBuffer");function qq1(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&lwf(e.buffer),t}var Iq1=Ema("string"),dDe=Ema("function"),fwf=Ema("number"),Ama=e=>e!==null&&typeof e=="object",Bq1=e=>e===!0||e===!1,Dma=e=>{if(Sma(e)!=="object")return!1;let t=Y0u(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Nq1=dIt("Date"),zq1=dIt("File"),Rq1=dIt("Blob"),Fq1=dIt("FileList"),Lq1=e=>Ama(e)&&dDe(e.pipe),Uq1=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||dDe(e.append)&&((t=Sma(e))==="formdata"||t==="object"&&dDe(e.toString)&&e.toString()==="[object FormData]"))},Vq1=dIt("URLSearchParams"),[Wq1,Hq1,Qq1,Jq1]=["ReadableStream","Request","Response","Headers"].map(dIt),Gq1=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function qvi(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),Z4n(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,f;for(n=0;n<u;n++)f=a[n],t.call(null,e[f],f,e)}}function dwf(e,t){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 Nrn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,pwf=e=>!Cvi(e)&&e!==Nrn;function K0u(){let{caseless:e}=pwf(this)&&this||{},t={},r=(n,i)=>{let a=e&&dwf(t,i)||i;Dma(t[a])&&Dma(n)?t[a]=K0u(t[a],n):Dma(n)?t[a]=K0u({},n):Z4n(n)?t[a]=n.slice():t[a]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&qvi(arguments[n],r);return t}var $q1=(e,t,r,{allOwnKeys:n}={})=>(qvi(t,(i,a)=>{r&&dDe(i)?e[a]=Tvi(i,r):e[a]=i},{allOwnKeys:n}),e),Kq1=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Yq1=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},Xq1=(e,t,r,n)=>{let i,a,u,f={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)u=i[a],(!n||n(u,e,t))&&!f[u]&&(t[u]=e[u],f[u]=!0);e=r!==!1&&Y0u(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},Zq1=(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},kq1=e=>{if(!e)return null;if(Z4n(e))return e;let t=e.length;if(!fwf(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},e61=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Y0u(Uint8Array)),t61=(e,t)=>{let n=(e&&e[Symbol.iterator]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},r61=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},n61=dIt("HTMLFormElement"),i61=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),swf=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),a61=dIt("RegExp"),_wf=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};qvi(r,(i,a)=>{let u;(u=t(i,a,e))!==!1&&(n[a]=u||i)}),Object.defineProperties(e,n)},o61=e=>{_wf(e,(t,r)=>{if(dDe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(dDe(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+"'")})}})},u61=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return Z4n(e)?n(e):n(String(e).split(t)),r},s61=()=>{},c61=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,$0u="abcdefghijklmnopqrstuvwxyz",cwf="0123456789",hwf={DIGIT:cwf,ALPHA:$0u,ALPHA_DIGIT:$0u+$0u.toUpperCase()+cwf},l61=(e=16,t=hwf.ALPHA_DIGIT)=>{let r="",{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r};function f61(e){return!!(e&&dDe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var d61=e=>{let t=new Array(10),r=(n,i)=>{if(Ama(n)){if(t.indexOf(n)>=0)return;if(!("toJSON"in n)){t[i]=n;let a=Z4n(n)?[]:{};return qvi(n,(u,f)=>{let d=r(u,i+1);!Cvi(d)&&(a[f]=d)}),t[i]=void 0,a}}return n};return r(e,0)},p61=dIt("AsyncFunction"),_61=e=>e&&(Ama(e)||dDe(e))&&dDe(e.then)&&dDe(e.catch),ywf=((e,t)=>e?setImmediate:t?((r,n)=>(Nrn.addEventListener("message",({source:i,data:a})=>{i===Nrn&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),Nrn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",dDe(Nrn.postMessage)),h61=typeof queueMicrotask<"u"?queueMicrotask.bind(Nrn):typeof process<"u"&&process.nextTick||ywf,Jl={isArray:Z4n,isArrayBuffer:lwf,isBuffer:Cq1,isFormData:Uq1,isArrayBufferView:qq1,isString:Iq1,isNumber:fwf,isBoolean:Bq1,isObject:Ama,isPlainObject:Dma,isReadableStream:Wq1,isRequest:Hq1,isResponse:Qq1,isHeaders:Jq1,isUndefined:Cvi,isDate:Nq1,isFile:zq1,isBlob:Rq1,isRegExp:a61,isFunction:dDe,isStream:Lq1,isURLSearchParams:Vq1,isTypedArray:e61,isFileList:Fq1,forEach:qvi,merge:K0u,extend:$q1,trim:Gq1,stripBOM:Kq1,inherits:Yq1,toFlatObject:Xq1,kindOf:Sma,kindOfTest:dIt,endsWith:Zq1,toArray:kq1,forEachEntry:t61,matchAll:r61,isHTMLForm:n61,hasOwnProperty:swf,hasOwnProp:swf,reduceDescriptors:_wf,freezeMethods:o61,toObjectSet:u61,toCamelCase:i61,noop:s61,toFiniteNumber:c61,findKey:dwf,global:Nrn,isContextDefined:pwf,ALPHABET:hwf,generateString:l61,isSpecCompliantForm:f61,toJSONObject:d61,isAsyncFn:p61,isThenable:_61,setImmediate:ywf,asap:h61};function k4n(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Jl.inherits(k4n,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Jl.toJSONObject(this.config),code:this.code,status:this.status}}});var vwf=k4n.prototype,bwf={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{bwf[e]={value:e}});Object.defineProperties(k4n,bwf);Object.defineProperty(vwf,"isAxiosError",{value:!0});k4n.from=(e,t,r,n,i,a)=>{let u=Object.create(vwf);return Jl.toFlatObject(e,u,function(d){return d!==Error.prototype},f=>f!=="isAxiosError"),k4n.call(u,e.message,t,r,n,i),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var zy=k4n;var gwf=Yo(oNr(),1),Mma=gwf.default;function X0u(e){return Jl.isPlainObject(e)||Jl.isArray(e)}function Owf(e){return Jl.endsWith(e,"[]")?e.slice(0,-2):e}function mwf(e,t,r){return e?e.concat(t).map(function(i,a){return i=Owf(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function y61(e){return Jl.isArray(e)&&!e.some(X0u)}var v61=Jl.toFlatObject(Jl,{},null,function(t){return/^is[A-Z]/.test(t)});function b61(e,t,r){if(!Jl.isObject(e))throw new TypeError("target must be an object");t=t||new(Mma||FormData),r=Jl.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(j,M){return!Jl.isUndefined(M[j])});let n=r.metaTokens,i=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&Jl.isSpecCompliantForm(t);if(!Jl.isFunction(i))throw new TypeError("visitor must be a function");function c(P){if(P===null)return"";if(Jl.isDate(P))return P.toISOString();if(!d&&Jl.isBlob(P))throw new zy("Blob is not supported. Use a Buffer instead.");return Jl.isArrayBuffer(P)||Jl.isTypedArray(P)?d&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function o(P,j,M){let q=P;if(P&&!M&&typeof P=="object"){if(Jl.endsWith(j,"{}"))j=n?j:j.slice(0,-2),P=JSON.stringify(P);else if(Jl.isArray(P)&&y61(P)||(Jl.isFileList(P)||Jl.endsWith(j,"[]"))&&(q=Jl.toArray(P)))return j=Owf(j),q.forEach(function(I,C){!(Jl.isUndefined(I)||I===null)&&t.append(u===!0?mwf([j],C,a):u===null?j:j+"[]",c(I))}),!1}return X0u(P)?!0:(t.append(mwf(M,j,a),c(P)),!1)}let l=[],g=Object.assign(v61,{defaultVisitor:o,convertValue:c,isVisitable:X0u});function O(P,j){if(!Jl.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+j.join("."));l.push(P),Jl.forEach(P,function(q,B){(!(Jl.isUndefined(q)||q===null)&&i.call(t,q,Jl.isString(B)?B.trim():B,j,g))===!0&&O(q,j?j.concat(B):[B])}),l.pop()}}if(!Jl.isObject(e))throw new TypeError("data must be an object");return O(e),t}var o8r=b61;function Pwf(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function wwf(e,t){this._pairs=[],e&&o8r(e,this,t)}var jwf=wwf.prototype;jwf.append=function(t,r){this._pairs.push([t,r])};jwf.toString=function(t){let r=t?function(n){return t.call(this,n,Pwf)}:Pwf;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var Dwf=wwf;function g61(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function zrn(e,t,r){if(!t)return e;let n=r&&r.encode||g61,i=r&&r.serialize,a;if(i?a=i(t,r):a=Jl.isURLSearchParams(t)?t.toString():new Dwf(t,r).toString(n),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Z0u=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){Jl.forEach(this.handlers,function(n){n!==null&&t(n)})}},k0u=Z0u;var e3n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Swf=Yo(require("url"),1),Ewf=Swf.default.URLSearchParams;var Awf={isNode:!0,classes:{URLSearchParams:Ewf,FormData:Mma,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var rvu={};kc(rvu,{hasBrowserEnv:()=>tvu,hasStandardBrowserEnv:()=>m61,hasStandardBrowserWebWorkerEnv:()=>O61,navigator:()=>evu,origin:()=>P61});var tvu=typeof window<"u"&&typeof document<"u",evu=typeof navigator=="object"&&navigator||void 0,m61=tvu&&(!evu||["ReactNative","NativeScript","NS"].indexOf(evu.product)<0),O61=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",P61=tvu&&window.location.href||"http://localhost";var g6={...rvu,...Awf};function nvu(e,t){return o8r(e,new g6.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,a){return g6.isNode&&Jl.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function w61(e){return Jl.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function j61(e){let t={},r=Object.keys(e),n,i=r.length,a;for(n=0;n<i;n++)a=r[n],t[a]=e[a];return t}function D61(e){function t(r,n,i,a){let u=r[a++];if(u==="__proto__")return!0;let f=Number.isFinite(+u),d=a>=r.length;return u=!u&&Jl.isArray(i)?i.length:u,d?(Jl.hasOwnProp(i,u)?i[u]=[i[u],n]:i[u]=n,!f):((!i[u]||!Jl.isObject(i[u]))&&(i[u]=[]),t(r,n,i[u],a)&&Jl.isArray(i[u])&&(i[u]=j61(i[u])),!f)}if(Jl.isFormData(e)&&Jl.isFunction(e.entries)){let r={};return Jl.forEachEntry(e,(n,i)=>{t(w61(n),i,r,0)}),r}return null}var xma=D61;function S61(e,t,r){if(Jl.isString(e))try{return(t||JSON.parse)(e),Jl.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var ivu={transitional:e3n,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=Jl.isObject(t);if(a&&Jl.isHTMLForm(t)&&(t=new FormData(t)),Jl.isFormData(t))return i?JSON.stringify(xma(t)):t;if(Jl.isArrayBuffer(t)||Jl.isBuffer(t)||Jl.isStream(t)||Jl.isFile(t)||Jl.isBlob(t)||Jl.isReadableStream(t))return t;if(Jl.isArrayBufferView(t))return t.buffer;if(Jl.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let f;if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return nvu(t,this.formSerializer).toString();if((f=Jl.isFileList(t))||n.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return o8r(f?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),S61(t)):t}],transformResponse:[function(t){let r=this.transitional||ivu.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Jl.isResponse(t)||Jl.isReadableStream(t))return t;if(t&&Jl.isString(t)&&(n&&!this.responseType||i)){let u=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t)}catch(f){if(u)throw f.name==="SyntaxError"?zy.from(f,zy.ERR_BAD_RESPONSE,this,null,this.response):f}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:g6.classes.FormData,Blob:g6.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Jl.forEach(["delete","get","head","post","put","patch"],e=>{ivu.headers[e]={}});var t3n=ivu;var E61=Jl.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"]),Mwf=e=>{let t={},r,n,i;return e&&e.split(`
1822
1822
  `).forEach(function(u){i=u.indexOf(":"),r=u.substring(0,i).trim().toLowerCase(),n=u.substring(i+1).trim(),!(!r||t[r]&&E61[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};var xwf=Symbol("internals");function Ivi(e){return e&&String(e).trim().toLowerCase()}function Tma(e){return e===!1||e==null?e:Jl.isArray(e)?e.map(Tma):String(e)}function A61(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 M61=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function avu(e,t,r,n,i){if(Jl.isFunction(n))return n.call(this,t,r);if(i&&(t=r),!!Jl.isString(t)){if(Jl.isString(n))return t.indexOf(n)!==-1;if(Jl.isRegExp(n))return n.test(t)}}function x61(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function T61(e,t){let r=Jl.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(i,a,u){return this[n].call(this,t,i,a,u)},configurable:!0})})}var r3n=class{constructor(t){t&&this.set(t)}set(t,r,n){let i=this;function a(f,d,c){let o=Ivi(d);if(!o)throw new Error("header name must be a non-empty string");let l=Jl.findKey(i,o);(!l||i[l]===void 0||c===!0||c===void 0&&i[l]!==!1)&&(i[l||d]=Tma(f))}let u=(f,d)=>Jl.forEach(f,(c,o)=>a(c,o,d));if(Jl.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(Jl.isString(t)&&(t=t.trim())&&!M61(t))u(Mwf(t),r);else if(Jl.isHeaders(t))for(let[f,d]of t.entries())a(d,f,n);else t!=null&&a(r,t,n);return this}get(t,r){if(t=Ivi(t),t){let n=Jl.findKey(this,t);if(n){let i=this[n];if(!r)return i;if(r===!0)return A61(i);if(Jl.isFunction(r))return r.call(this,i,n);if(Jl.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=Ivi(t),t){let n=Jl.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||avu(this,this[n],n,r)))}return!1}delete(t,r){let n=this,i=!1;function a(u){if(u=Ivi(u),u){let f=Jl.findKey(n,u);f&&(!r||avu(n,n[f],f,r))&&(delete n[f],i=!0)}}return Jl.isArray(t)?t.forEach(a):a(t),i}clear(t){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let a=r[n];(!t||avu(this,this[a],a,t,!0))&&(delete this[a],i=!0)}return i}normalize(t){let r=this,n={};return Jl.forEach(this,(i,a)=>{let u=Jl.findKey(n,a);if(u){r[u]=Tma(i),delete r[a];return}let f=t?x61(a):String(a).trim();f!==a&&delete r[a],r[f]=Tma(i),n[f]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return Jl.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=t&&Jl.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(`
1823
1823
  `)}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[xwf]=this[xwf]={accessors:{}}).accessors,i=this.prototype;function a(u){let f=Ivi(u);n[f]||(T61(i,u),n[f]=!0)}return Jl.isArray(t)?t.forEach(a):a(t),this}};r3n.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Jl.reduceDescriptors(r3n.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});Jl.freezeMethods(r3n);var C3=r3n;function Bvi(e,t){let r=this||t3n,n=t||r,i=C3.from(n.headers),a=n.data;return Jl.forEach(e,function(f){a=f.call(r,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function Nvi(e){return!!(e&&e.__CANCEL__)}function Twf(e,t,r){zy.call(this,e??"canceled",zy.ERR_CANCELED,t,r),this.name="CanceledError"}Jl.inherits(Twf,zy,{__CANCEL__:!0});var pDe=Twf;function p9t(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new zy("Request failed with status code "+r.status,[zy.ERR_BAD_REQUEST,zy.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function ovu(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function uvu(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Rrn(e,t){return e&&!ovu(t)?uvu(e,t):t}var Kwf=Yo(qwf(),1),Ywf=Yo(require("http"),1),Xwf=Yo(require("https"),1),Zwf=Yo(require("util"),1),kwf=Yo(q_a(),1),yAr=Yo(require("zlib"),1);var Frn="1.7.7";function zvi(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var z61=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function svu(e,t,r){let n=r&&r.Blob||g6.classes.Blob,i=zvi(e);if(t===void 0&&n&&(t=!0),i==="data"){e=i.length?e.slice(i.length+1):e;let a=z61.exec(e);if(!a)throw new zy("Invalid URL",zy.ERR_INVALID_URL);let u=a[1],f=a[2],d=a[3],c=Buffer.from(decodeURIComponent(d),f?"base64":"utf8");if(t){if(!n)throw new zy("Blob is not supported",zy.ERR_NOT_SUPPORT);return new n([c],{type:u})}return c}throw new zy("Unsupported protocol "+i,zy.ERR_NOT_SUPPORT)}var Lrn=Yo(require("stream"),1);var Iwf=Yo(require("stream"),1);var cvu=Symbol("internals"),lvu=class extends Iwf.default.Transform{constructor(t){t=Jl.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(n,i)=>!Jl.isUndefined(i[n])),super({readableHighWaterMark:t.chunkSize});let r=this[cvu]={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[cvu];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,n){let i=this[cvu],a=i.maxRate,u=this.readableHighWaterMark,f=i.timeWindow,d=1e3/f,c=a/d,o=i.minChunkSize!==!1?Math.max(i.minChunkSize,c*.01):0,l=(O,P)=>{let j=Buffer.byteLength(O);i.bytesSeen+=j,i.bytes+=j,i.isCaptured&&this.emit("progress",i.bytesSeen),this.push(O)?process.nextTick(P):i.onReadCallback=()=>{i.onReadCallback=null,process.nextTick(P)}},g=(O,P)=>{let j=Buffer.byteLength(O),M=null,q=u,B,I=0;if(a){let C=Date.now();(!i.ts||(I=C-i.ts)>=f)&&(i.ts=C,B=c-i.bytes,i.bytes=B<0?-B:0,I=0),B=c-i.bytes}if(a){if(B<=0)return setTimeout(()=>{P(null,O)},f-I);B<q&&(q=B)}q&&j>q&&j-q>o&&(M=O.subarray(q),O=O.subarray(0,q)),l(O,M?()=>{process.nextTick(P,null,M)}:P)};g(t,function O(P,j){if(P)return n(P);j?g(j,O):n(null)})}},fvu=lvu;var ejf=require("events");var Nwf=require("util"),zwf=require("stream");var{asyncIterator:Bwf}=Symbol,R61=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[Bwf]?yield*e[Bwf]():yield e},Cma=R61;var F61=Jl.ALPHABET.ALPHA_DIGIT+"-_",Rvi=new Nwf.TextEncoder,u8r=`\r
1824
1824
  `,L61=Rvi.encode(u8r),U61=2,dvu=class{constructor(t,r){let{escapeName:n}=this.constructor,i=Jl.isString(r),a=`Content-Disposition: form-data; name="${n(t)}"${!i&&r.name?`; filename="${n(r.name)}"`:""}${u8r}`;i?r=Rvi.encode(String(r).replace(/\r?\n|\r\n?/g,u8r)):a+=`Content-Type: ${r.type||"application/octet-stream"}${u8r}`,this.headers=Rvi.encode(a+u8r),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+U61,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;Jl.isTypedArray(t)?yield t:yield*Cma(t),yield L61}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},V61=(e,t,r)=>{let{tag:n="form-data-boundary",size:i=25,boundary:a=n+"-"+Jl.generateString(i,F61)}=r||{};if(!Jl.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let u=Rvi.encode("--"+a+u8r),f=Rvi.encode("--"+a+"--"+u8r+u8r),d=f.byteLength,c=Array.from(e.entries()).map(([l,g])=>{let O=new dvu(l,g);return d+=O.size,O});d+=u.byteLength*c.length,d=Jl.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),zwf.Readable.from(async function*(){for(let l of c)yield u,yield*l.encode();yield f}())},Rwf=V61;var Fwf=Yo(require("stream"),1),pvu=class extends Fwf.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)}},Lwf=pvu;var W61=(e,t)=>Jl.isAsyncFn(e)?function(...r){let n=r.pop();e.apply(this,r).then(i=>{try{t?n(null,...t(i)):n(null,i)}catch(a){n(a)}},n)}:e,Uwf=W61;function H61(e,t){e=e||10;let r=new Array(e),n=new Array(e),i=0,a=0,u;return t=t!==void 0?t:1e3,function(d){let c=Date.now(),o=n[a];u||(u=c),r[i]=d,n[i]=c;let l=a,g=0;for(;l!==i;)g+=r[l++],l=l%e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),c-u<t)return;let O=o&&c-o;return O?Math.round(g*1e3/O):void 0}}var Vwf=H61;function Q61(e,t){let r=0,n=1e3/t,i,a,u=(c,o=Date.now())=>{r=o,i=null,a&&(clearTimeout(a),a=null),e.apply(null,c)};return[(...c)=>{let o=Date.now(),l=o-r;l>=n?u(c,o):(i=c,a||(a=setTimeout(()=>{a=null,u(i)},n-l)))},()=>i&&u(i)]}var Wwf=Q61;var hAr=(e,t,r=3)=>{let n=0,i=Vwf(50,250);return Wwf(a=>{let u=a.loaded,f=a.lengthComputable?a.total:void 0,d=u-n,c=i(d),o=u<=f;n=u;let l={loaded:u,total:f,progress:f?u/f:void 0,bytes:d,rate:c||void 0,estimated:c&&f&&o?(f-u)/c:void 0,event:a,lengthComputable:f!=null,[t?"download":"upload"]:!0};e(l)},r)},i3n=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},a3n=e=>(...t)=>Jl.asap(()=>e(...t));var Hwf={flush:yAr.default.constants.Z_SYNC_FLUSH,finishFlush:yAr.default.constants.Z_SYNC_FLUSH},J61={flush:yAr.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:yAr.default.constants.BROTLI_OPERATION_FLUSH},Qwf=Jl.isFunction(yAr.default.createBrotliDecompress),{http:G61,https:$61}=kwf.default,K61=/https:?/,Jwf=g6.protocols.map(e=>e+":"),Gwf=(e,[t,r])=>(e.on("end",r).on("error",r),t);function Y61(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function tjf(e,t,r){let n=t;if(!n&&n!==!1){let i=(0,Kwf.getProxyForUrl)(r);i&&(n=new URL(i))}if(n){if(n.username&&(n.auth=(n.username||"")+":"+(n.password||"")),n.auth){(n.auth.username||n.auth.password)&&(n.auth=(n.auth.username||"")+":"+(n.auth.password||""));let a=Buffer.from(n.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let i=n.hostname||n.host;e.hostname=i,e.host=i,e.port=n.port,e.path=r,n.protocol&&(e.protocol=n.protocol.includes(":")?n.protocol:`${n.protocol}:`)}e.beforeRedirects.proxy=function(a){tjf(a,t,a.href)}}var X61=typeof process<"u"&&Jl.kindOf(process)==="process",Z61=e=>new Promise((t,r)=>{let n,i,a=(d,c)=>{i||(i=!0,n&&n(d,c))},u=d=>{a(d),t(d)},f=d=>{a(d,!0),r(d)};e(u,f,d=>n=d).catch(f)}),k61=({address:e,family:t})=>{if(!Jl.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},$wf=(e,t)=>k61(Jl.isObject(e)?e:{address:e,family:t}),rjf=X61&&function(t){return Z61(async function(n,i,a){let{data:u,lookup:f,family:d}=t,{responseType:c,responseEncoding:o}=t,l=t.method.toUpperCase(),g,O=!1,P;if(f){let or=Uwf(f,jr=>Jl.isArray(jr)?jr:[jr]);f=(jr,Vr,It)=>{or(jr,Vr,(cr,Hr,Gt)=>{if(cr)return It(cr);let wn=Jl.isArray(Hr)?Hr.map(An=>$wf(An)):[$wf(Hr,Gt)];Vr.all?It(cr,wn):It(cr,wn[0].address,wn[0].family)})}}let j=new ejf.EventEmitter,M=()=>{t.cancelToken&&t.cancelToken.unsubscribe(q),t.signal&&t.signal.removeEventListener("abort",q),j.removeAllListeners()};a((or,jr)=>{g=!0,jr&&(O=!0,M())});function q(or){j.emit("abort",!or||or.type?new pDe(null,t,P):or)}j.once("abort",i),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(q),t.signal&&(t.signal.aborted?q():t.signal.addEventListener("abort",q)));let B=Rrn(t.baseURL,t.url),I=new URL(B,g6.hasBrowserEnv?g6.origin:void 0),C=I.protocol||Jwf[0];if(C==="data:"){let or;if(l!=="GET")return p9t(n,i,{status:405,statusText:"method not allowed",headers:{},config:t});try{or=svu(t.url,c==="blob",{Blob:t.env&&t.env.Blob})}catch(jr){throw zy.from(jr,zy.ERR_BAD_REQUEST,t)}return c==="text"?(or=or.toString(o),(!o||o==="utf8")&&(or=Jl.stripBOM(or))):c==="stream"&&(or=Lrn.default.Readable.from(or)),p9t(n,i,{data:or,status:200,statusText:"OK",headers:new C3,config:t})}if(Jwf.indexOf(C)===-1)return i(new zy("Unsupported protocol "+C,zy.ERR_BAD_REQUEST,t));let F=C3.from(t.headers).normalize();F.set("User-Agent","axios/"+Frn,!1);let{onUploadProgress:K,onDownloadProgress:ee}=t,J=t.maxRate,G,te;if(Jl.isSpecCompliantForm(u)){let or=F.getContentType(/boundary=([-_\w\d]{10,70})/i);u=Rwf(u,jr=>{F.set(jr)},{tag:`axios-${Frn}-boundary`,boundary:or&&or[1]||void 0})}else if(Jl.isFormData(u)&&Jl.isFunction(u.getHeaders)){if(F.set(u.getHeaders()),!F.hasContentLength())try{let or=await Zwf.default.promisify(u.getLength).call(u);Number.isFinite(or)&&or>=0&&F.setContentLength(or)}catch{}}else if(Jl.isBlob(u))u.size&&F.setContentType(u.type||"application/octet-stream"),F.setContentLength(u.size||0),u=Lrn.default.Readable.from(Cma(u));else if(u&&!Jl.isStream(u)){if(!Buffer.isBuffer(u))if(Jl.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(Jl.isString(u))u=Buffer.from(u,"utf-8");else return i(new zy("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",zy.ERR_BAD_REQUEST,t));if(F.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return i(new zy("Request body larger than maxBodyLength limit",zy.ERR_BAD_REQUEST,t))}let Xe=Jl.toFiniteNumber(F.getContentLength());Jl.isArray(J)?(G=J[0],te=J[1]):G=te=J,u&&(K||G)&&(Jl.isStream(u)||(u=Lrn.default.Readable.from(u,{objectMode:!1})),u=Lrn.default.pipeline([u,new fvu({maxRate:Jl.toFiniteNumber(G)})],Jl.noop),K&&u.on("progress",Gwf(u,i3n(Xe,hAr(a3n(K),!1,3)))));let Re;if(t.auth){let or=t.auth.username||"",jr=t.auth.password||"";Re=or+":"+jr}if(!Re&&I.username){let or=I.username,jr=I.password;Re=or+":"+jr}Re&&F.delete("authorization");let Pt;try{Pt=zrn(I.pathname+I.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(or){let jr=new Error(or.message);return jr.config=t,jr.url=t.url,jr.exists=!0,i(jr)}F.set("Accept-Encoding","gzip, compress, deflate"+(Qwf?", br":""),!1);let Ct={path:Pt,method:l,headers:F.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:Re,protocol:C,family:d,beforeRedirect:Y61,beforeRedirects:{}};!Jl.isUndefined(f)&&(Ct.lookup=f),t.socketPath?Ct.socketPath=t.socketPath:(Ct.hostname=I.hostname.startsWith("[")?I.hostname.slice(1,-1):I.hostname,Ct.port=I.port,tjf(Ct,t.proxy,C+"//"+I.hostname+(I.port?":"+I.port:"")+Ct.path));let Wt,Bt=K61.test(Ct.protocol);if(Ct.agent=Bt?t.httpsAgent:t.httpAgent,t.transport?Wt=t.transport:t.maxRedirects===0?Wt=Bt?Xwf.default:Ywf.default:(t.maxRedirects&&(Ct.maxRedirects=t.maxRedirects),t.beforeRedirect&&(Ct.beforeRedirects.config=t.beforeRedirect),Wt=Bt?$61:G61),t.maxBodyLength>-1?Ct.maxBodyLength=t.maxBodyLength:Ct.maxBodyLength=1/0,t.insecureHTTPParser&&(Ct.insecureHTTPParser=t.insecureHTTPParser),P=Wt.request(Ct,function(jr){if(P.destroyed)return;let Vr=[jr],It=+jr.headers["content-length"];if(ee||te){let An=new fvu({maxRate:Jl.toFiniteNumber(te)});ee&&An.on("progress",Gwf(An,i3n(It,hAr(a3n(ee),!0,3)))),Vr.push(An)}let cr=jr,Hr=jr.req||P;if(t.decompress!==!1&&jr.headers["content-encoding"])switch((l==="HEAD"||jr.statusCode===204)&&delete jr.headers["content-encoding"],(jr.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Vr.push(yAr.default.createUnzip(Hwf)),delete jr.headers["content-encoding"];break;case"deflate":Vr.push(new Lwf),Vr.push(yAr.default.createUnzip(Hwf)),delete jr.headers["content-encoding"];break;case"br":Qwf&&(Vr.push(yAr.default.createBrotliDecompress(J61)),delete jr.headers["content-encoding"])}cr=Vr.length>1?Lrn.default.pipeline(Vr,Jl.noop):Vr[0];let Gt=Lrn.default.finished(cr,()=>{Gt(),M()}),wn={status:jr.statusCode,statusText:jr.statusMessage,headers:new C3(jr.headers),config:t,request:Hr};if(c==="stream")wn.data=cr,p9t(n,i,wn);else{let An=[],Ht=0;cr.on("data",function(dn){An.push(dn),Ht+=dn.length,t.maxContentLength>-1&&Ht>t.maxContentLength&&(O=!0,cr.destroy(),i(new zy("maxContentLength size of "+t.maxContentLength+" exceeded",zy.ERR_BAD_RESPONSE,t,Hr)))}),cr.on("aborted",function(){if(O)return;let dn=new zy("maxContentLength size of "+t.maxContentLength+" exceeded",zy.ERR_BAD_RESPONSE,t,Hr);cr.destroy(dn),i(dn)}),cr.on("error",function(dn){P.destroyed||i(zy.from(dn,null,t,Hr))}),cr.on("end",function(){try{let dn=An.length===1?An[0]:Buffer.concat(An);c!=="arraybuffer"&&(dn=dn.toString(o),(!o||o==="utf8")&&(dn=Jl.stripBOM(dn))),wn.data=dn}catch(dn){return i(zy.from(dn,null,t,wn.request,wn))}p9t(n,i,wn)})}j.once("abort",An=>{cr.destroyed||(cr.emit("error",An),cr.destroy())})}),j.once("abort",or=>{i(or),P.destroy(or)}),P.on("error",function(jr){i(zy.from(jr,null,t,P))}),P.on("socket",function(jr){jr.setKeepAlive(!0,1e3*60)}),t.timeout){let or=parseInt(t.timeout,10);if(Number.isNaN(or)){i(new zy("error trying to parse `config.timeout` to int",zy.ERR_BAD_OPTION_VALUE,t,P));return}P.setTimeout(or,function(){if(g)return;let Vr=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",It=t.transitional||e3n;t.timeoutErrorMessage&&(Vr=t.timeoutErrorMessage),i(new zy(Vr,It.clarifyTimeoutError?zy.ETIMEDOUT:zy.ECONNABORTED,t,P)),q()})}if(Jl.isStream(u)){let or=!1,jr=!1;u.on("end",()=>{or=!0}),u.once("error",Vr=>{jr=!0,P.destroy(Vr)}),u.on("close",()=>{!or&&!jr&&q(new pDe("Request stream has been aborted",t,P))}),u.pipe(P)}else P.end(u)})};var njf=g6.hasStandardBrowserEnv?function(){let t=g6.navigator&&/(msie|trident)/i.test(g6.navigator.userAgent),r=document.createElement("a"),n;function i(a){let u=a;return t&&(r.setAttribute("href",u),u=r.href),r.setAttribute("href",u),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(u){let f=Jl.isString(u)?i(u):u;return f.protocol===n.protocol&&f.host===n.host}}():function(){return function(){return!0}}();var ijf=g6.hasStandardBrowserEnv?{write(e,t,r,n,i,a){let u=[e+"="+encodeURIComponent(t)];Jl.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),Jl.isString(n)&&u.push("path="+n),Jl.isString(i)&&u.push("domain="+i),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var ajf=e=>e instanceof C3?{...e}:e;function pIt(e,t){t=t||{};let r={};function n(c,o,l){return Jl.isPlainObject(c)&&Jl.isPlainObject(o)?Jl.merge.call({caseless:l},c,o):Jl.isPlainObject(o)?Jl.merge({},o):Jl.isArray(o)?o.slice():o}function i(c,o,l){if(Jl.isUndefined(o)){if(!Jl.isUndefined(c))return n(void 0,c,l)}else return n(c,o,l)}function a(c,o){if(!Jl.isUndefined(o))return n(void 0,o)}function u(c,o){if(Jl.isUndefined(o)){if(!Jl.isUndefined(c))return n(void 0,c)}else return n(void 0,o)}function f(c,o,l){if(l in t)return n(c,o);if(l in e)return n(void 0,c)}let d={url:a,method:a,data:a,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:f,headers:(c,o)=>i(ajf(c),ajf(o),!0)};return Jl.forEach(Object.keys(Object.assign({},e,t)),function(o){let l=d[o]||i,g=l(e[o],t[o],o);Jl.isUndefined(g)&&l!==f||(r[o]=g)}),r}var qma=e=>{let t=pIt({},e),{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:a,headers:u,auth:f}=t;t.headers=u=C3.from(u),t.url=zrn(Rrn(t.baseURL,t.url),e.params,e.paramsSerializer),f&&u.set("Authorization","Basic "+btoa((f.username||"")+":"+(f.password?unescape(encodeURIComponent(f.password)):"")));let d;if(Jl.isFormData(r)){if(g6.hasStandardBrowserEnv||g6.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[c,...o]=d?d.split(";").map(l=>l.trim()).filter(Boolean):[];u.setContentType([c||"multipart/form-data",...o].join("; "))}}if(g6.hasStandardBrowserEnv&&(n&&Jl.isFunction(n)&&(n=n(t)),n||n!==!1&&njf(t.url))){let c=i&&a&&ijf.read(a);c&&u.set(i,c)}return t};var eI1=typeof XMLHttpRequest<"u",ojf=eI1&&function(e){return new Promise(function(r,n){let i=qma(e),a=i.data,u=C3.from(i.headers).normalize(),{responseType:f,onUploadProgress:d,onDownloadProgress:c}=i,o,l,g,O,P;function j(){O&&O(),P&&P(),i.cancelToken&&i.cancelToken.unsubscribe(o),i.signal&&i.signal.removeEventListener("abort",o)}let M=new XMLHttpRequest;M.open(i.method.toUpperCase(),i.url,!0),M.timeout=i.timeout;function q(){if(!M)return;let I=C3.from("getAllResponseHeaders"in M&&M.getAllResponseHeaders()),F={data:!f||f==="text"||f==="json"?M.responseText:M.response,status:M.status,statusText:M.statusText,headers:I,config:e,request:M};p9t(function(ee){r(ee),j()},function(ee){n(ee),j()},F),M=null}"onloadend"in M?M.onloadend=q:M.onreadystatechange=function(){!M||M.readyState!==4||M.status===0&&!(M.responseURL&&M.responseURL.indexOf("file:")===0)||setTimeout(q)},M.onabort=function(){M&&(n(new zy("Request aborted",zy.ECONNABORTED,e,M)),M=null)},M.onerror=function(){n(new zy("Network Error",zy.ERR_NETWORK,e,M)),M=null},M.ontimeout=function(){let C=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",F=i.transitional||e3n;i.timeoutErrorMessage&&(C=i.timeoutErrorMessage),n(new zy(C,F.clarifyTimeoutError?zy.ETIMEDOUT:zy.ECONNABORTED,e,M)),M=null},a===void 0&&u.setContentType(null),"setRequestHeader"in M&&Jl.forEach(u.toJSON(),function(C,F){M.setRequestHeader(F,C)}),Jl.isUndefined(i.withCredentials)||(M.withCredentials=!!i.withCredentials),f&&f!=="json"&&(M.responseType=i.responseType),c&&([g,P]=hAr(c,!0),M.addEventListener("progress",g)),d&&M.upload&&([l,O]=hAr(d),M.upload.addEventListener("progress",l),M.upload.addEventListener("loadend",O)),(i.cancelToken||i.signal)&&(o=I=>{M&&(n(!I||I.type?new pDe(null,e,M):I),M.abort(),M=null)},i.cancelToken&&i.cancelToken.subscribe(o),i.signal&&(i.signal.aborted?o():i.signal.addEventListener("abort",o)));let B=zvi(i.url);if(B&&g6.protocols.indexOf(B)===-1){n(new zy("Unsupported protocol "+B+":",zy.ERR_BAD_REQUEST,e));return}M.send(a||null)})};var tI1=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let n=new AbortController,i,a=function(c){if(!i){i=!0,f();let o=c instanceof Error?c:this.reason;n.abort(o instanceof zy?o:new pDe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new zy(`timeout ${t} of ms exceeded`,zy.ETIMEDOUT))},t),f=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(a):c.removeEventListener("abort",a)}),e=null)};e.forEach(c=>c.addEventListener("abort",a));let{signal:d}=n;return d.unsubscribe=()=>Jl.asap(f),d}},ujf=tI1;var rI1=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},nI1=async function*(e,t){for await(let r of iI1(e))yield*rI1(r,t)},iI1=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()}},_vu=(e,t,r,n)=>{let i=nI1(e,t),a=0,u,f=d=>{u||(u=!0,n&&n(d))};return new ReadableStream({async pull(d){try{let{done:c,value:o}=await i.next();if(c){f(),d.close();return}let l=o.byteLength;if(r){let g=a+=l;r(g)}d.enqueue(new Uint8Array(o))}catch(c){throw f(c),c}},cancel(d){return f(d),i.return()}},{highWaterMark:2})};var Bma=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",cjf=Bma&&typeof ReadableStream=="function",aI1=Bma&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),ljf=(e,...t)=>{try{return!!e(...t)}catch{return!1}},oI1=cjf&&ljf(()=>{let e=!1,t=new Request(g6.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),sjf=64*1024,hvu=cjf&&ljf(()=>Jl.isReadableStream(new Response("").body)),Ima={stream:hvu&&(e=>e.body)};Bma&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!Ima[t]&&(Ima[t]=Jl.isFunction(e[t])?r=>r[t]():(r,n)=>{throw new zy(`Response type '${t}' is not supported`,zy.ERR_NOT_SUPPORT,n)})})})(new Response);var uI1=async e=>{if(e==null)return 0;if(Jl.isBlob(e))return e.size;if(Jl.isSpecCompliantForm(e))return(await new Request(g6.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(Jl.isArrayBufferView(e)||Jl.isArrayBuffer(e))return e.byteLength;if(Jl.isURLSearchParams(e)&&(e=e+""),Jl.isString(e))return(await aI1(e)).byteLength},sI1=async(e,t)=>{let r=Jl.toFiniteNumber(e.getContentLength());return r??uI1(t)},fjf=Bma&&(async e=>{let{url:t,method:r,data:n,signal:i,cancelToken:a,timeout:u,onDownloadProgress:f,onUploadProgress:d,responseType:c,headers:o,withCredentials:l="same-origin",fetchOptions:g}=qma(e);c=c?(c+"").toLowerCase():"text";let O=ujf([i,a&&a.toAbortSignal()],u),P,j=O&&O.unsubscribe&&(()=>{O.unsubscribe()}),M;try{if(d&&oI1&&r!=="get"&&r!=="head"&&(M=await sI1(o,n))!==0){let F=new Request(t,{method:"POST",body:n,duplex:"half"}),K;if(Jl.isFormData(n)&&(K=F.headers.get("content-type"))&&o.setContentType(K),F.body){let[ee,J]=i3n(M,hAr(a3n(d)));n=_vu(F.body,sjf,ee,J)}}Jl.isString(l)||(l=l?"include":"omit");let q="credentials"in Request.prototype;P=new Request(t,{...g,signal:O,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:n,duplex:"half",credentials:q?l:void 0});let B=await fetch(P),I=hvu&&(c==="stream"||c==="response");if(hvu&&(f||I&&j)){let F={};["status","statusText","headers"].forEach(G=>{F[G]=B[G]});let K=Jl.toFiniteNumber(B.headers.get("content-length")),[ee,J]=f&&i3n(K,hAr(a3n(f),!0))||[];B=new Response(_vu(B.body,sjf,ee,()=>{J&&J(),j&&j()}),F)}c=c||"text";let C=await Ima[Jl.findKey(Ima,c)||"text"](B,e);return!I&&j&&j(),await new Promise((F,K)=>{p9t(F,K,{data:C,headers:C3.from(B.headers),status:B.status,statusText:B.statusText,config:e,request:P})})}catch(q){throw j&&j(),q&&q.name==="TypeError"&&/fetch/i.test(q.message)?Object.assign(new zy("Network Error",zy.ERR_NETWORK,e,P),{cause:q.cause||q}):zy.from(q,q&&q.code,e,P)}});var yvu={http:rjf,xhr:ojf,fetch:fjf};Jl.forEach(yvu,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var djf=e=>`- ${e}`,cI1=e=>Jl.isFunction(e)||e===null||e===!1,Nma={getAdapter:e=>{e=Jl.isArray(e)?e:[e];let{length:t}=e,r,n,i={};for(let a=0;a<t;a++){r=e[a];let u;if(n=r,!cI1(r)&&(n=yvu[(u=String(r)).toLowerCase()],n===void 0))throw new zy(`Unknown adapter '${u}'`);if(n)break;i[u||"#"+a]=n}if(!n){let a=Object.entries(i).map(([f,d])=>`adapter ${f} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1941,7 +1941,7 @@ errors:
1941
1941
  Run ${nl.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
1942
1942
  Run ${nl.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),u3n(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function hmu({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!XMf(e))return;let i=t??"",a=e.filter(f=>f.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((f,d)=>f.generatorName.localeCompare(d.generatorName)||f.currentVersion.localeCompare(d.currentVersion));for(let f of u)i+=`
1943
1943
  ${await SF1(f.generatorName)} (${f.apiName!=null?"API: "+f.apiName+", ":""}Group: ${f.generatorGroup}) `+nl.dim(f.currentVersion)+nl.reset(" \u2192 ")+nl.green(f.latestVersion);return i+=`
1944
- `,n?u3n(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function SF1(e){let r=await new YMf.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 EF1({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let f={type:"singleApi",versions:{}};return await kMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,c,o,l)=>{f.versions[c]==null&&(f.versions[c]={});let g=nP.getGeneratorNameOrThrow(o.name,l),O=await nP.getLatestGeneratorVersion({generatorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:i,includeMajor:a,context:l});O!=null&&(f.versions[c][o.name]={previousVersion:o.version,latestVersion:O})},generatorFilter:r,groupFilter:n}),f}let u={type:"multiApi",versions:{}};return await kMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,d,c,o)=>{if(f==null)return;u.versions[f]==null&&(u.versions[f]={}),u.versions[f][d]==null&&(u.versions[f][d]={});let l=nP.getGeneratorNameOrThrow(c.name,o),g=await nP.getLatestGeneratorVersion({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:c.version,channel:i,includeMajor:a,context:o});g!=null&&(u.versions[f][d][c.name]={previousVersion:c.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}async function kMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let f=await nP.loadGeneratorsConfiguration({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(f==null||f.groups==null)){for(let d of f.groups)if(!(i!=null&&d.groupName!==i))for(let c of d.generators)n!=null&&c.name!==n||await r(a.workspaceName,d.groupName,c,u)}})}))}function exf(e,t,r){let n=[];for(let[i,a]of Object.entries(e))for(let[u,f]of Object.entries(a)){r.debug(`Checking if ${u} in group ${i} has an upgrade available...`);let d=iae(f.latestVersion,f.previousVersion);r.debug(`Latest version: ${f.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),n.push({generatorName:u,generatorGroup:i,apiName:t,isUpgradeAvailable:d,currentVersion:f.previousVersion,latestVersion:f.latestVersion})}return n}async function JOa({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let u=[];if(e!=null){let f=await EF1({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a});if(f.type==="multiApi")for(let[d,c]of Object.entries(f.versions))u.push(...exf(c,d,t.logger));else u.push(...exf(f.versions,void 0,t.logger))}return u}var wbi=class extends Error{response;request;options;constructor(t,r,n){let i=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${i} ${a}`.trim(),f=u?`status code ${u}`:"an unknown error";super(`Request failed with ${f}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=n}};var B3n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var N3n=e=>e!==null&&typeof e=="object";var jbi=(...e)=>{for(let t of e)if((!N3n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return bmu({},...e)},ymu=(e={},t={})=>{let r=new globalThis.Headers(e),n=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[a,u]of i.entries())n&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function GOa(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:bmu(e[r]??[],t[r]??[])}var vmu=(e={},t={})=>({beforeRequest:GOa(e,t,"beforeRequest"),beforeRetry:GOa(e,t,"beforeRetry"),afterResponse:GOa(e,t,"afterResponse"),beforeError:GOa(e,t,"beforeError")}),bmu=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(N3n(i)){for(let[a,u]of Object.entries(i))N3n(u)&&a in t&&(u=bmu(t[a],u)),t={...t,[a]:u};N3n(i.hooks)&&(n=vmu(n,i.hooks),t.hooks=n),N3n(i.headers)&&(r=ymu(r,i.headers),t.headers=r)}return t};var txf=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";if(r&&n)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return e&&!t})(),rxf=typeof globalThis.AbortController=="function",nxf=typeof globalThis.ReadableStream=="function",ixf=typeof globalThis.FormData=="function",$Oa=["get","post","put","patch","head","delete"],AF1=()=>{};AF1();var axf={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},KOa=2147483647,YOa=Symbol("stop"),oxf={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},uxf={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var cxf=e=>$Oa.includes(e)?e.toUpperCase():e,MF1=["get","put","head","delete","options","trace"],xF1=[408,413,429,500,502,503,504],TF1=[413,429,503],sxf={limit:2,methods:MF1,statusCodes:xF1,afterStatusCodes:TF1,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},lxf=(e={})=>{if(typeof e=="number")return{...sxf,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...sxf,...e}};async function gmu(e,t,r,n){return new Promise((i,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new B3n(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(u)})})}async function mmu(e,{signal:t}){return new Promise((r,n)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(a),n(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e)})}var fxf=(e,t)=>{let r={};for(let n in t)!(n in uxf)&&!(n in oxf)&&!(n in e)&&(r[n]=t[n]);return r};var Dbi=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>KOa)throw new RangeError(`The \`timeout\` option cannot be greater than ${KOa}`);await Promise.resolve();let f=await n._fetch();for(let d of n._options.hooks.afterResponse){let c=await d(n.request,n._options,n._decorateResponse(f.clone()));c instanceof globalThis.Response&&(f=c)}if(n._decorateResponse(f),!f.ok&&n._options.throwHttpErrors){let d=new wbi(f,n.request,n._options);for(let c of n._options.hooks.beforeError)d=await c(d);throw d}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!nxf)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return n._stream(f.clone(),n._options.onDownloadProgress)}return f},u=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i();for(let[f,d]of Object.entries(axf))u[f]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||d);let o=(await u).clone();if(f==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[f]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:ymu(this._input.headers,r.headers),hooks:vmu({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:cxf(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:lxf(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(rxf){this.abortController=new globalThis.AbortController;let n=this._options.signal??this._input.signal;n?.addEventListener("abort",()=>{this.abortController.abort(n.reason)}),this._options.signal=this.abortController.signal}if(txf&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let i="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);(ixf&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof B3n)throw t;if(t instanceof wbi){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let n=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(n&&this._options.retry.afterStatusCodes.includes(t.response.status)){let i=Number(n)*1e3;Number.isNaN(i)?i=Date.parse(n)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());let a=this._options.retry.maxRetryAfter??i;return i<a?i:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let n=Math.min(this._calculateRetryDelay(r),KOa);if(this._retryCount<1)throw r;await mmu(n,{signal:this._options.signal});for(let i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===YOa)return;return this._retry(t)}}async _fetch(){for(let n of this._options.hooks.beforeRequest){let i=await n(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=fxf(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):gmu(r,t,this.abortController,this._options)}_stream(t,r){let n=Number(t.headers.get("content-length"))||0,i=0;return t.status===204?(r&&r({percent:1,totalBytes:n,transferredBytes:i},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array);async function f(){let{done:d,value:c}=await u.read();if(d){a.close();return}if(r){i+=c.byteLength;let o=n===0?0:i/n;r({percent:o,transferredBytes:i,totalBytes:n},c)}a.enqueue(c),await f()}await f()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var Omu=e=>{let t=(r,n)=>Dbi.create(r,jbi(e,n));for(let r of $Oa)t[r]=(n,i)=>Dbi.create(n,jbi(e,i,{method:r}));return t.create=r=>Omu(jbi(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Omu(jbi(e,r))),t.stop=YOa,t},CF1=Omu(),dxf=CF1;var Bxf=Yo(Ixf(),1);function Smu(e){let t=(0,Bxf.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var m2f=Yo(ATf(),1),O2f=Yo(g2f(),1),iOu=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},aOu=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function oOu(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??Smu(i),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),f=(0,m2f.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,f&&(d.authorization=`${f.type} ${f.token}`);let c;try{c=await dxf(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new iOu(e):l}if(t.allVersions)return c;let o=new aOu(e,r);if(c["dist-tags"][r]){let{time:l}=c;c=c.versions[c["dist-tags"][r]],c.time=l}else if(r){let l=!!c.versions[r];if(n&&!l)for(let[O,P]of Object.entries(c.versions))P.deprecated&&delete c.versions[O];if(!l){let O=Object.keys(c.versions);if(r=O2f.default.maxSatisfying(O,r),!r)throw o}let{time:g}=c;if(c=c.versions[r],c.time=g,!c)throw o}return c}async function Rbi(e,t){let{version:r}=await oOu(e.toLowerCase(),t);return r}async function Q3n({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:Rbi(e.packageName,{version:t?"prerelease":"latest"})}var P2f=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],bPa=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=KA.Info;constructor(t){this.ttyAwareLogger=new QOa(t);let r=this.getPackageName(),n=this.getPackageVersion(),i=this.getCliName();(r==null||n==null||i==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:n,cliName:i}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.45.0-rc24"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${nl.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new rTe}failWithoutThrowing(t,r){this.didSucceed=!1,UOa({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),(await X4n()).flush(),this.exitProgram()}async nudgeUpgradeIfAvaialable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await ZMf({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1944
+ `,n?u3n(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function SF1(e){let r=await new YMf.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 EF1({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let f={type:"singleApi",versions:{}};return await kMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,c,o,l)=>{f.versions[c]==null&&(f.versions[c]={});let g=nP.getGeneratorNameOrThrow(o.name,l),O=await nP.getLatestGeneratorVersion({generatorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:i,includeMajor:a,context:l});O!=null&&(f.versions[c][o.name]={previousVersion:o.version,latestVersion:O})},generatorFilter:r,groupFilter:n}),f}let u={type:"multiApi",versions:{}};return await kMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,d,c,o)=>{if(f==null)return;u.versions[f]==null&&(u.versions[f]={}),u.versions[f][d]==null&&(u.versions[f][d]={});let l=nP.getGeneratorNameOrThrow(c.name,o),g=await nP.getLatestGeneratorVersion({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:c.version,channel:i,includeMajor:a,context:o});g!=null&&(u.versions[f][d][c.name]={previousVersion:c.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}async function kMf({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let f=await nP.loadGeneratorsConfiguration({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(f==null||f.groups==null)){for(let d of f.groups)if(!(i!=null&&d.groupName!==i))for(let c of d.generators)n!=null&&c.name!==n||await r(a.workspaceName,d.groupName,c,u)}})}))}function exf(e,t,r){let n=[];for(let[i,a]of Object.entries(e))for(let[u,f]of Object.entries(a)){r.debug(`Checking if ${u} in group ${i} has an upgrade available...`);let d=iae(f.latestVersion,f.previousVersion);r.debug(`Latest version: ${f.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),n.push({generatorName:u,generatorGroup:i,apiName:t,isUpgradeAvailable:d,currentVersion:f.previousVersion,latestVersion:f.latestVersion})}return n}async function JOa({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let u=[];if(e!=null){let f=await EF1({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a});if(f.type==="multiApi")for(let[d,c]of Object.entries(f.versions))u.push(...exf(c,d,t.logger));else u.push(...exf(f.versions,void 0,t.logger))}return u}var wbi=class extends Error{response;request;options;constructor(t,r,n){let i=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${i} ${a}`.trim(),f=u?`status code ${u}`:"an unknown error";super(`Request failed with ${f}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=n}};var B3n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var N3n=e=>e!==null&&typeof e=="object";var jbi=(...e)=>{for(let t of e)if((!N3n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return bmu({},...e)},ymu=(e={},t={})=>{let r=new globalThis.Headers(e),n=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[a,u]of i.entries())n&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function GOa(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:bmu(e[r]??[],t[r]??[])}var vmu=(e={},t={})=>({beforeRequest:GOa(e,t,"beforeRequest"),beforeRetry:GOa(e,t,"beforeRetry"),afterResponse:GOa(e,t,"afterResponse"),beforeError:GOa(e,t,"beforeError")}),bmu=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(N3n(i)){for(let[a,u]of Object.entries(i))N3n(u)&&a in t&&(u=bmu(t[a],u)),t={...t,[a]:u};N3n(i.hooks)&&(n=vmu(n,i.hooks),t.hooks=n),N3n(i.headers)&&(r=ymu(r,i.headers),t.headers=r)}return t};var txf=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";if(r&&n)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return e&&!t})(),rxf=typeof globalThis.AbortController=="function",nxf=typeof globalThis.ReadableStream=="function",ixf=typeof globalThis.FormData=="function",$Oa=["get","post","put","patch","head","delete"],AF1=()=>{};AF1();var axf={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},KOa=2147483647,YOa=Symbol("stop"),oxf={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},uxf={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var cxf=e=>$Oa.includes(e)?e.toUpperCase():e,MF1=["get","put","head","delete","options","trace"],xF1=[408,413,429,500,502,503,504],TF1=[413,429,503],sxf={limit:2,methods:MF1,statusCodes:xF1,afterStatusCodes:TF1,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},lxf=(e={})=>{if(typeof e=="number")return{...sxf,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...sxf,...e}};async function gmu(e,t,r,n){return new Promise((i,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new B3n(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(u)})})}async function mmu(e,{signal:t}){return new Promise((r,n)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(a),n(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e)})}var fxf=(e,t)=>{let r={};for(let n in t)!(n in uxf)&&!(n in oxf)&&!(n in e)&&(r[n]=t[n]);return r};var Dbi=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>KOa)throw new RangeError(`The \`timeout\` option cannot be greater than ${KOa}`);await Promise.resolve();let f=await n._fetch();for(let d of n._options.hooks.afterResponse){let c=await d(n.request,n._options,n._decorateResponse(f.clone()));c instanceof globalThis.Response&&(f=c)}if(n._decorateResponse(f),!f.ok&&n._options.throwHttpErrors){let d=new wbi(f,n.request,n._options);for(let c of n._options.hooks.beforeError)d=await c(d);throw d}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!nxf)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return n._stream(f.clone(),n._options.onDownloadProgress)}return f},u=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i();for(let[f,d]of Object.entries(axf))u[f]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||d);let o=(await u).clone();if(f==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[f]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:ymu(this._input.headers,r.headers),hooks:vmu({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:cxf(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:lxf(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(rxf){this.abortController=new globalThis.AbortController;let n=this._options.signal??this._input.signal;n?.addEventListener("abort",()=>{this.abortController.abort(n.reason)}),this._options.signal=this.abortController.signal}if(txf&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let i="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);(ixf&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof B3n)throw t;if(t instanceof wbi){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let n=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(n&&this._options.retry.afterStatusCodes.includes(t.response.status)){let i=Number(n)*1e3;Number.isNaN(i)?i=Date.parse(n)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());let a=this._options.retry.maxRetryAfter??i;return i<a?i:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let n=Math.min(this._calculateRetryDelay(r),KOa);if(this._retryCount<1)throw r;await mmu(n,{signal:this._options.signal});for(let i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===YOa)return;return this._retry(t)}}async _fetch(){for(let n of this._options.hooks.beforeRequest){let i=await n(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=fxf(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):gmu(r,t,this.abortController,this._options)}_stream(t,r){let n=Number(t.headers.get("content-length"))||0,i=0;return t.status===204?(r&&r({percent:1,totalBytes:n,transferredBytes:i},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array);async function f(){let{done:d,value:c}=await u.read();if(d){a.close();return}if(r){i+=c.byteLength;let o=n===0?0:i/n;r({percent:o,transferredBytes:i,totalBytes:n},c)}a.enqueue(c),await f()}await f()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var Omu=e=>{let t=(r,n)=>Dbi.create(r,jbi(e,n));for(let r of $Oa)t[r]=(n,i)=>Dbi.create(n,jbi(e,i,{method:r}));return t.create=r=>Omu(jbi(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Omu(jbi(e,r))),t.stop=YOa,t},CF1=Omu(),dxf=CF1;var Bxf=Yo(Ixf(),1);function Smu(e){let t=(0,Bxf.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var m2f=Yo(ATf(),1),O2f=Yo(g2f(),1),iOu=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},aOu=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function oOu(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??Smu(i),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),f=(0,m2f.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,f&&(d.authorization=`${f.type} ${f.token}`);let c;try{c=await dxf(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new iOu(e):l}if(t.allVersions)return c;let o=new aOu(e,r);if(c["dist-tags"][r]){let{time:l}=c;c=c.versions[c["dist-tags"][r]],c.time=l}else if(r){let l=!!c.versions[r];if(n&&!l)for(let[O,P]of Object.entries(c.versions))P.deprecated&&delete c.versions[O];if(!l){let O=Object.keys(c.versions);if(r=O2f.default.maxSatisfying(O,r),!r)throw o}let{time:g}=c;if(c=c.versions[r],c.time=g,!c)throw o}return c}async function Rbi(e,t){let{version:r}=await oOu(e.toLowerCase(),t);return r}async function Q3n({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:Rbi(e.packageName,{version:t?"prerelease":"latest"})}var P2f=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],bPa=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=KA.Info;constructor(t){this.ttyAwareLogger=new QOa(t);let r=this.getPackageName(),n=this.getPackageVersion(),i=this.getCliName();(r==null||n==null||i==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:n,cliName:i}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.45.0-rc25"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${nl.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new rTe}failWithoutThrowing(t,r){this.didSucceed=!1,UOa({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),(await X4n()).flush(),this.exitProgram()}async nudgeUpgradeIfAvaialable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await ZMf({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1945
1945
  `)||(r+=`
1946
1946
  `),this.logger.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram(){process.exit(this.didSucceed?0:1)}longestWorkspaceName;registerWorkspaces(t){let r=EKo(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 ybi(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(a){throw a.message.includes("globalThis")?(n.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),n.failWithoutThrowing()):n.failWithoutThrowing(void 0,a),new rTe}finally{n.finish()}return i}async instrumentPostHogEvent(t){(await X4n()).sendEvent(t)}logger=Vpi(this.log.bind(this));constructTaskInitForWorkspace(t){let r=w2f(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?w2f(this.longestWorkspaceName):r).length,i=r.padEnd(n),a=P2f[this.numTasks++%P2f.length],u=nl.hex(a)(i);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===E4.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}])}logImmediately(t){let r=t.filter(n=>T3r.indexOf(n.level)>=T3r.indexOf(this.logLevel));this.ttyAwareLogger.log(r,{includeDebugInfo:this.logLevel===KA.Debug})}_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 Q3n({cliEnvironment:this.environment,includePreReleases:t}),n=iae(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},a=await JOa({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}};function w2f(e){return`[${e}]:`}var Xqf=Yo(Yqf(),1);async function PDe(e,t,r=[],{doNotPipeOutput:n=!1,secrets:i=[],substitutions:a={},...u}={}){let f=i.reduce((o,l)=>({...o,[l]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[o,l]of Object.entries(f))d=d.replaceAll(o,l);e?.debug(`+ ${d}`);let c=(0,Xqf.default)(t,r,u);return n||(c.stdout?.pipe(process.stdout),c.stderr?.pipe(process.stderr)),c}function SPa(e,{logger:t,...r}={}){return(n,i)=>PDe(t,e,n,{...r,...i})}var APa=require("fs/promises"),Zqf=Yo(Nne(),1),wH1="buf.gen.yaml",kqf="output",jH1=`${kqf}/openapi.yaml`,DH1=`
1947
1947
  version: v1
@@ -1987,7 +1987,7 @@ ${g}
1987
1987
  `+Object.keys(t.union).map(B=>` - ${B}`).join(`
1988
1988
  `)}];let g=typeof l=="string"?l:l.type;if(typeof g!="string")return Xtd(o);let O=n.resolveType({type:g,file:a});if(O==null)return[];if(O._type==="named"&&mA(O.declaration))return j8n({typeName:e,typeNameForBreadcrumb:e,rawObject:O.declaration,file:O.file,example:o,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f});let P=typeof l!="string"&&typeof l.key=="string"?l.key:void 0;if(P==null)return[];let{[P]:j,...M}=o,q=[];return j==null?q.push({message:`Missing property "${P}"`}):q.push(...iQ({rawTypeReference:g,example:j,typeResolver:n,exampleResolver:i,file:a,workspace:u,breadcrumbs:f})),q.push(...Xtd(M)),q}function Xtd(e){return Object.keys(e).map(t=>({severity:"error",message:`Unexpected property "${t}"`}))}function DTa({typeName:e,typeDeclaration:t,file:r,typeResolver:n,exampleResolver:i,example:a,workspace:u,breadcrumbs:f}){return zz(t,{alias:d=>Htd({rawAlias:d,file:r,typeResolver:n,exampleResolver:i,example:a,workspace:u,breadcrumbs:f}),enum:d=>Qtd({rawEnum:d,example:a,breadcrumbs:f}),object:d=>j8n({typeName:e,typeNameForBreadcrumb:e,rawObject:d,example:a,file:r,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f}),discriminatedUnion:d=>Ztd({typeName:e,rawUnion:d,example:a,file:r,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f}),undiscriminatedUnion:d=>Jtd({rawUnion:d,example:a,file:r,typeResolver:n,exampleResolver:i,workspace:u,breadcrumbs:f})})}var urd=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,k2w=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,eqw=/^\d{4}-\d{2}-\d{2}$/;function iQ({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:u}){if(typeof t=="string"&&t.startsWith(uFt)){let f=r.resolveType({type:e,file:i});if(f==null)return[];let d=n.parseExampleReference(t);if(d==null)return[];let c=r.resolveNamedType({referenceToNamedType:d.rawTypeReference,file:i});return c==null?[]:CPi({expected:f,actual:c})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return Dtn({type:e,_default:void 0,validation:void 0,visitor:{primitive:f=>tqw({primitiveType:f,example:t}),named:f=>{let d=r.getDeclarationOfNamedType({referenceToNamedType:f,file:i});return d==null?[]:DTa({typeName:d.typeName,typeDeclaration:d.declaration,file:d.file,example:t,typeResolver:r,exampleResolver:n,workspace:a,breadcrumbs:u})},map:({keyType:f,valueType:d})=>lS(t)?Object.entries(t).flatMap(([c,o])=>[...iQ({rawTypeReference:f,example:c,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,c]}),...iQ({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,c]})]):F2e(t,"a map"),list:f=>Array.isArray(t)?t.flatMap((d,c)=>iQ({rawTypeReference:f,example:d,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,`${c}`]})):F2e(t,"a list"),set:f=>{if(!Array.isArray(t))return F2e(t,"a list");let d=lKo(t);return d.length>0?[{severity:"error",message:`Set has duplicate elements:
1989
1989
  `+d.map(c=>` - ${JSON.stringify(c)}`).join(`
1990
- `)}]:t.flatMap((c,o)=>iQ({rawTypeReference:f,example:c,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,`${o}`]}))},optional:f=>t==null?[]:iQ({rawTypeReference:f,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:u}),unknown:()=>[],literal:f=>{switch(f.type){case"boolean":return LDe(d=>d===f.boolean,f.boolean.toString())(t);case"string":return LDe(d=>d===f.string,`"${f.string}"`)(t);default:Lc(f)}}}})}function tqw({primitiveType:e,example:t}){return e.v2!=null?kA._visit(e.v2,{integer:r=>rqw({example:t,rules:r.validation}),long:()=>rrd(t),uint:()=>ktd(t),uint64:()=>erd(t),double:r=>nqw({example:t,rules:r.validation}),float:()=>trd(t),boolean:()=>nrd(t),string:r=>iqw({example:t,rules:r.validation}),uuid:()=>ird(t),date:()=>ord(t),dateTime:()=>ard(t),base64:()=>S8n(t),bigInteger:()=>S8n(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):vP._visit(e.v1,{integer:()=>srd(t),long:()=>rrd(t),uint:()=>ktd(t),uint64:()=>erd(t),double:()=>crd(t),float:()=>trd(t),boolean:()=>nrd(t),string:()=>S8n(t),uuid:()=>ird(t),dateTime:()=>ard(t),date:()=>ord(t),base64:()=>S8n(t),bigInteger:()=>S8n(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function rqw({example:e,rules:t}){let r=srd(e);if(r.length>0||t==null)return r;let n=e;return t.min!=null&&(t.exclusiveMin&&n<=t.min||!t.exclusiveMin&&n<t.min)?[{message:`Expected integer to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&n>=t.max||!t.exclusiveMax&&n>t.max)?[{message:`Expected integer to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&n%t.multipleOf!==0?[{message:`Expected integer to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function nqw({example:e,rules:t}){let r=crd(e);if(r.length>0||t==null)return r;let n=e;return t.min!=null&&(t.exclusiveMin&&n<=t.min||!t.exclusiveMin&&n<t.min)?[{message:`Expected double to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&n>=t.max||!t.exclusiveMax&&n>t.max)?[{message:`Expected double to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&n%t.multipleOf!==0?[{message:`Expected double to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function iqw({example:e,rules:t}){let r=S8n(e);if(r.length>0||t==null)return r;let n=e;return t.minLength!=null&&n.length<t.minLength?[{message:`Expected string length to be greater than or equal to ${t.minLength}. Example is ${e}, which is of length ${n.length}.`}]:t.maxLength!=null&&n.length>t.maxLength?[{message:`Expected string length to be less than or equal to ${t.maxLength}. Example is ${e}, which is of length ${n.length}.`}]:t.pattern!=null&&!new RegExp(t.pattern).test(n)?[{message:`Expected string to match pattern ${t.pattern}. Example is ${e}.`}]:[]}var S8n=LDe(e=>typeof e=="string","a string"),srd=LDe(e=>Number.isInteger(e),"an integer"),ktd=LDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),erd=LDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),trd=LDe(e=>typeof e=="number","a float"),crd=LDe(e=>typeof e=="number","a double"),rrd=LDe(e=>Number.isInteger(e),"an integer"),nrd=LDe(e=>typeof e=="boolean","a boolean"),ird=LDe(e=>typeof e=="string"&&k2w.test(e),"a UUID"),ard=LDe(e=>typeof e=="string"&&urd.test(e),"an ISO 8601 timestamp"),ord=LDe(e=>typeof e=="string"&&eqw.test(e)&&urd.test(e),"a date");function LDe(e,t){return r=>e(r)?[]:F2e(r,t)}function CPi({expected:e,actual:t}){if(e._type==="unknown")return!0;if(e._type==="primitive")return t._type==="primitive"&&e.primitive.v1===t.primitive.v1;if(e._type==="container")switch(e.container._type){case"list":case"set":return t._type==="container"&&t.container._type===e.container._type&&CPi({expected:e.container.itemType,actual:t.container.itemType});case"optional":return CPi({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"map":return t._type==="container"&&t.container._type===e.container._type&&CPi({expected:e.container.keyType,actual:t.container.keyType})&&CPi({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:aqw({expected:e.container.literal,actual:t.container.literal});default:Lc(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;Lc(e)}function aqw({expected:e,actual:t}){switch(e.type){case"boolean":return t.type==="boolean"?e.boolean===t.boolean:!1;case"string":return t.type==="string"?e.string===t.string:!1;default:Lc(e)}}async function STa({_enum:e,file:t}){let r=await Promise.all(e.enum.map(async i=>({...await Z$(i),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof i=="string"?i:i.value,name:E8n(i).name,opts:{casingOverrides:typeof i!="string"?i.casing:void 0}})}))),n;if(e.default!=null&&(n=r.find(i=>i.name.wireValue===e.default),n==null))throw new Error(`Default value ${e.default} not found in enum values`);return{default:n,values:r}}function lrd(e,t){let r=t.enum.find(n=>typeof n=="string"?!1:n.value===e);return{name:typeof r=="string"?e:r?.name??e,wasExplicitlySet:!1}}function E8n(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function Tqu({typeName:e,typeDeclaration:t,example:r,typeResolver:n,exampleResolver:i,fileContainingType:a,fileContainingExample:u,workspace:f}){return zz(t,{alias:d=>dS.alias({value:lT({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f})}),object:d=>frd({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f}),discriminatedUnion:d=>{let c=han(d);if(!lS(r))throw new Error("Example is not an object");let o=r[c];if(o==null)throw new Error("Example is missing discriminant: "+c);if(typeof o!="string")throw new Error("Discriminant value is not a string");let l=d.union[o];if(l==null)throw new Error(`${o} is not one of the specified discriminant values.`);let g=typeof l=="string"?l:typeof l.type=="string"?l.type:void 0;return dS.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:cRr(d).name,wireValue:c}),singleUnionType:uqw({rawValueType:g,rawSingleUnionType:l,fileContainingType:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,example:r,discriminant:c,discriminantValueForExample:o,workspace:f})})},enum:d=>{if(typeof r!="string")throw new Error("Enum example is not a string");return dS.enum({value:u.casingsGenerator.generateNameAndWireValue({name:lrd(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,o]of d.union.entries())if(iQ({rawTypeReference:typeof o=="string"?o:o.type,example:r,typeResolver:n,exampleResolver:i,file:a,workspace:f,breadcrumbs:[]}).length===0)return dS.undiscriminatedUnion({index:c,singleUnionType:lT({example:r,rawTypeBeingExemplified:typeof o=="string"?o:o.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f})});throw new Error("Example doesn't match any of the undiscriminated unions")}})}function lT({example:e,fileContainingExample:t,rawTypeBeingExemplified:r,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}){let{resolvedExample:f,file:d}=a.resolveExampleOrThrow({example:e,file:t}),c=a.resolveAllReferencesInExampleOrThrow({example:e,file:t}).resolvedExample;return{shape:Dtn({type:r,_default:void 0,validation:void 0,visitor:{primitive:l=>oqw({example:f,typeBeingExemplified:l.v1}),map:({keyType:l,valueType:g})=>{if(!lS(f))throw new Error("Example is not an object");return dO.container(gA.map({map:Object.entries(f).map(([O,P])=>({key:lT({example:O,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}),value:lT({example:P,fileContainingExample:d,rawTypeBeingExemplified:g,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})})),keyType:n.parseTypeReference(l),valueType:n.parseTypeReference(g)}))},list:l=>{if(!Array.isArray(f))throw new Error("Example is not a list");return dO.container(gA.list({list:f.map(g=>lT({example:g,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})),itemType:n.parseTypeReference(l)}))},set:l=>{if(!Array.isArray(f))throw new Error("Example is not a list");return dO.container(gA.set({set:f.map(g=>lT({example:g,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})),itemType:n.parseTypeReference(l)}))},optional:l=>dO.container(gA.optional({optional:f!=null?lT({example:f,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}):void 0,valueType:n.parseTypeReference(l)})),literal:l=>{switch(l.type){case"boolean":return dO.container(gA.literal({literal:Pv.boolean(l.boolean)}));case"string":return dO.container(gA.literal({literal:Pv.string({original:l.string})}));default:Lc(l)}},named:l=>{let g=i.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:r,file:n}),O=n.parseTypeReference(l);if(O.type!=="named")throw new Error("Type reference is not to a named type.");let P={typeId:O.typeId,fernFilepath:O.fernFilepath,name:O.name};return dO.named({typeName:P,shape:Tqu({typeName:P,typeDeclaration:g.declaration,fileContainingType:g.file,fileContainingExample:d,example:f,typeResolver:i,exampleResolver:a,workspace:u})})},unknown:()=>dO.unknown(c)}}),jsonExample:c}}function oqw({example:e,typeBeingExemplified:t}){return vP._visit(t,{string:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},dateTime:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.datetime({datetime:new Date(e),raw:e}))},date:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.date(e))},base64:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},uint:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.uint(e))},uint64:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.uint64(e))},integer:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.integer(e))},float:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.float(e))},double:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.double(e))},long:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.long(e))},boolean:()=>{if(typeof e!="boolean")throw new Error("Example is not a boolean");return dO.primitive(Pv.boolean(e))},uuid:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.uuid(e))},bigInteger:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function frd({typeName:e,rawObject:t,example:r,fileContainingType:n,fileContainingExample:i,typeResolver:a,exampleResolver:u,workspace:f}){if(!lS(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return dS.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[c,o])=>{let l=drd({typeName:e,wirePropertyKey:c,rawObject:t,typeResolver:a,file:n});if(l==null)throw new Error("Could not find original type declaration for property: "+c);let g=lT({example:o,fileContainingExample:i,rawTypeBeingExemplified:typeof l.rawPropertyType=="string"?l.rawPropertyType:l.rawPropertyType.type,fileContainingRawTypeReference:l.file,typeResolver:a,exampleResolver:u,workspace:f});return d.push({name:i.casingsGenerator.generateNameAndWireValue({name:nQ({propertyKey:c,property:l.rawPropertyType}).name,wireValue:c}),value:g,originalTypeDeclaration:l.typeName}),d},[]):[]})}function drd({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:n,file:i}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:i}:qPi({wirePropertyKey:t,extends_:r.extends,typeResolver:n,file:i})}function qPi({wirePropertyKey:e,extends_:t,typeResolver:r,file:n}){if(t!=null){let i=typeof t=="string"?[t]:t;for(let a of i){let u=r.resolveNamedTypeOrThrow({referenceToNamedType:a,file:n});if(u._type!=="named"||!mA(u.declaration))throw new Error("Extension is not of a named object");let f=drd({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(f!=null)return f}}}function uqw({rawValueType:e,rawSingleUnionType:t,fileContainingType:r,fileContainingExample:n,typeResolver:i,exampleResolver:a,example:u,discriminant:f,discriminantValueForExample:d,workspace:c}){let o=n.casingsGenerator.generateNameAndWireValue({name:D8n({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:Bz.noProperties()};let l=xqu({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:i});switch(l.propertiesType){case"singleProperty":{if(!lS(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:Bz.singleProperty(lT({example:u[l.name.wireValue],rawTypeBeingExemplified:e,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:n,workspace:c}))}}case"samePropertiesAsObject":{if(!lS(u))throw new Error("Example is not an object");let{[f]:g,...O}=u,P=i.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});if(!mA(P.declaration))throw new Error(`${e} is not an object`);let j={typeId:l.typeId,fernFilepath:l.fernFilepath,name:l.name};return{wireDiscriminantValue:o,shape:Bz.samePropertiesAsObject({typeId:s1.generateTypeId(j),object:frd({rawObject:P.declaration,example:O,fileContainingType:P.file,fileContainingExample:n,typeResolver:i,exampleResolver:a,typeName:j,workspace:c})})}}default:Lc(l)}}async function ETa({file:e,queryParameterKey:t,queryParameter:r}){let{name:n}=_Mr({queryParameterKey:t,queryParameter:r}),i=e.parseTypeReference(r);return{...await Z$(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:n}),valueType:i,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1}}function _Mr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function sqw(e){let t=JSON.stringify(e);return prd.default.createHash("sha256").update(t).digest("hex")}function _rd({service:e,endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,variableResolver:u,file:f,workspace:d}){let c=lqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:a,variableResolver:u,file:f,workspace:d});return{id:r.name??sqw(r),name:r.name!=null?f.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:hqw({file:f,service:e,endpoint:t,example:r,pathParams:c}),...c,...fqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:a,file:f,workspace:d}),queryParameters:r["query-parameters"]!=null?Object.entries(r["query-parameters"]).map(([o,l])=>{let g=typeof t.request!="string"?t.request?.["query-parameters"]?.[o]:void 0;if(g==null)throw new Error(`Query parameter ${o} does not exist`);return{name:f.casingsGenerator.generateNameAndWireValue({name:_Mr({queryParameterKey:o,queryParameter:g}).name,wireValue:o}),value:lT({example:l,rawTypeBeingExemplified:typeof g=="string"?g:g.type,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:f,fileContainingExample:f,workspace:d}),shape:cqw({queryParameter:g})}}):[],request:dqw({endpoint:t,example:r,typeResolver:n,exampleResolver:a,file:f,workspace:d}),response:pqw({endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,file:f,workspace:d})}}function cqw({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?NF.exploded():NF.single()}function lqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:i,variableResolver:a,file:u,workspace:f}){let d=[],c=[],o=[],l=({name:g,pathParameterDeclaration:O,examplePathParameter:P})=>{let j=IPi({parameter:O,variableResolver:a,file:u});return{name:g,value:lT({example:P,rawTypeBeingExemplified:j.rawType,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:j.file,fileContainingExample:u,workspace:f})}};if(r["path-parameters"]!=null)for(let[g,O]of Object.entries(r["path-parameters"])){let P=u.rootApiFile["path-parameters"]?.[g],j=e["path-parameters"]?.[g],M=t["path-parameters"]?.[g];if(P!=null)d.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:P,examplePathParameter:O}));else if(M!=null)o.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:M,examplePathParameter:O}));else if(j!=null)c.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:j,examplePathParameter:O}));else throw new Error(`Path parameter ${g} does not exist`)}return{rootPathParameters:d,endpointPathParameters:o,servicePathParameters:c}}function fqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:i,file:a,workspace:u}){let f=[],d=[];if(r.headers!=null)for(let[c,o]of Object.entries(r.headers)){let l=typeof t.request!="string"?t.request?.headers?.[c]:void 0,g=e.headers?.[c];if(l!=null)d.push({name:a.casingsGenerator.generateNameAndWireValue({name:sLt({headerKey:c,header:l}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else if(g!=null)f.push({name:a.casingsGenerator.generateNameAndWireValue({name:sLt({headerKey:c,header:g}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof g=="string"?g:g.type,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else throw new Error(`Header ${c} does not exist`)}return{endpointHeaders:d,serviceHeaders:f}}function dqw({endpoint:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=typeof e.request!="string"?e.request?.body:e.request;if(u==null||typeof u=="string"&&syi(u)!=null)return;if(!v6(u))return b$.reference(lT({example:t.request,rawTypeBeingExemplified:typeof u!="string"?u.type:u,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}));if(!t.request)return;if(!lS(t.request))throw new Error(`Example is not an object. Got: ${JSON.stringify(t.request)}`);let f=[];for(let[d,c]of Object.entries(t.request)){let o=u.properties?.[d],l=typeof o=="string"?o:o?.type;if(!(l!=null&&ACe(l)!=null))if(o!=null)f.push({name:i.casingsGenerator.generateNameAndWireValue({name:nQ({propertyKey:d,property:o}).name,wireValue:d}),value:lT({example:c,rawTypeBeingExemplified:typeof o!="string"?o.type:o,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),originalTypeDeclaration:void 0});else{let g=qPi({extends_:u.extends,wirePropertyKey:d,typeResolver:r,file:i});if(g==null)throw new Error("Could not find original type declaration for property: "+d);f.push({name:i.casingsGenerator.generateNameAndWireValue({name:nQ({propertyKey:d,property:g.rawPropertyType}).name,wireValue:d}),value:lT({example:c,rawTypeBeingExemplified:typeof g.rawPropertyType=="string"?g.rawPropertyType:g.rawPropertyType.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:g.file,fileContainingExample:i,workspace:a}),originalTypeDeclaration:g.typeName})}}return b$.inlinedRequestBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t.request,file:i}).resolvedExample,properties:f})}function pqw({endpoint:e,example:t,typeResolver:r,errorResolver:n,exampleResolver:i,file:a,workspace:u}){return t.response==null?T4.ok(cN.body(void 0)):Etn(e,t.response,{body:f=>{if(f.error!=null){let d=n.getDeclarationOrThrow(f.error,a);return T4.error({error:uRr({errorName:f.error,file:a}),body:d.declaration.type!=null?lT({example:f.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return T4.ok(cN.body(_qw({endpoint:e,example:f,typeResolver:r,exampleResolver:i,file:a,workspace:u})))},stream:f=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return T4.ok(cN.stream(f.stream.map(c=>{if(d!=null)return lT({example:c,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter($M)))},events:f=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return T4.ok(cN.sse(f.stream.map(({event:c,data:o})=>{if(d==null)return;let l=lT({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:c,data:l}}).filter($M)))}})}function _qw({endpoint:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=typeof e.response!="string"?e.response?.type:e.response;if(u!=null&&t.body!=null)return lT({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a})}function hqw({file:e,service:t,endpoint:r,example:n,pathParams:i}){let a=k1(e.rootApiFile["base-path"]??"",t["base-path"],r.path);if(n["path-parameters"]!=null)for(let u of[...i.endpointPathParameters,...i.servicePathParameters,...i.rootPathParameters])a=a.replaceAll(`{${u.name.originalName}}`,`${u.value.jsonExample}`);return a=a.replaceAll("//","/"),a.startsWith("/")||(a=`/${a}`),a}async function hrd({endpoint:e,file:t,typeResolver:r}){return{body:await yqw({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}async function yqw({endpoint:e,file:t,typeResolver:r}){let n=await vqw({endpoint:e,file:t,typeResolver:r}),i=await bqw({endpoint:e,file:t,typeResolver:r});if(n!=null&&i!=null){let a;switch(n.type){case"fileDownload":{a=Fie.fileDownload({...n});break}case"json":{a=Fie.json({...n.value});break}case"text":{a=Fie.text({...n});break}default:Lc(n)}return A3.streamParameter({nonStreamResponse:a,streamResponse:i})}else{if(n!=null)return n;if(i!=null)return A3.streaming(i)}}async function vqw({endpoint:e,file:t,typeResolver:r}){let{response:n}=e;if(n!=null){let i=typeof n!="string"?n.docs:void 0,a=typeof n=="string"?n:n.type;return ACe(a)!=null?A3.fileDownload({docs:i}):cyi(a)!=null?A3.text({docs:i}):await gqw(n,i,t,r)}}async function bqw({endpoint:e,file:t,typeResolver:r}){let{["response-stream"]:n}=e;if(n!=null){let i=typeof n!="string"?n.docs:void 0,a=typeof n=="string"?n:n.type,u=typeof n=="string"?"json":n.format??"json";return C6n(a)?Lie.text({docs:i}):typeof n!="string"&&u==="sse"?Lie.sse({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0}):Lie.json({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0})}}async function gqw(e,t,r,n){let i=r.parseTypeReference(e),a=n.resolveTypeOrThrow({type:typeof e!="string"?e.type:e,file:r}),u=typeof e!="string"?e.property:void 0;return u!=null?A3.json(N6t.nestedPropertyAsResponse({docs:t,responseBodyType:i,responseProperty:await MPi({typeResolver:n,file:r,resolvedType:a,property:u})})):A3.json(N6t.response({docs:t,responseBodyType:i}))}async function yrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return PCe.cursor({page:await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.cursor}),next:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.next_cursor}),results:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results})})}async function vrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return PCe.offset({page:await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.offset}),results:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results}),step:i.step!=null?await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.step}):void 0,hasNextPage:i.hasNextPage!=null?await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.hasNextPage}):void 0})}function brd(e){return mqw(e)?{type:"offset",offset:HIt(e.offset),results:dMr(e.results),step:e.step!=null?HIt(e.step):void 0,hasNextPage:e["has-next-page"]!=null?dMr(e["has-next-page"]):void 0}:{type:"cursor",cursor:HIt(e.cursor),next_cursor:dMr(e.next_cursor),results:dMr(e.results)}}function mqw(e){return e.offset!=null&&e.results!=null}async function grd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n}){let i=typeof n.pagination=="boolean"?t.rootApiFile.pagination:n.pagination;if(!i)return;let a=brd(i);switch(a.type){case"cursor":return await yrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});case"offset":return vrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});default:Lc(a)}}function mrd({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let n=typeof r=="string"?r:r.error,i=uRr({errorName:n,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:i}})}function ATa({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function Ord({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:ATa({source:e}),name:sRr.generateName(r)}}async function Prd({file:e,serviceDeclaration:t,sourceResolver:r}){if(t.source==null)return gCe.http();let n=await r.resolveSourceOrThrow({source:t.source,file:e});if(n==null||n.type!=="protobuf")return gCe.http();let i=Ord({source:n,serviceNameOverride:t.transport?.grpc?.["service-name"]});if(i==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return gCe.grpc({service:i})}async function wrd({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:n,errorResolver:i,typeResolver:a,propertyResolver:u,exampleResolver:f,variableResolver:d,sourceResolver:c,globalErrors:o,workspace:l}){let g=await A8n({pathParameters:r["path-parameters"],location:mCe.Service,file:n,variableResolver:d}),O=await Prd({file:n,serviceDeclaration:r,sourceResolver:c}),P={fernFilepath:n.fernFilepath};return{availability:Dae(r.availability),name:P,displayName:r["display-name"]??void 0,basePath:R2e(r["base-path"]),headers:r.headers!=null?await Promise.all(Object.entries(r.headers).map(([M,q])=>L2e({headerKey:M,header:q,file:n}))):[],pathParameters:g,encoding:jqw(O),transport:O,endpoints:await Promise.all(Object.entries(r.endpoints).map(async([M,q])=>{let B=await A8n({pathParameters:q["path-parameters"],location:mCe.Endpoint,file:n,variableResolver:d}),I={...await Z$(q),id:"",name:n.casingsGenerator.generateName(M),displayName:q["display-name"],auth:q.auth??r.auth,idempotent:q.idempotent??r.idempotent??!1,baseUrl:q.url??r.url??e,method:q.method!=null?wqw(q.method):zie.Post,basePath:q["base-path"]!=null?R2e(q["base-path"]):void 0,path:R2e(q.path),fullPath:R2e(q["base-path"]!=null?k1(q["base-path"],q.path):n.rootApiFile["base-path"]!=null?k1(n.rootApiFile["base-path"],r["base-path"],q.path):k1(r["base-path"],q.path)),pathParameters:B,allPathParameters:q["base-path"]!=null?B:[...t,...g,...B],queryParameters:typeof q.request!="string"&&q.request?.["query-parameters"]!=null?await Promise.all(Object.entries(q.request["query-parameters"]).map(async([C,F])=>await ETa({file:n,queryParameterKey:C,queryParameter:F}))):[],headers:typeof q.request!="string"&&q.request?.headers!=null?await Promise.all(Object.entries(q.request.headers).map(([C,F])=>L2e({headerKey:C,header:F,file:n}))):[],requestBody:Ntd({request:q.request,file:n}),sdkRequest:await Utd({service:r,request:q.request,endpoint:q,endpointKey:M,file:n,typeResolver:a,propertyResolver:u}),response:await hrd({endpoint:q,file:n,typeResolver:a}),errors:[...mrd({errors:q.errors,file:n}),...o],userSpecifiedExamples:q.examples!=null?q.examples.map(C=>({example:_rd({service:r,endpoint:q,example:C,typeResolver:a,errorResolver:i,exampleResolver:f,variableResolver:d,file:n,workspace:l}),codeSamples:C["code-samples"]?.map(F=>Wtd({codeSample:F,file:n}))})):[],autogeneratedExamples:[],pagination:await grd({propertyResolver:u,file:n,endpointName:M,endpointSchema:q})};return I.id=s1.generateEndpointId(P,I),I}))}}async function A8n({pathParameters:e,location:t,file:r,variableResolver:n}){return e==null?[]:await Promise.all(Object.entries(e).map(([i,a])=>Oqw({parameterName:i,parameter:a,location:t,file:r,variableResolver:n})))}async function Oqw({parameterName:e,parameter:t,location:r,file:n,variableResolver:i}){return{...await Z$(t),name:n.casingsGenerator.generateName(e),valueType:Pqw({parameter:t,variableResolver:i,file:n}),location:r,variable:bIn(t)?i.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function Pqw({parameter:e,variableResolver:t,file:r}){let n=IPi({parameter:e,variableResolver:t,file:r});return n.file.parseTypeReference(n.rawType)}function IPi({parameter:e,variableResolver:t,file:r}){let n=MTa({parameter:e,variableResolver:t,file:r});if(n==null)throw new Error("Cannot resolve path parameter");return n}function MTa({parameter:e,variableResolver:t,file:r}){if(bIn(e)){let n=typeof e=="string"?e:e.variable,i=t.getDeclaration(n,r);return i==null?void 0:{rawType:typeof i.declaration=="string"?i.declaration:i.declaration.type,file:i.file}}else return{file:r,rawType:typeof e=="string"?e:e.type}}function wqw(e){switch(e){case"GET":return zie.Get;case"POST":return zie.Post;case"PUT":return zie.Put;case"PATCH":return zie.Patch;case"DELETE":return zie.Delete;default:Lc(e)}}async function L2e({headerKey:e,header:t,file:r}){let{name:n}=sLt({headerKey:e,header:t});return{...await Z$(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:n}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function sLt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function jqw(e){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Lc(e)}}var k$={};kc(k$,{validateObjectExample:()=>j8n,validateTypeExample:()=>DTa,validateTypeReferenceExample:()=>iQ});function jrd(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function xTa({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}async function Drd({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:s1.generateEndpointIdFromResolvedEndpoint(i),serviceId:s1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:xTa({fernFilePath:i.file.fernFilepath})?void 0:s1.generateSubpackageId(i.file.fernFilepath)},requestProperties:{refreshToken:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.refresh_token})},responseProperties:{accessToken:await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.access_token}),expiresIn:n.responseProperties.expires_in!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.expires_in}):void 0,refreshToken:n.responseProperties.refresh_token!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.refresh_token}):void 0}}}async function Srd({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:s1.generateEndpointIdFromResolvedEndpoint(i),serviceId:s1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:xTa({fernFilePath:i.file.fernFilepath})?void 0:s1.generateSubpackageId(i.file.fernFilepath)},requestProperties:{clientId:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.client_id}),clientSecret:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.client_secret}),scopes:n.requestProperties.scopes!=null?await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.scopes}):void 0},responseProperties:{accessToken:await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.access_token}),expiresIn:n.responseProperties.expires_in!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.expires_in}):void 0,refreshToken:n.responseProperties.refresh_token!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.refresh_token}):void 0}}}async function Erd({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:n,tokenEndpoint:i,refreshTokenEndpoint:a}){let u=await Srd({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:i});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let f=a!=null?await Drd({propertyResolver:e,endpointResolver:t,file:r,refreshTokenEndpoint:a}):void 0;return{clientIdEnvVar:n["client-id-env"],clientSecretEnvVar:n["client-secret-env"],tokenPrefix:n["token-prefix"],scopes:n.scopes,tokenEndpoint:u,refreshEndpoint:f}}var BPi={requestProperties:{type:"access_token",client_id:["client_id"],client_secret:["client_secret"],scopes:void 0},responseProperties:{type:"access_token",access_token:["access_token"],expires_in:void 0,refresh_token:void 0}},Cqu={requestProperties:{type:"refresh_token",refresh_token:["refresh_token"]},responseProperties:{type:"access_token",access_token:["access_token"],refresh_token:void 0,expires_in:void 0}};function Ard(e){return{endpoint:e["get-token"].endpoint,requestProperties:Dqw({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:Sqw({responseProperties:e["get-token"]?.["response-properties"]})}}function Mrd(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:Eqw({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:Aqw({responseProperties:e["refresh-token"]?.["response-properties"]})}}function Dqw({requestProperties:e}){if(e==null)return BPi.requestProperties;let t=e["client-id"],r=e["client-secret"],n=e.scopes;return{type:"access_token",client_id:t!=null?HIt(t):BPi.requestProperties.client_id,client_secret:r!=null?HIt(r):BPi.requestProperties.client_secret,scopes:n!=null?HIt(n):BPi.requestProperties.scopes}}function Sqw({responseProperties:e}){return xrd({responseProperties:e,defaultValue:BPi.responseProperties})}function Eqw({requestProperties:e}){if(e==null)return Cqu.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?HIt(t):Cqu.requestProperties.refresh_token}}function Aqw({responseProperties:e}){return xrd({responseProperties:e,defaultValue:Cqu.responseProperties})}function xrd({responseProperties:e,defaultValue:t}){if(e==null)return t;let r=e["access-token"],n=e["expires-in"],i=e["refresh-token"];return{type:"access_token",access_token:r!=null?dMr(r):t.access_token,expires_in:n!=null?dMr(n):t.expires_in,refresh_token:i!=null?dMr(i):t.refresh_token}}async function Brd({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:n}){if(e.auth==null)return{docs:void 0,requirement:SNr.All,schemes:[]};let i=typeof e.auth!="string"?e.auth.docs:void 0;return lyi(e.auth,{single:async a=>{let u=await Trd({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n});return{docs:i,requirement:SNr.All,schemes:[u]}},any:async({any:a})=>({docs:i,requirement:SNr.Any,schemes:await Promise.all(a.map(async u=>await Trd({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n})))})})}async function Trd({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:n,endpointResolver:i}){let a=(f,d)=>{let c=t?.[f];if(c==null)throw new Error("Unknown auth scheme: "+f);return hsu(c,{header:async o=>AH.header({docs:d,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??f,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:async o=>qrd({file:r,docs:d,rawScheme:o}),bearer:async o=>Crd({file:r,docs:d,rawScheme:o}),oauth:async o=>await Ird({file:r,docs:d,rawScheme:o,propertyResolver:n,endpointResolver:i})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return Crd({file:r,docs:void 0,rawScheme:void 0});case"basic":return qrd({file:r,docs:void 0,rawScheme:void 0});case"oauth":return await Ird({file:r,docs:void 0,rawScheme:void 0,propertyResolver:n,endpointResolver:i});default:return a(u,typeof e!="string"?e.docs:void 0)}}function Crd({file:e,docs:t,rawScheme:r}){return AH.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function qrd({file:e,docs:t,rawScheme:r}){return AH.basic({docs:t,username:e.casingsGenerator.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.casingsGenerator.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}async function Ird({file:e,docs:t,rawScheme:r,propertyResolver:n,endpointResolver:i}){switch(r?.type){case"client-credentials":return AH.oauth({docs:t,configuration:ENr.clientCredentials(await Erd({propertyResolver:n,endpointResolver:i,file:e,oauthScheme:r,tokenEndpoint:Ard(r),refreshTokenEndpoint:Mrd(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}async function Nrd({file:e,rawApiFileSchema:t}){if(t.version!=null)return MNr.header({header:await Mqw({file:e,header:t.version.header}),value:await xqw({file:e,versionDeclaration:t.version})})}async function Mqw({file:e,header:t}){return typeof t=="string"?await L2e({file:e,headerKey:t,header:{type:"string"}}):await L2e({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}async function xqw({file:e,versionDeclaration:t}){return await STa({_enum:{default:t.default,enum:t.values},file:e})}async function zrd({channel:e,typeResolver:t,exampleResolver:r,variableResolver:n,file:i,workspace:a}){let u=[];for(let[f,d]of Object.entries(e.messages??{}))u.push({type:f,availability:Dae(d.availability),docs:d.docs,origin:d.origin,body:qqw({body:d.body,file:i}),displayName:d["display-name"]});return{availability:Dae(e.availability),path:R2e(e.path),auth:e.auth,name:i.fernFilepath.file??i.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?await Promise.all(Object.entries(e.headers).map(([f,d])=>L2e({headerKey:f,header:d,file:i}))):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?await A8n({pathParameters:e["path-parameters"],location:mCe.Endpoint,file:i,variableResolver:n}):[],queryParameters:e["query-parameters"]!=null?await Promise.all(Object.entries(e["query-parameters"]).map(async([f,d])=>{let{name:c}=_Mr({queryParameterKey:f,queryParameter:d}),o=i.parseTypeReference(d);return{...await Z$(d),name:i.casingsGenerator.generateNameAndWireValue({wireValue:f,name:c}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1}})):[],messages:Object.values(u),examples:(e.examples??[]).map(f=>{let d=Bqw({channel:e,example:f,typeResolver:t,exampleResolver:r,variableResolver:n,file:i,workspace:a});return{name:f.name!=null?i.casingsGenerator.generateName(f.name):void 0,docs:f.docs,url:zqw({channel:e,example:f,pathParams:d}),...d,...Nqw({channel:e,example:f,typeResolver:t,exampleResolver:r,file:i,workspace:a}),queryParameters:f["query-parameters"]!=null?Object.entries(f["query-parameters"]).map(([c,o])=>{let l=e["query-parameters"]?.[c];if(l==null)throw new Error(`Query parameter ${c} does not exist`);return{name:i.casingsGenerator.generateNameAndWireValue({name:_Mr({queryParameterKey:c,queryParameter:l}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),shape:Tqw({queryParameter:l})}}):[],messages:f.messages.map(c=>{let o=e.messages?.[c.type];if(o==null)throw new Error(`Message ${c.type} does not exist`);return{type:c.type,body:Cqw({message:o,example:c.body,typeResolver:t,exampleResolver:r,file:i,workspace:a})}})}})}}function Tqw({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?NF.exploded():NF.single()}function Cqw({message:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){if(!Rqw(e.body))return F6t.reference(lT({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}));if(!lS(t))throw new Error("Example must be an object");let u=[];for(let[f,d]of Object.entries(t)){let c=e.body.properties?.[f];if(c!=null)u.push({name:i.casingsGenerator.generateNameAndWireValue({name:nQ({propertyKey:f,property:c}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof c!="string"?c.type:c,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),originalTypeDeclaration:void 0});else{let o=qPi({extends_:e.body.extends,wirePropertyKey:f,typeResolver:r,file:i});if(o==null)throw new Error("Could not find original type declaration for property: "+f);u.push({name:i.casingsGenerator.generateNameAndWireValue({name:nQ({propertyKey:f,property:o.rawPropertyType}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof o.rawPropertyType=="string"?o.rawPropertyType:o.rawPropertyType.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:o.file,fileContainingExample:i,workspace:a}),originalTypeDeclaration:o.typeName})}}return F6t.inlinedBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t,file:i}).resolvedExample,properties:u})}function qqw({body:e,file:t}){return typeof e=="string"?jCe.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):Iqw(e)?jCe.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):jCe.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:WIt(e.extends??[]).map(r=>CU({typeName:r,file:t})),properties:[]})}function Iqw(e){return e.type!=null}function Bqw({channel:e,example:t,typeResolver:r,exampleResolver:n,variableResolver:i,file:a,workspace:u}){let f=[],d=({name:c,pathParameterDeclaration:o,examplePathParameter:l})=>{let g=IPi({parameter:o,variableResolver:i,file:a});return{name:c,value:lT({example:l,rawTypeBeingExemplified:g.rawType,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:g.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null)for(let[c,o]of Object.entries(t["path-parameters"])){let l=e["path-parameters"]?.[c];if(l!=null)f.push(d({name:a.casingsGenerator.generateName(c),pathParameterDeclaration:l,examplePathParameter:o}));else throw new Error(`Path parameter ${c} does not exist`)}return{pathParameters:f}}function Nqw({channel:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=[];if(t.headers!=null)for(let[f,d]of Object.entries(t.headers)){let c=e.headers?.[f];if(c!=null)u.push({name:i.casingsGenerator.generateNameAndWireValue({name:sLt({headerKey:f,header:c}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a})});else throw new Error(`Heder ${f} does not exist`)}return{headers:u}}function zqw({channel:e,example:t,pathParams:r}){let n=e.path;if(t["path-parameters"]!=null)for(let i of[...r.pathParameters])n=n.replaceAll(`{${i.name.originalName}}`,`${i.value.jsonExample}`);return n}function Rqw(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function qqu({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let n=Object.values(t)[0];if(n!=null)return{defaultEnvironment:e??void 0,environments:zEr(n,{singleBaseUrl:()=>q6t.singleBaseUrl(Fqw({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>q6t.multipleBaseUrls(Lqw({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})}}function Fqw({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>zEr(n,{singleBaseUrl:i=>({docs:typeof i=="string"?void 0:i.docs,id:r,name:t.generateName(r),url:Rrd(typeof i=="string"?i:i.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function Lqw({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>zEr(i,{multipleBaseUrls:a=>({docs:a.docs,id:n,name:r.generateName(n),urls:by(a.urls,u=>Rrd(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function Rrd(e){return e.endsWith("/")?e.slice(0,-1):e}function Frd({errorName:e,errorDeclaration:t,file:r,typeResolver:n,exampleResolver:i,workspace:a}){let u=[];if(t.type!=null&&t.examples!=null)for(let f of t.examples)u.push({name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,docs:f.docs,jsonExample:i.resolveAllReferencesInExampleOrThrow({example:f.value,file:r}).resolvedExample,shape:lT({example:f.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})});return{name:uRr({errorName:e,file:r}),discriminantValue:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:e}),docs:typeof t!="string"?t.docs:void 0,statusCode:t["status-code"],type:t.type!=null?r.parseTypeReference(t.type):void 0,examples:u}}var Lrd="content";function Urd(e,t){if(e==null||e.strategy==="status-code")return z6t.statusCode();switch(e.strategy){case"property":return z6t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:Lrd,wireValue:Lrd})});default:Lc(e)}}function Vrd({readme:e,services:t}){let r=new Iqu(t);return{apiReferenceLink:e.apiReferenceLink,bannerLink:e.bannerLink,introduction:e.introduction,defaultEndpoint:e.defaultEndpoint!=null?r.getEndpointForReadmeOrThrow(e.defaultEndpoint).id:void 0,features:e.features!=null?Object.fromEntries(Object.entries(e.features).map(([n,i])=>[n,i.map(a=>r.getEndpointForReadmeOrThrow(a).id)])):void 0}}var Iqu=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=Vqw({endpoint:t}),n=this.getEndpointKeyForReadmeEndpoint(r);return this.endpoints[n]}getEndpointForReadmeOrThrow(t){let r=this.getEndpointForReadme(t);if(r==null)throw new Error(`Endpoint not found for ${JSON.stringify(t)}`);return r}buildEndpoints(t){let r={};for(let n of Object.values(t))for(let i of n.endpoints)r[this.getEndpointKeyForHttpEndpoint(i)]=i;return r}getEndpointKeyForReadmeEndpoint(t){return this.getEndpointKey({method:t.method,path:t.path,stream:t.stream??!1})}getEndpointKeyForHttpEndpoint(t){return this.getEndpointKey({method:t.method,path:Uqw(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:n}){return`${t}|${r}|${n}`}};function Uqw(e){let t="";e.fullPath.head.length>0&&(t=k1(t,e.fullPath.head));for(let r of e.fullPath.parts)t=k1(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=k1(t,r.tail));return t.startsWith("/")?t:`/${t}`}function Vqw({endpoint:e}){if(typeof e=="string"){let t=e.split(" ");if(t.length!==2||t[0]==null||t[1]==null)throw new Error(`invalid endpoint string: ${e}`);return{method:t[0],path:t[1]}}return e}async function Wrd({webhooks:e,file:t,typeResolver:r,exampleResolver:n,workspace:i}){let a=[];for(let[u,f]of Object.entries(e))a.push({id:s1.generateWebhookId(t.fernFilepath,u),availability:Dae(f.availability),displayName:f["display-name"],docs:f.docs,method:f.method,name:t.casingsGenerator.generateName(u),headers:f.headers!=null?await Promise.all(Object.entries(f.headers).map(([d,c])=>L2e({headerKey:d,header:c,file:t}))):[],payload:Wqw({payload:f.payload,file:t}),examples:f.examples!=null?Qqw({webhook:f,examples:f.examples,file:t,typeResolver:r,exampleResolver:n,workspace:i}):void 0});return a}function Wqw({payload:e,file:t}){return typeof e=="string"?Hie.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):TTa(e)?Hie.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):Hie.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:WIt(e.extends).map(r=>CU({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,n])=>Hqw({propertyKey:r,propertyDefinition:n,docs:typeof n!="string"?n.docs:void 0,availability:typeof n!="string"?Dae(n.availability):void 0,file:t})):[]})}function Hqw({propertyKey:e,propertyDefinition:t,docs:r,availability:n,file:i}){return{docs:r,availability:n,name:i.casingsGenerator.generateNameAndWireValue({wireValue:e,name:nQ({propertyKey:e,property:t}).name}),valueType:i.parseTypeReference(t)}}function Qqw({webhook:e,examples:t,file:r,typeResolver:n,exampleResolver:i,workspace:a}){let u=typeof e.payload=="string"?e.payload:TTa(e.payload)?e.payload.type:void 0;if(u!=null)return t.map(f=>({docs:e.docs,name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,payload:lT({example:f.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}));if(!lS(e.payload))throw new Error(`Example webhook payload is not an object. Got: ${JSON.stringify(e.payload)}`);return t.map(f=>({docs:e.docs,name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,payload:lT({example:f.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}))}function TTa(e){return e.type!=null}function M8n(e){let t={};for(let[r,n]of Object.entries(e))if(typeof n!="string")for(let i of n.audiences??[])t[i]==null&&(t[i]=new Set),t[i]?.add(r);return t}function Hrd({name:e,source:t}){return wD.userDefined({file:ATa({source:t}),name:sRr.generateName(e)})}function Qrd({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=Jqw({type:e.proto.type});if(t!=null)return t}}function Jqw({type:e}){switch(e){case"google.protobuf.Any":return wD.wellKnown(uh.any());case"google.protobuf.Api":return wD.wellKnown(uh.api());case"google.protobuf.BoolValue":return wD.wellKnown(uh.boolValue());case"google.protobuf.BytesValue":return wD.wellKnown(uh.bytesValue());case"google.protobuf.DoubleValue":return wD.wellKnown(uh.doubleValue());case"google.protobuf.Duration":return wD.wellKnown(uh.duration());case"google.protobuf.Empty":return wD.wellKnown(uh.empty());case"google.protobuf.Enum":return wD.wellKnown(uh.enum());case"google.protobuf.EnumValue":return wD.wellKnown(uh.enumValue());case"google.protobuf.Field":return wD.wellKnown(uh.field());case"google.protobuf.FieldCardinality":return wD.wellKnown(uh.fieldCardinality());case"google.protobuf.FieldKind":return wD.wellKnown(uh.fieldKind());case"google.protobuf.FieldMask":return wD.wellKnown(uh.fieldMask());case"google.protobuf.FloatVlaue":return wD.wellKnown(uh.floatValue());case"google.protobuf.Int32Value":return wD.wellKnown(uh.int32Value());case"google.protobuf.Int64Value":return wD.wellKnown(uh.int64Value());case"google.protobuf.ListValue":return wD.wellKnown(uh.listValue());case"google.protobuf.Method":return wD.wellKnown(uh.method());case"google.protobuf.Mixin":return wD.wellKnown(uh.mixin());case"google.protobuf.NullValue":return wD.wellKnown(uh.nullValue());case"google.protobuf.Option":return wD.wellKnown(uh.option());case"google.protobuf.SourceContext":return wD.wellKnown(uh.sourceContext());case"google.protobuf.StringValue":return wD.wellKnown(uh.stringValue());case"google.protobuf.Struct":return wD.wellKnown(uh.struct());case"google.protobuf.Syntax":return wD.wellKnown(uh.syntax());case"google.protobuf.Timestamp":return wD.wellKnown(uh.timestamp());case"google.protobuf.Type":return wD.wellKnown(uh.type());case"google.protobuf.Uint32Value":return wD.wellKnown(uh.uint32Value());case"google.protobuf.Uint64Value":return wD.wellKnown(uh.uint64Value());case"google.protobuf.Value":return wD.wellKnown(uh.value())}}async function Jrd({generic:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type,i=E3(n);if(i==null)throw new Error(`Invalid generic type definition: ${n}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:n,file:t});if(i.arguments&&mA(a.declaration)){let u=E3(a.typeName)?.arguments??[],f=Object.entries(a.declaration.properties??{}).map(([d,c])=>{let o=c;return typeof c=="string"&&u?.includes(c)&&(o=i.arguments?.[u.indexOf(c)]??c),[d,o]});return Sq.object({extends:WIt(a.declaration.extends).map(d=>CU({typeName:d,file:t})),properties:await APi({properties:Object.fromEntries(f)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${n}`)}async function Grd({alias:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type;return bCe(n)?await Jrd({generic:n,file:t,typeResolver:r}):Sq.alias({aliasOf:t.parseTypeReference(e),resolvedType:Gqw({aliasOf:n,file:t,typeResolver:r})})}function Gqw({aliasOf:e,file:t,typeResolver:r}){let n=r.resolveTypeOrThrow({type:e,file:t});switch(n._type){case"primitive":return MH.primitive(n.originalTypeReference.primitive);case"container":return MH.container(n.originalTypeReference.container);case"unknown":return MH.unknown();case"named":{let i=mA(n.declaration)?R6t.Object:UNr(n.declaration)?R6t.Union:V6t(n.declaration)?R6t.Enum:mIn(n.declaration)?R6t.UndiscriminatedUnion:Lc(n.declaration);return MH.named({name:n.name,shape:i})}}}function $rd({union:e,file:t}){return Sq.undiscriminatedUnion({members:e.union.map(r=>typeof r=="string"?{docs:void 0,type:t.parseTypeReference(r)}:{type:t.parseTypeReference(r),docs:r.docs})})}function Krd(e){let t=[];if(e.extends!=null){let r=typeof e.extends=="string"?[e.extends]:e.extends;t.push(...r)}return e.properties!=null&&t.push(...Object.values(e.properties).map(r=>typeof r=="string"?r:r.type)),t}function Nqu({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:n=new Bqu}){let i=zz(e,{alias:u=>{let f=typeof u=="string"?u:u.type,d=E3(f);if(d!=null){let c=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t}),l=E3(o.typeName)?.arguments;if(mA(o.declaration)){let g=Krd(o.declaration);l&&g.filter(O=>!l.includes(O)).forEach(O=>c.add(O))}return Array.from(c)}return[f]},object:u=>Krd(u),discriminatedUnion:u=>{let f=[];return u["base-properties"]!=null&&f.push(...Object.values(u["base-properties"]).map(d=>typeof d=="string"?d:d.type)),f.push(...Object.values(u.union).reduce((d,c)=>{let o=typeof c=="string"?c:c.type;return typeof o=="string"&&d.push(o),d},[])),f},undiscriminatedUnion:u=>Object.values(u.union).reduce((f,d)=>{let c=typeof d=="string"?d:d.type;return typeof c=="string"&&f.push(c),f},[]),enum:()=>[]}),a=[];for(let u of i){let f=P$({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:d,valueType:c})=>[...d,...c],list:d=>d,optional:d=>d,set:d=>d,named:d=>[d],literal:()=>[],unknown:()=>[]}});for(let d of f){let c=CU({typeName:d,file:t});if(!n.hasTypeNameBeenSeen(c)){n.addTypeName(c),a.push(c);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(bCe(o.typeName))continue;a.push(...Nqu({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:n}))}}}return a}var Bqu=class{cache=new Set;addTypeName(t){this.cache.add(this.computeCacheKey(t))}hasTypeNameBeenSeen(t){return this.cache.has(this.computeCacheKey(t))}computeCacheKey(t){return t.fernFilepath.allParts.map(r=>r.originalName).join("/")+":"+t.name.originalName}};async function Yrd({typeName:e,typeDeclaration:t,file:r,typeResolver:n,exampleResolver:i,sourceResolver:a,workspace:u}){let f=await Z$(t),d=CU({typeName:e,file:r}),c=Nqu({typeDeclaration:t,file:r,typeResolver:n}),o={};mA(t)&&(o=M8n(t.properties??{}));let l=await Kqw({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...f,inline:!1,name:d,shape:await $qw({typeDeclaration:t,file:r,typeResolver:n}),referencedTypes:new Set(c.map(g=>g.typeId)),encoding:Yqw({typeDeclaration:t,source:l}),source:l,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(g=>({name:g.name!=null?r.casingsGenerator.generateName(g.name):void 0,docs:g.docs,jsonExample:i.resolveAllReferencesInExampleOrThrow({example:g.value,file:r}).resolvedExample,shape:Tqu({typeName:d,example:g.value,typeResolver:n,exampleResolver:i,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(c.map(g=>g.fernFilepath))}}async function $qw({typeDeclaration:e,file:t,typeResolver:r}){return await zz(e,{alias:n=>Grd({alias:n,file:t,typeResolver:r}),object:n=>Itd({object:n,file:t}),discriminatedUnion:n=>Ytd({union:n,file:t,typeResolver:r}),undiscriminatedUnion:n=>$rd({union:n,file:t}),enum:async n=>Sq.enum(await STa({_enum:n,file:t}))})}async function Kqw({file:e,typeDeclaration:t,typeName:r,sourceResolver:n}){if(typeof t=="string"||t.source==null&&t.encoding==null)return;if(t.encoding!=null){let a=Qrd({encoding:t.encoding});if(a!=null)return BEr.proto(a)}if(t.source==null)return;let i=await n.resolveSourceOrThrow({source:t.source,file:e});if(!(i==null||i.type!=="protobuf"))return BEr.proto(Hrd({source:i,name:r}))}function Yqw({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?Xqw(e.encoding):Zqw(t)}function Xqw(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function Zqw(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function Xrd(e,t){let r=t[e];if(r==null)throw new GSr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function Zrd(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,e6w({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(n=>kqw({endpoint:n,ir:e}))}]))}}function kqw({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>krd(r,t))}}}function e6w({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>krd(r,t))}}}return e}function krd(e,t){let r=zqu(e.typeId,t);return end({objectTypeDeclaration:r,ir:t})}function zqu(e,t){let r=Xrd(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return zqu(r.shape.resolvedType.name.typeId,t)}throw new GSr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function end({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(n=>{let i=zqu(n.typeId,t);return end({objectTypeDeclaration:i,ir:t})});return[...e.properties,...r]}var CTa=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;subpackages=new Set;constructor({types:t,properties:r,errors:n,environments:i,services:a,endpoints:u,webhooks:f,subpackages:d,queryParameters:c,requestProperties:o,webhookPayloadProperties:l}){this.environments=i,this.types=t,this.properties=r,this.errors=n,this.services=a,this.endpoints=u,this.webhooks=f,this.webhookPayloadProperties=l,this.subpackages=d,this.requestProperties=o,this.queryParameters=c}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=s1.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let n=this.properties[t];return n==null?!0:n.has(r)}hasError(t){let r=s1.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=s1.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let n=this.requestProperties[t];return n==null?!0:n.has(r)}hasQueryParameter(t,r){let n=this.queryParameters[t];return n==null?!0:n.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasWebhookPayloadProperty(t,r){let n=this.webhookPayloadProperties[t];return n==null?!0:n.has(r)}};var qTa=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=t6w(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:a}){let u=s1.generateTypeId(t),f={typeId:u,allDescendants:r,descendantsByAudience:i,referencedSubpackages:n};this.types[u]=f,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let n=s1.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath),this.types[n]?.referencedSubpackages.forEach(i=>{this.addSubpackages(i)}))}markEnvironmentForAudiences(t,r,n){t&&(this.hasAudience(r)||n)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){return this.typesReferencedByService}addError(t){let r=s1.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&G5(t.type,n,i);let a={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=a}addEndpoint(t,r,n){let i=s1.generateServiceId(t.name),a=r.id,u=new Set,f=new Set,d=new Set;for(let c of[...t.headers,...r.headers])G5(c.valueType,u,d);for(let c of[...t.pathParameters,...r.pathParameters])G5(c.valueType,u,d);for(let c of r.queryParameters)G5(c.valueType,u,d);if(n!=null&&n.request!=null&&typeof n.request!="string"){let c=M8n(n.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:c}}r.requestBody!=null&&T5._visit(r.requestBody,{inlinedRequestBody:c=>{for(let o of c.extends)Rqu(o,u,d);for(let o of c.properties)G5(o.valueType,u,d);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&v6(n.request.body)){let o=M8n(n.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:c})=>{G5(c,u,d)},fileUpload:({properties:c})=>{for(let o of c)Rie._visit(o,{file:cl,bodyProperty:({valueType:l})=>{G5(l,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&A3._visit(r.response.body,{fileDownload:cl,json:c=>{G5(c.responseBodyType,u,d)},streaming:c=>{c._visit({sse:o=>G5(o.payload,u,d),json:o=>G5(o.payload,u,d),text:cl,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.type)}})},streamParameter:c=>{c.streamResponse._visit({sse:o=>G5(o.payload,u,d),json:o=>G5(o.payload,u,d),text:cl,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.streamResponse.type)}}),c.nonStreamResponse.type==="json"&&G5(c.nonStreamResponse.value.responseBodyType,u,d)},text:cl,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(c=>{f.add(s1.generateErrorId(c.error)),d.add(c.error.fernFilepath)});for(let c of u)this.markTypeForService(c,i);this.endpoints[a]={endpointId:a,referencedTypes:u,referencedErrors:f,referencedSubpackages:d}}markEndpointForAudience(t,r,n){if(this.hasAudience(n)){let i=s1.generateServiceId(t);this.servicesNeededForAudience.add(i),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(f=>{this.addSubpackages(f)})}),this.servicesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath)}}addWebhook(t,r,n){let i=r.id;if(i==null)return;let a=new Set,u=new Set;r.payload!=null&&Hie._visit(r.payload,{inlinedPayload:f=>{for(let d of f.extends)Rqu(d,a,u);for(let d of f.properties)G5(d.valueType,a,u);if(n?.payload!=null&&typeof n.payload=="object"&&!TTa(n.payload)){let d=M8n(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:d}}},reference:({payloadType:f})=>{G5(f,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t.fernFilepath),this.webhooks[i]={webhookId:i,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,n){let i=r.id;i!=null&&this.hasAudience(n)&&(this.webhooksNeededForAudience.add(i),this.addSubpackages(t.fernFilepath))}build(){let t=new Set,r=new Set;for(let f of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(f);for(let c of d.referencedErrors){if(r.has(c))continue;r.add(c);let o=this.getErrorNode(c);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let f of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(f);this.addReferencedTypes(t,d.referencedTypes)}let n={},i={},a={},u={};if(this.audiences.type==="filtered"){for(let[f,d]of Object.entries(this.properties)){if(!t.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}c.size>0&&(n[f]=c),n[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}i[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.parametersByAudience[o];l?.forEach(g=>{c.add(g)})}a[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}u[f]=c.size>0?c:void 0}}return new CTa({types:t,properties:n,errors:r,requestProperties:i,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience})}markTypeForService(t,r){let n=this.typesReferencedByService[t];n==null?this.typesReferencedByService[t]=new Set(r):n.add(r)}addReferencedTypes(t,r){for(let n of r){if(t.has(n))continue;t.add(n);let i=this.getTypeNode(n);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=i.descendantsByAudience[a];if(u!=null)u.forEach(f=>{t.add(f)});else{i.allDescendants.forEach(f=>{t.add(f)});break}}else i.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(n=>r.audiences.has(n));default:Lc(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(s1.generateSubpackageId(n))}}};function t6w(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Lc(e)}}function G5(e,t,r){uT._visit(e,{container:n=>{r6w(n,t,r)},named:n=>{Rqu(n,t,r)},primitive:cl,unknown:cl,_other:cl})}function Rqu(e,t,r){t.add(s1.generateTypeId(e)),r.add(e.fernFilepath)}function r6w(e,t,r){Eq._visit(e,{list:n=>{G5(n,t,r)},map:n=>{G5(n.keyType,t,r),G5(n.valueType,t,r)},optional:n=>{G5(n,t,r)},set:n=>{G5(n,t,r)},literal:cl,_other:cl})}function rnd({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let n=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:ON({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?Bz.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=ON({filteredIr:e,exampleTypeReference:r});return n!==void 0?Bz.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function ON({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:dO.container(gA.list({...n,list:n.list.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:dO.container(gA.set({...n,set:n.set.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?ON({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:dO.container(gA.optional({optional:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:dO.container(gA.map({...n,map:n.map.map(i=>{let a=ON({filteredIr:e,exampleTypeReference:i.key}),u=ON({filteredIr:e,exampleTypeReference:i.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(i=>i!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:n=>{let i=ON({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:dO.named({...r,shape:dS.enum(n)})}),object:n=>({...t,shape:dO.named({...r,shape:dS.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:ON({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=rnd({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=ON({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Fqu({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function n6w({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function tnd({filteredIr:e,headers:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function i6w({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(n=>n.originalTypeDeclaration?e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue):!0).map(n=>{let i=ON({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=ON({filteredIr:e,exampleTypeReference:r});return n!==void 0?b$.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function a6w({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>T4.ok(cN.body(n!=null?ON({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>T4.ok(cN.stream(n.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter($M))),sse:n=>T4.ok(cN.sse(n.map(({event:i,data:a})=>{let u=ON({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:i,data:u}:void 0}).filter($M))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>T4.error({error:r,body:n!=null?ON({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function Lqu({filteredIr:e,example:t}){return{...t,rootPathParameters:Fqu({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Fqu({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Fqu({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:tnd({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:tnd({filteredIr:e,headers:t.endpointHeaders}),queryParameters:n6w({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?i6w({filteredIr:e,requestBody:t.request}):void 0,response:a6w({filteredIr:e,response:t.response})}}function nnd({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:dS.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:dS.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:ON({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=rnd({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:dS.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=ON({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:dS.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var ITa=class{subpackages={};rootPackage={docs:void 0,fernFilepath:{allParts:[],packagePath:[],file:void 0},websocket:void 0,service:void 0,types:[],errors:[],subpackages:[],webhooks:void 0,navigationConfig:void 0};addPackageRedirection({from:t,to:r}){let n=this.getPackageForFernFilepath(t);if(n.navigationConfig!=null)throw new Error("Found duplicate navigationConfig for package");n.navigationConfig={pointsTo:s1.generateSubpackageId(r)}}addDocs(t,r){let n=this.getPackageForFernFilepath(t);if(n.docs!=null)throw new Error("Found duplicate docs for package");n.docs=r}addSubpackage(t){this.getPackageForFernFilepath(t)}addType(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).types.push(t)}addError(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).errors.push(t)}addService(t,r){let n=this.getPackageForFernFilepath(r.name.fernFilepath);if(n.service!=null)throw new Error("Found duplicate service for "+t);n.service=t}addWebhookGroup(t,r){let n=this.getPackageForFernFilepath(r);if(n.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);n.webhooks=t}addWebSocketChannel(t,r){let n=this.getPackageForFernFilepath(r);if(n.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);n.websocket=t}build(t){t!=null&&(Object.entries(this.subpackages).forEach(([n,i])=>{t.hasSubpackageId(n)?this.subpackages[n]={...i,types:i.types.filter(a=>t.hasTypeId(a)),errors:i.errors.filter(a=>t.hasErrorId(a)),service:i.service!=null&&t.hasServiceId(i.service)?i.service:void 0,subpackages:i.subpackages.filter(a=>t.hasSubpackageId(a))}:delete this.subpackages[n]}),this.rootPackage={...this.rootPackage,types:this.rootPackage.types.filter(n=>t.hasTypeId(n)),errors:this.rootPackage.errors.filter(n=>t.hasErrorId(n)),service:this.rootPackage.service!=null&&t.hasServiceId(this.rootPackage.service)?this.rootPackage.service:void 0,subpackages:this.rootPackage.subpackages.filter(n=>t.hasSubpackageId(n)),webhooks:this.rootPackage.webhooks!=null?this.rootPackage.webhooks:void 0});let r=new Set(this.getAllChildrenWithEndpoints(this.rootPackage));return{subpackages:by(this.subpackages,(n,i)=>({...n,hasEndpointsInTree:r.has(i)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!ind(this.rootPackage.subpackages,t))throw new Error("Sorted subpackages differ from unsorted packages in root");this.rootPackage.subpackages=t}sortSubpackage(t,r){let n=this.subpackages[t];if(n==null)throw new Error("Subpackage does not exist: "+t);if(!ind(n.subpackages,r))throw new Error("Sorted subpackages differ from unsorted packages");n.subpackages=r}getAllSubpackagesWithEndpoints(t){let r=this.subpackages[t];if(r==null)throw new Error("Subpackage does not exist: "+t);let n=this.getAllChildrenWithEndpoints(r);return(n.length>0||r.service!=null)&&n.push(t),n}getAllChildrenWithEndpoints(t){return t.subpackages.flatMap(r=>[...this.getAllSubpackagesWithEndpoints(r)])}getPackageForFernFilepath(t,r=0,n=this.rootPackage){let i=t.allParts[r];if(i==null)return n;let a=n.subpackages.map(c=>{let o=this.subpackages[c];if(o==null)throw new Error("Subpackage ID is invalid: "+c);return o}),u=r+1,f={allParts:t.allParts.slice(0,u),packagePath:t.packagePath.slice(0,u),file:u===t.allParts.length?t.file:void 0},d=a.find(c=>c.name.originalName===i.originalName);if(d==null){let c=s1.generateSubpackageId(f),o={docs:void 0,fernFilepath:f,name:i,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[c]=o,n.subpackages.push(c),d=o}return this.getPackageForFernFilepath(t,u,d)}};function ind(e,t){if(e.length!==t.length)return!1;let r=new Set(e);for(let n of t)if(!r.has(n))return!1;return!0}function and({reference:e,referencedIn:t,imports:r}){let[n,i,...a]=e.split(".");if(n==null||a.length>0)return;if(i==null)return{endpointName:n,relativeFilepath:t};let f=r[n];if(f!=null)return{endpointName:i,relativeFilepath:oRr({referencedIn:t,importPath:f})}}var yan=class{workspace;constructor(t){this.workspace=t}async resolveEndpointOrThrow({endpoint:t,file:r}){let n=await this.resolveEndpoint({endpoint:t,file:r});if(n==null)throw new Error("Cannot resolve endpoint: "+t+" in file "+r.relativeFilepath);return n}async resolveEndpointByMethodAndPath({method:t,path:r}){let n;return await Jz(this.workspace,async(i,a,u)=>{let f=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:sRr,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[d,c]of Object.entries(a.service?.endpoints??{}))c.method===t&&c.path===r&&(n={endpointId:d,endpoint:c,file:f})}),await Enn(this.workspace,async(i,a)=>{let u=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:sRr,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[f,d]of Object.entries(a.service?.endpoints??{}))d.method===t&&d.path===r&&(n={endpointId:f,endpoint:d,file:u})}),n}async resolveEndpoint({endpoint:t,file:r}){let i=new fyi().tryParse(t);if(i!=null)return await this.resolveEndpointByMethodAndPath(i);let a=this.getDeclarationOfEndpoint({referenceToEndpoint:t,file:r});if(a==null)return;let u=a.file.definitionFile.service?.endpoints?.[a.endpointName];if(u!=null)return{endpointId:a.endpointName,endpoint:u,file:a.file}}getDeclarationOfEndpoint({referenceToEndpoint:t,file:r}){let n=and({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=cae(this.workspace,n.relativeFilepath);if(!(i==null||i.service?.endpoints?.[n.endpointName]==null))return{endpointName:n.endpointName,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var van=class{workspace;constructor(t){this.workspace=t}getDeclarationOrThrow(t,r){let n=this.getDeclaration(t,r);if(n==null)throw new Error("Error does not exist: "+t);return n}getDeclaration(t,r){let n=FDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=cae(this.workspace,n.relativeFilepath);if(i==null)return;let a=i.errors?.[n.typeName];if(a!=null)return{declaration:a,file:qO({definitionFile:i,relativeFilepath:n.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var UDe=class{typeResolver;constructor(t){this.typeResolver=t}resolveAllReferencesInExample({example:t,file:r}){if(typeof t=="string"){let n=this.resolveExample({example:t,file:r});return n==null||typeof n.resolvedExample=="string"?n:this.resolveAllReferencesInExample({example:n.resolvedExample,file:n.file})}else if(lS(t)){let n={};for(let[i,a]of Object.entries(t)){let u=this.resolveAllReferencesInExample({example:a,file:r});if(u==null)return;n[i]=u.resolvedExample}return{resolvedExample:n}}else if(Array.isArray(t)){let n=[];for(let i of t){let a=this.resolveAllReferencesInExample({example:i,file:r});if(a==null)return;n.push(a.resolvedExample)}return{resolvedExample:n}}return{resolvedExample:t}}resolveAllReferencesInExampleOrThrow({example:t,file:r}){let n=this.resolveAllReferencesInExample({example:t,file:r});if(n==null)throw new Error("Failed to resolve examples");return n}resolveExample({example:t,file:r}){if(typeof t!="string")return{resolvedExample:t,file:r};if(t.startsWith(`\\${uFt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(uFt))return{resolvedExample:t,file:r};let n=this.parseExampleReference(t);if(n==null)return;let i=this.typeResolver.getDeclarationOfNamedType({referenceToNamedType:n.rawTypeReference,file:r});if(i==null||typeof i.declaration=="string"||i.declaration.examples==null)return;let a=i.declaration.examples.find(u=>u.name===n.exampleName);if(a!=null)return this.resolveExample({example:a.value,file:i.file})}resolveExampleOrThrow({example:t,file:r}){let n=this.resolveExample({example:t,file:r});if(n==null)throw new Error("Cannot resolve example: "+t);return n}parseExampleReference(t){let[r,n,i,...a]=t.split(".");if(!(r==null||n==null||a.length>0))return i==null?{rawTypeReference:r.slice(uFt.length),exampleName:n}:{rawTypeReference:`${r}.${n}`.slice(uFt.length),exampleName:i}}};var BTa=class{typeResolver;endpointResolver;constructor(t,r){this.typeResolver=t,this.endpointResolver=r,this.typeResolver=t,this.endpointResolver=r}async resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n}){let i=await this.resolveRequestProperty({file:t,endpoint:r,propertyComponents:n});if(i==null)throw new Error("Cannot resolve request property from endpoint: "+r+" in file "+t.relativeFilepath);return i}async resolveRequestProperty({file:t,endpoint:r,propertyComponents:n}){let i=await this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t});if(i.endpoint.request==null)return;if(typeof i.endpoint.request!="string")return this.resolveRequestPropertyFromInlinedRequest({typeResolver:this.typeResolver,file:i.file,requestType:i.endpoint.request,propertyComponents:n});let a=await this.resolveObjectProperty({file:i.file,typeName:i.endpoint.request,propertyComponents:n});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:n,file:t}),property:Uie.body(a)}}async resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n}){let i=await this.resolveResponseProperty({file:t,endpoint:r,propertyComponents:n});if(i==null)throw new Error("Cannot resolve response property from endpoint: "+r+" in file "+t.relativeFilepath);return i}async resolveResponseProperty({file:t,endpoint:r,propertyComponents:n}){let i=await this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t}),a=await this.resolveObjectProperty({file:i.file,typeName:(typeof i.endpoint.response!="string"?i.endpoint.response?.type:i.endpoint.response)??"",propertyComponents:n});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:n,file:t}),property:a}}async resolveRequestPropertyFromInlinedRequest({typeResolver:t,file:r,requestType:n,propertyComponents:i}){if(i.length===1){let a=i[0]??"",u=typeof n["query-parameters"]!=null?n["query-parameters"]?.[a]:void 0;if(u!=null)return{property:Uie.query(await ETa({file:r,queryParameterKey:a,queryParameter:u})),propertyPath:void 0}}return this.resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:n,propertyComponents:i})}async resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:n,propertyComponents:i}){if(n.body==null)return;if(typeof n.body=="string"){let u=await this.resolveObjectProperty({file:r,typeName:n.body,propertyComponents:i});return u==null?void 0:{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Uie.body(u)}}if(v6(n.body)){let u=await Aqu({typeResolver:t,file:r,objectSchema:n.body,propertyComponents:i});return u==null?void 0:{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Uie.body(u)}}let a=await this.resolveObjectProperty({file:r,typeName:n.body.type,propertyComponents:i});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Uie.body(a)}}async resolveObjectProperty({file:t,typeName:r,propertyComponents:n}){let i=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return await Equ({typeResolver:this.typeResolver,file:xPi(i)??t,resolvedType:i,propertyComponents:n})}async propertyPathFromPropertyComponents({propertyComponents:t,file:r}){return t.length<=1?[]:t.slice(0,-1).map(n=>r.casingsGenerator.generateName(n))}};var ond=require("fs/promises"),NTa=class{async parse({absoluteFilePath:t}){let r=await(0,ond.readFile)(t,"utf-8"),n=r.match(/option\s+csharp_namespace\s*=\s*"([^"]+)";/),i=r.match(/package\s+([a-zA-Z_][\w.]*);/),a=r.match(/service\s+([a-zA-Z_]\w*)\s*{/);return{csharpNamespace:n?.[1],packageName:i?.[1],serviceName:a?.[1]}}};var zTa=class{context;workspace;sourceCache;constructor(t,r){this.context=t,this.workspace=r,this.sourceCache=new Map}async resolveSourceOrThrow({source:t,file:r}){let n=await this.resolveSource({source:t,file:r});if(n==null){if(vca(t))throw new Error(`Cannot resolve source ${t.proto} from file ${r.relativeFilepath}`);this.context.logger.warn(`Cannot resolve source ${t.openapi} from file ${r.relativeFilepath}`)}return n}async resolveSource({source:t,file:r}){return vca(t)?await this.resolveProtobufSource({source:t,file:r}):await this.resolveOpenAPISource({source:t,file:r})}async resolveProtobufSource({source:t,file:r}){let n=yf(this.workspace.absoluteFilePath,Ms.of(t.proto));if(this.sourceCache.has(n))return this.sourceCache.get(n);if(!await Wh(n))return;let a=await new NTa().parse({absoluteFilePath:n}),u={type:"protobuf",absoluteFilePath:n,relativeFilePath:Ms.of(t.proto),csharpNamespace:a.csharpNamespace,packageName:a.packageName,serviceName:a.serviceName};return this.sourceCache.set(n,u),u}async resolveOpenAPISource({source:t,file:r}){let n=yf(this.workspace.absoluteFilePath,Ms.of(t.openapi));if(this.sourceCache.has(n))return this.sourceCache.get(n);if(!await Wh(n))return;let i={type:"openapi",absoluteFilePath:n,relativeFilePath:Ms.of(t.openapi)};return this.sourceCache.set(n,i),i}};var eM=class{workspace;constructor(t){this.workspace=t}resolveTypeOrThrow({type:t,file:r}){let n=this.resolveType({type:t,file:r});if(n==null)throw new Error("Cannot resolve type: "+t+" in file "+r.relativeFilepath);return n}getDeclarationOfNamedTypeOrThrow({referenceToNamedType:t,file:r}){let n=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(n==null)throw new Error("Cannot find declaration of type: "+t+" in file "+r.relativeFilepath);return n}getDeclarationOfNamedType({referenceToNamedType:t,file:r}){let n=FDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=cae(this.workspace,n.relativeFilepath);if(i==null)return;let a=i.types?.[n.typeName];if(a==null){let u=E3(n.typeName);if(u!=null){for(let f of Object.keys(i.types??{})??[])if(u.name&&f.startsWith(u.name)&&f.endsWith(">")){let d=i.types?.[f];return d!=null?{typeName:f,declaration:d,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:n.typeName,declaration:a,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:n=[]}){return P$({type:t,_default:void 0,validation:void 0,visitor:{primitive:i=>({_type:"primitive",primitive:i,originalTypeReference:uT.primitive(i)}),unknown:()=>({_type:"unknown",originalTypeReference:uT.unknown()}),map:({keyType:i,valueType:a})=>i!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:i,valueType:a},originalTypeReference:uT.container(Eq.map({keyType:i.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:i=>i!=null?{_type:"container",container:{_type:"list",itemType:i},originalTypeReference:uT.container(Eq.list(i.originalTypeReference))}:void 0,optional:i=>i!=null?{_type:"container",container:{_type:"optional",itemType:i},originalTypeReference:uT.container(Eq.optional(i.originalTypeReference))}:void 0,set:i=>i!=null?{_type:"container",container:{_type:"set",itemType:i},originalTypeReference:uT.container(Eq.set(i.originalTypeReference))}:void 0,literal:i=>({_type:"container",container:{_type:"literal",literal:i},originalTypeReference:uT.container(Eq.literal(i))}),named:i=>{let a=this.getDeclarationOfNamedType({referenceToNamedType:i,file:r});if(a==null)return;let u={typeName:a.typeName,file:a.file.relativeFilepath,reference:i};if(!n.some(f=>f.file===u.file&&f.typeName===u.typeName))return this.resolveNamedTypeFromDeclaration({referenceToNamedType:i,referencedIn:r,rawDeclaration:a,objectPath:[...n,u]})}}})}resolveNamedTypeOrThrow({referenceToNamedType:t,file:r}){let n=this.resolveNamedType({referenceToNamedType:t,file:r});if(n==null)throw new Error("Cannot resolve type: "+t);return n}resolveNamedType({referenceToNamedType:t,file:r}){let n=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(n!=null)return this.resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:n})}resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:n,objectPath:i=[]}){let{declaration:a,file:u}=n;if(gIn(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:i});let f=jTa({type:t,_default:void 0,validation:void 0,file:r});if(!(f.type!=="named"||cae(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:n.typeName,name:f,declaration:a,filepath:u.relativeFilepath,objectPath:i,originalTypeReference:f,file:u}}};var JIt=class e{static VARIABLE_PREFIX="$";getDeclarationOrThrow(t,r){let n=this.getDeclaration(t,r);if(n==null)throw new Error("Variable does not exist: "+t);return n}getDeclaration(t,r){if(!t.startsWith(e.VARIABLE_PREFIX))return;let n=r.rootApiFile.variables?.[t.substring(1)];if(n!=null)return{declaration:n,file:pMr({casingsGenerator:r.casingsGenerator,rootApiFile:r.rootApiFile})}}getVariableIdOrThrow(t){let r=this.getVariableId(t);if(r==null)throw new Error("Variable reference does not start with "+e.VARIABLE_PREFIX);return r}getVariableId(t){if(t.startsWith(e.VARIABLE_PREFIX))return t.substring(e.VARIABLE_PREFIX.length)}};function RTa(e,t){if(t){for(let[r,n]of Object.entries(t))if(typeof n!="string"&&r===e)return n.audiences}}function und({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":{let r=e??aD.STRING;return{type:"success",example:Pv.string({original:r}),jsonExample:r}}case"BASE_64":return{type:"success",example:Pv.base64(aD.BASE64),jsonExample:aD.BASE64};case"BOOLEAN":return{type:"success",example:Pv.boolean(aD.BOOLEAN),jsonExample:aD.BOOLEAN};case"DATE":return{type:"success",example:Pv.date(aD.DATE),jsonExample:aD.DATE};case"DATE_TIME":return{type:"success",example:Pv.datetime({datetime:new Date(aD.DATE_TIME),raw:aD.DATE_TIME}),jsonExample:aD.DATE_TIME};case"DOUBLE":return{type:"success",example:Pv.double(aD.DOUBLE),jsonExample:aD.DOUBLE};case"FLOAT":return{type:"success",example:Pv.float(aD.FLOAT),jsonExample:aD.FLOAT};case"INTEGER":return{type:"success",example:Pv.integer(aD.INT),jsonExample:aD.INT};case"UINT_64":return{type:"success",example:Pv.uint64(aD.INT64),jsonExample:aD.INT64};case"UINT":return{type:"success",example:Pv.uint(aD.UINT),jsonExample:aD.UINT};case"BIG_INTEGER":return{type:"success",example:Pv.bigInteger(aD.INT64.toString()),jsonExample:`${aD.INT64}`};case"LONG":return{type:"success",example:Pv.long(aD.INT64),jsonExample:aD.INT64};case"UUID":return{type:"success",example:Pv.uuid(aD.UUID),jsonExample:aD.UUID};default:Lc(t.v1)}}function snd({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:a}){if(n>=r)return lRr({containerType:t});switch(t.type){case"list":{let u=YF({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?lRr({containerType:t}):{type:"success",example:gA.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:gA.literal({literal:t.literal._visit({boolean:u=>Pv.boolean(u),string:u=>Pv.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return lRr({containerType:t});let u=YF({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?lRr({containerType:t}):{type:"success",example:gA.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"set":{let u=YF({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?lRr({containerType:t}):{type:"success",example:gA.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=YF({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a}),f=YF({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"||f.type==="failure"?lRr({containerType:t}):{type:"success",example:gA.map({map:[{key:u.example,value:f.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:f.jsonExample}}}default:Lc(t)}}function lRr({containerType:e}){switch(e.type){case"list":return{type:"success",example:gA.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:gA.literal({literal:e.literal._visit({boolean:t=>Pv.boolean(t),string:t=>Pv.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:gA.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"set":return{type:"success",example:gA.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:gA.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Lc(e)}}function x8n({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function lnd({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=YF({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:d}=u;return{type:"success",example:dS.alias({value:f}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:dS.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u=cnd({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:i,maxDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:d}=u;return{type:"success",example:dS.object(f),jsonExample:d}}case"undiscriminatedUnion":{let u=0;for(let f of r.shape.members){let d=YF({fieldName:e,typeReference:f.type,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:c,jsonExample:o}=d;return{type:"success",example:dS.undiscriminatedUnion({index:u,singleUnionType:c}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant;for(let f of r.shape.types){let d=f.shape._visit({noProperties:()=>({type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Bz.noProperties()}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue}}),samePropertiesAsObject:c=>{let o=t[c.typeId];if(o==null)throw new Error(`Failed to find type declaration with id ${c.typeId}`);if(o.shape.type!=="object")throw new Error(`Same properties as object union is not an object ${o.shape.type}`);let l=cnd({currentDepth:i,maxDepth:n,fieldName:e,objectTypeDeclaration:o.shape,typeDeclaration:o,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:g,jsonExample:O}=l;return{type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Bz.samePropertiesAsObject({typeId:o.name.typeId,object:g})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{}}}},singleProperty:c=>{let o=YF({currentDepth:i+1,maxDepth:n,fieldName:e,typeReference:c.type,typeDeclarations:t,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:l,jsonExample:g}=o;return{type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Bz.singleProperty(l)}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,[c.name.wireValue]:g}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(d.type!=="failure")return d}}}return{type:"failure",message:"Failed to generate example for type reference"}}function cnd({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:n,maxDepth:i,currentDepth:a,skipOptionalProperties:u}){let f={},d=[];for(let c of[...r.properties??[],...r.extendedProperties??[]]){let o=YF({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:n,currentDepth:a+1,maxDepth:i,skipOptionalProperties:u});if(o.type==="failure"&&!x8n({typeDeclarations:n,typeReference:c.valueType}))return{type:"failure",message:`Failed to generate required property ${c.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:l,jsonExample:g}=o;d.push({name:c.name,originalTypeDeclaration:t.name,value:l}),f[c.name.wireValue]=g}return{type:"success",example:dS.object({properties:d}),jsonExample:f}}function YF({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){if(i>n)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)throw new Error(`Failed to find type declaration with id ${t.typeId}`);let f=lnd({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:d,jsonExample:c}=f;return{type:"success",example:{jsonExample:c,shape:dO.named({shape:d,typeName:u.name})},jsonExample:c}}case"container":{let u=snd({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(u.type==="failure"){let{example:c,jsonExample:o}=lRr({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:dO.container(c)},jsonExample:o}}let{example:f,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:dO.container(f)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:f}=und({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:dO.primitive(f)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:dO.unknown(u)},jsonExample:u}}}}var fnd=Yo(p1u(),1);function NPi({ir:e,endpoint:t,service:r,typeDeclarations:n,skipOptionalRequestProperties:i,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:T4.ok(cN.body(void 0)),docs:void 0},f=[{params:t.pathParameters,add:c=>u.endpointPathParameters.push(c)},{params:r.pathParameters,add:c=>u.servicePathParameters.push(c)},{params:e.pathParameters,add:c=>u.rootPathParameters.push(c)}];for(let c of f)for(let o of c.params){let l=YF({fieldName:o.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:o.valueType,skipOptionalProperties:i});if(l.type==="failure")return l;let{example:g}=l;c.add({name:o.name,value:g})}for(let c of t.queryParameters){if(i&&x8n({typeDeclarations:n,typeReference:c.valueType}))continue;let o=YF({fieldName:c.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:c.valueType,skipOptionalProperties:i});if(o.type==="failure")return o;let{example:l}=o;u.queryParameters.push({name:c.name,shape:c.allowMultiple?NF.exploded():NF.single(),value:l})}let d=[{params:t.headers,add:c=>u.endpointHeaders.push(c)},{params:r.headers,add:c=>u.serviceHeaders.push(c)}];for(let c of d)for(let o of c.params){if(i&&x8n({typeDeclarations:n,typeReference:o.valueType}))continue;let l=YF({fieldName:o.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:o.valueType,skipOptionalProperties:i});if(l.type==="failure")return l;let{example:g}=l;c.add({name:o.name,value:g})}if(t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let c={},o=[];for(let l of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let g=YF({fieldName:l.name.wireValue,typeReference:l.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(g.type==="failure"&&!x8n({typeDeclarations:n,typeReference:l.valueType}))return{type:"failure",message:`Failed to generate required property ${l.name.wireValue} b/c ${g.message}`};if(g.type==="failure")continue;let{example:O,jsonExample:P}=g;o.push({name:l.name,originalTypeDeclaration:void 0,value:O}),c[l.name.wireValue]=P}u.request=b$.inlinedRequestBody({jsonExample:c,properties:o});break}case"reference":{let c=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.request=b$.reference(o);break}default:Lc(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let c=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=T4.ok(cN.body({...o,jsonExample:l}));break}case"streamParameter":return{type:"failure",message:"Stream parameter unsupported"};case"streaming":return{type:"failure",message:"Streaming unsupported"};case"text":return{type:"failure",message:"Text unsupported"};default:Lc(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=T4.error({body:void 0,error:a.declaration.name});else{let c=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:a.declaration.type,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.response=T4.error({body:o,error:a.declaration.name})}return{type:"success",example:{id:(0,fnd.default)(u),url:o6w(t,u),...u},jsonExample:void 0}}function o6w(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(i=>{let a=i.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[i.name.originalName]=u});let n=e.fullPath.head+e.fullPath.parts.map(i=>r[i.pathParameter]+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}async function aQ({fdrApiDefinitionId:e,workspace:t,generationLanguage:r,keywords:n,smartCasing:i,disableExamples:a,audiences:u,readme:f,packageName:d,version:c,context:o}){let l=oLt({generationLanguage:r,keywords:n,smartCasing:i}),g=new qTa(u),O=pMr({casingsGenerator:l,rootApiFile:t.definition.rootApiFile.contents}),P=(t.definition.rootApiFile.contents.errors??[]).map(Hr=>({error:uRr({errorName:Hr,file:O}),docs:void 0})),j=new eM(t),M=new yan(t),q=new BTa(j,M),B=new van(t),I=new UDe(j),C=new JIt,F=new zTa(o,t),K={fdrApiDefinitionId:e,apiVersion:await Nrd({file:O,rawApiFileSchema:t.definition.rootApiFile.contents}),apiName:l.generateName(t.definition.rootApiFile.contents.name),apiDisplayName:t.definition.rootApiFile.contents["display-name"],apiDocs:await mTa(t.definition.rootApiFile.contents.docs),auth:await Brd({rawApiFileSchema:t.definition.rootApiFile.contents,file:O,propertyResolver:q,endpointResolver:M}),headers:t.definition.rootApiFile.contents.headers!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents.headers).map(([Hr,Gt])=>L2e({headerKey:Hr,header:Gt,file:O}))):[],idempotencyHeaders:t.definition.rootApiFile.contents["idempotency-headers"]!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents["idempotency-headers"]).map(([Hr,Gt])=>L2e({headerKey:Hr,header:Gt,file:O}))):[],types:{},errors:{},services:{},constants:jrd(l),environments:qqu({casingsGenerator:l,rawApiFileSchema:t.definition.rootApiFile.contents}),errorDiscriminationStrategy:Urd(t.definition.rootApiFile.contents["error-discrimination"],O),basePath:t.definition.rootApiFile.contents["base-path"]!=null?R2e(t.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:await A8n({pathParameters:t.definition.rootApiFile.contents["path-parameters"],file:O,location:mCe.Root,variableResolver:C}),variables:t.definition.rootApiFile.contents.variables!=null?Object.entries(t.definition.rootApiFile.contents.variables).map(([Hr,Gt])=>({docs:typeof Gt!="string"?Gt.docs:void 0,id:Hr,name:O.casingsGenerator.generateName(Hr),type:O.parseTypeReference(Gt)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0},ee=new ITa,J=async Hr=>{ee.addSubpackage(Hr.fernFilepath),await VP(Hr.definitionFile,{imports:cl,docs:Gt=>{Gt!=null&&ee.addDocs(Hr.fernFilepath,Gt)},types:async Gt=>{if(Gt!=null)for(let[wn,An]of Object.entries(Gt)){if(bCe(wn))continue;let Ht=await Yrd({typeName:wn,typeDeclaration:An,file:Hr,typeResolver:j,exampleResolver:I,sourceResolver:F,workspace:t}),er=Ht.typeDeclaration;a&&(er.userProvidedExamples=[],er.autogeneratedExamples=[]);let dn=Ht.descendantFilepaths,fn=s1.generateTypeId(er.name);K.types[fn]=er,ee.addType(fn,er),g.addType({declaredTypeName:er.name,descendantTypeIds:er.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:Ht.propertiesByAudience,descendantFilepaths:dn}),g.markTypeForAudiences(er.name,qtd(An))}},errors:Gt=>{if(Gt==null)return;if(t.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[An,Ht]of Object.entries(Gt)){let er=Frd({errorName:An,errorDeclaration:Ht,file:Hr,typeResolver:j,exampleResolver:I,workspace:t}),dn=s1.generateErrorId(er.name);K.errors[dn]=er,ee.addError(dn,er),g.addError(er)}},service:async Gt=>{if(Gt==null)return;let wn=await wrd({rootDefaultUrl:Hr.defaultUrl??t.definition.rootApiFile.contents["default-url"],rootPathParameters:K.pathParameters,serviceDefinition:Gt,file:Hr,errorResolver:B,typeResolver:j,propertyResolver:q,exampleResolver:I,sourceResolver:F,globalErrors:P,variableResolver:C,workspace:t}),An=s1.generateServiceId(wn.name);K.services[An]=wn,ee.addService(An,wn);let Ht={};wn.endpoints.forEach(er=>{a&&(er.autogeneratedExamples=[],er.userSpecifiedExamples=[]);let dn=Gt.endpoints[er.name.originalName];g.addEndpoint(wn,er,dn),Ht[er.name.originalName]=er}),Gt.audiences!=null&&g.markEndpointForAudience(wn.name,wn.endpoints,Gt.audiences),Object.entries(Gt.endpoints).map(([er,dn])=>{let fn=Ht[er];fn!=null&&dn.audiences!=null&&g.markEndpointForAudience(wn.name,[fn],dn.audiences)})},webhooks:async Gt=>{if(Gt==null)return;let wn=s1.generateWebhookGroupId(Hr.fernFilepath),An=await Wrd({webhooks:Gt,file:Hr,typeResolver:j,exampleResolver:I,workspace:t}),Ht={};for(let er of An)Ht[er.name.originalName]=er;Object.entries(Gt).forEach(([er,dn])=>{let fn=Ht[er];fn!=null&&(g.addWebhook(Hr,fn,dn),dn.audiences!=null&&g.markWebhookForAudiences(Hr,fn,dn.audiences))}),K.webhookGroups[wn]=An,ee.addWebhookGroup(wn,Hr.fernFilepath)},channel:async Gt=>{if(Gt==null)return;let wn=s1.generateWebSocketChannelId(Hr.fernFilepath),An=await zrd({channel:Gt,file:Hr,variableResolver:C,typeResolver:j,exampleResolver:I,workspace:t});K.websocketChannels!=null&&(K.websocketChannels[wn]=An,ee.addWebSocketChannel(wn,Hr.fernFilepath))}})};await Jz(t,async(Hr,Gt,wn)=>{await J(qO({relativeFilepath:Hr,definitionFile:Gt,casingsGenerator:l,rootApiFile:t.definition.rootApiFile.contents,defaultUrl:wn.defaultUrl}))}),await Enn(t,async(Hr,Gt)=>{if(Gt.navigation!=null)if(typeof Gt.navigation=="string")ee.addPackageRedirection({from:jae({relativeFilepath:Hr,casingsGenerator:l}),to:jae({relativeFilepath:yf(cb(Hr),Ms.of(Gt.navigation)),casingsGenerator:l})});else{let wn=Gt.navigation.map(An=>s1.generateSubpackageId(jae({relativeFilepath:yf(cb(Hr),Ms.of(An)),casingsGenerator:l})));Hr===$A?ee.sortRootPackage(wn):ee.sortSubpackage(s1.generateSubpackageId(jae({relativeFilepath:Hr,casingsGenerator:l})),wn)}}),K.serviceTypeReferenceInfo=s6w(g);let G=a?K:u6w(K,o),te=t.definition.rootApiFile.contents,Xe=qqu({casingsGenerator:l,rawApiFileSchema:te}),Re=Xe?.environments._visit({singleBaseUrl:Hr=>Hr.environments.filter(Gt=>RTa(Gt.id,te.environments)!=null).length===0,multipleBaseUrls:Hr=>Hr.environments.filter(Gt=>RTa(Gt.id,te.environments)!=null).length===0,_other:()=>!1});Xe?.environments.environments.forEach(Hr=>{g.markEnvironmentForAudiences(Hr,RTa(Hr.id,te.environments)??[],Re)});let Pt=g.hasNoAudiences()?void 0:g.build(),Ct=c6w(G,Pt),Wt=t.definition.rootApiFile.contents.auth!=null&&Object.values(Ct.services).every(Hr=>Hr.endpoints.every(Gt=>Gt.auth)),Bt=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.response?.body?.type==="streaming")),or=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.pagination!=null)),jr=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.response?.body?.type==="fileDownload")),Vr=f!=null?Vrd({readme:f,services:K.services}):void 0,{types:It,services:cr}=Zrd(Ct);return{...Ct,...ee.build(Pt),types:It,services:cr,sdkConfig:{isAuthMandatory:Wt,hasStreamingEndpoints:Bt,hasPaginatedEndpoints:or,hasFileDownloadEndpoints:jr,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:c!=null&&d!=null?{header:"User-Agent",value:`${d}/${c}`}:void 0}},readmeConfig:Vr}}function u6w(e,t){for(let[r,n]of Object.entries(e.services))for(let i of n.endpoints){t.logger.debug(`Generating example for ${i.id}`);let a=NPi({ir:e,service:n,endpoint:i,typeDeclarations:e.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(a.type==="failure"){t.logger.debug(`Failed to generate example for ${i.id}. ${a.message}`);continue}let{example:u}=a;i.autogeneratedExamples=[{example:u}]}return e}function s6w(e){let t={},r=[],n=e.getTypesReferencedByService();for(let[i,a]of Object.entries(n)){if(a.size===1){let u=a.values().next().value;t[u]===void 0&&(t[u]=[]),t[u]?.push(i);continue}r.push(i)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function c6w(e,t){if(t==null)return e;let r=Pkr(e.types,u=>t.hasType(u)),n=Object.fromEntries(Object.entries(r).map(([u,f])=>{let d=[];if(f.userProvidedExamples=f.userProvidedExamples.map(c=>nnd({filteredIr:t,exampleType:c})).filter(c=>c!==void 0),f.shape.type==="object"){for(let c of f.shape.properties)t.hasProperty(u,c.name.wireValue)&&d.push(c);return[u,{...f,shape:Sq.object({...f.shape,properties:d})}]}return[u,f]})),i=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,f])=>{let d=f.filter(c=>t.hasWebhook(c)).map(c=>{let o=c.id;return c.payload.type==="inlinedPayload"&&o!=null&&(c.payload={...c.payload,properties:c.payload.properties.filter(l=>t.hasWebhookPayloadProperty(o,l.name.wireValue))}),c});return[u,d]})),a=e.environments;if(a){switch(a.environments.type){case"singleBaseUrl":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}case"multipleBaseUrls":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}}a.defaultEnvironment&&(t.hasEnvironmentId(a.defaultEnvironment)||(a.defaultEnvironment=void 0))}return{...e,environments:a,types:n,errors:Pkr(e.errors,u=>t.hasError(u)),services:by(Pkr(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(f=>t.hasEndpoint(f)).map(f=>(f.autogeneratedExamples=f.autogeneratedExamples.map(d=>({...d,example:Lqu({filteredIr:t,example:d.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?Lqu({filteredIr:t,example:d.example}):void 0})),f.queryParameters.length>0&&(f.queryParameters=f.queryParameters.filter(d=>t.hasQueryParameter(f.id,d.name.wireValue))),f.requestBody?.type==="inlinedRequestBody"?{...f,requestBody:{...f.requestBody,properties:f.requestBody.properties.filter(d=>t.hasRequestProperty(f.id,d.name.wireValue))}}:f))})),webhookGroups:i,serviceTypeReferenceInfo:l6w(e.serviceTypeReferenceInfo,t)}}function l6w(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([n,i])=>{t.hasServiceId(n)&&(r[n]=i.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(n=>t.hasTypeId(n)),typesReferencedOnlyByService:r}}var Pnd=Yo(_Ta(),1),wnd=Yo(hTa(),1),VTa=require("fs/promises"),jnd=Yo(fxa(),1);function cLt(e){return typeof e.subpackageId=="string"}function VDe(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function ban(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var Uqu="__package__",fRr=class e{api;context;static create(t,r){return new e(t,r)}#e=new Map;#t=new Map;#n=new Map;#i=new Map;#r=new Map;#a=new Map;#o=new Map;#f=new Map;#c=new Map;#s=new Map;#u=new Map;static getSubpackageId(t){return cLt(t)?t.subpackageId:Uqu}getSubpackageByIdOrLocator(t){if(t==null)return;let r=KF.SubpackageId(t);return r===Uqu?this.api.rootPackage:this.api.subpackages[r]??this.#u.get(r)}resolveSubpackage(t){if(t!=null){for(;t?.pointsTo!=null;)t=this.api.subpackages[t.pointsTo];return t}}constructor(t,r){this.api=t,this.context=r,[t.rootPackage,...Object.values(t.subpackages)].forEach(n=>{let i=KF.SubpackageId(e.getSubpackageId(n)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(i,a),n.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let f=e.createEndpointId(u,i);this.#e.set(f,u);let d=[],c=[u.method];u.response?.type.type==="stream"&&c.push("STREAM"),c.forEach(o=>{d.push(`${o} ${VDe(u.path.parts)}`),d.push(`${o} ${ban(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,VDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,ban(u.path.parts))}`);let g=dnd(l);g!=null&&(d.push(`${o} ${k1(g,VDe(u.path.parts))}`),d.push(`${o} ${k1(g,ban(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.debug(`Registering endpoint locator: ${o}`),this.#f.set(o,u)})}),n.websockets.forEach(u=>{a.webSockets.set(u.id,u);let f=e.createWebSocketId(u,i);this.#t.set(f,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${VDe(u.path.parts)}`),d.push(`${o} ${ban(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,VDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,ban(u.path.parts))}`);let g=dnd(l);g!=null&&(d.push(`${o} ${k1(g,VDe(u.path.parts))}`),d.push(`${o} ${k1(g,ban(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.debug(`Registering websocket locator: ${o}`),this.#c.set(o,u)})}),n.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#n.set(e.createWebhookId(u,i),u)})}),this.#e.forEach((n,i)=>{this.#i.set(n,i)}),this.#t.forEach((n,i)=>{this.#r.set(n,i)}),this.#n.forEach((n,i)=>{this.#a.set(n,i)}),this.#d(t.rootPackage,[])}#d(t,r){if(t==null)return;let n=cLt(t)?[...r,t.name]:r,i=n.length===0?[Uqu]:n;if([i.join("."),i.join("/"),`${i.join(".")}.yml`].forEach(u=>{this.context?.logger.debug(`Registering subpackage locator: ${u}`),this.#u.set(u,t)}),t.pointsTo!=null)return this.#d(this.api.subpackages[t.pointsTo],n);t.endpoints.forEach(u=>{let f=[...n,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering endpoint locator: ${c}`),this.#f.set(c,u)})}),t.websockets.forEach(u=>{let f=[...n,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering websocket locator: ${c}`),this.#c.set(c,u)})}),t.webhooks.forEach(u=>{let f=[...n,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering webhook locator: ${c}`),this.#s.set(c,u)})}),t.subpackages.forEach(u=>{this.#d(this.api.subpackages[u],n)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#n}get endpointsByLocator(){return this.#f}get webSocketsByLocator(){return this.#c}get webhooksByLocator(){return this.#s}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#u}getEndpointId(t){return this.#i.get(t)}getWebSocketId(t){return this.#r.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return Yc.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return Yc.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return Yc.WebhookId(`${r}.${t.id}`)}};function dnd(e){if(e!=null){if(e.baseUrl.startsWith("/"))return e.baseUrl;if(e.baseUrl.startsWith("http")||e.baseUrl.startsWith("ws"))try{return new URL(e.baseUrl).pathname}catch{return}}}var T8n=Yo(_Ta(),1),_nd=Yo(hTa(),1);function pnd(e){let t=e.split(".")[0];if(t==null)return;let n=/(^\d{1,4})-(\d{1,2})-(\d{1,4})/.exec(t)?.[0];if(n!=null)try{return new Date(n)}catch{}}T8n.default.extend(_nd.default);var f6w="Changelog",d6w=["summary","index","overview"],gan=class{markdownToFullSlug;changelogFiles;docsWorkspace;idgen;constructor(t,r,n,i){this.markdownToFullSlug=t,this.changelogFiles=r,this.docsWorkspace=n,this.idgen=i}toChangelogNode(t){let r=t.title??f6w,n=[],i;for(let l of this.changelogFiles??[]){let g=PKo(l.split("/"));if(g==null)continue;let O=pnd(g);if(O==null){let j=g.split(".")[0]?.toLowerCase();j!=null&&d6w.includes(j)&&(i=l);continue}let P=this.toRelativeFilepath(l);n.push({date:O,pageId:Yc.PageId(P),absoluteFilepath:l})}let a=t.parentSlug.apply({fullSlug:i!=null?this.markdownToFullSlug.get(i)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??nH(r)}),u=n.map(l=>{let g=T8n.default.utc(l.date);return{id:this.idgen.get(l.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(l.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:l.date.toISOString(),pageId:l.pageId,noindex:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}),f=Vqu(u,l=>l.date,"desc"),d=i!=null?Yc.PageId(this.toRelativeFilepath(i)):void 0,c=this.idgen.get(d??"changelog"),o=this.groupByYear(c,f,a);return{id:c,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:o,overviewPageId:d,noindex:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}groupByYear(t,r,n){let i=new Map;for(let a of r){let u=T8n.default.utc(a.date).year(),f=i.get(u)??[];f.push(a),i.set(u,f)}return Vqu(Array.from(i.entries()).map(([a,u])=>{let f=n.append(a.toString()).get(),d=this.idgen.get(`${t}/year/${a}`);return{id:d,type:"changelogYear",title:a.toString(),year:a,slug:f,icon:void 0,hidden:void 0,children:this.groupByMonth(d,u,n),authed:void 0,viewers:void 0,orphaned:void 0}}),"year","desc")}groupByMonth(t,r,n){let i=new Map;for(let a of r){let u=T8n.default.utc(a.date).month()+1,f=i.get(u)??[];f.push(a),i.set(u,f)}return Vqu(Array.from(i.entries()).map(([a,u])=>{let f=(0,T8n.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:f.format("MMMM YYYY"),month:a,slug:n.append(a.toString()).get(),icon:void 0,hidden:void 0,children:u,authed:void 0,viewers:void 0,orphaned:void 0}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}};function Vqu(e,t,r="asc"){return e.concat().sort((n,i)=>{let a=typeof t=="function"?t(n):n[t],u=typeof t=="function"?t(i):i[t];return a<u?r==="asc"?-1:1:a>u?r==="asc"?1:-1:0})}var FTa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;apiDefinitionId;#e;#t=new Set;#n=new Set;#i=new Set;#r=new Set;#a=new Map;#o=[];#f;#c;#s;disableEndpointPairs;constructor(t,r,n,i,a,u,f,d){this.apiSection=t,this.workspace=i,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=f,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Yc.V1.ApiDefinitionId(r.id),this.#e=fRr.create(r,u),this.#s=d,this.#f=this.apiSection.overviewAbsolutePath!=null?Yc.V1.PageId(this.toRelativeFilepath(this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#c=n.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??nH(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#u(this.apiSection.navigation,this.#e.api.rootPackage,this.#c)),this.#o=this.#y(this.#o.map(o=>this.#g(o)),this.#j(this.#e.api.rootPackage,this.#c))}get(){let t=Yc.V1.followRedirects(this.#o);return{id:this.#s.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#c.get(),icon:this.apiSection.icon,hidden:this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:new gan(this.markdownFilesToFullSlugs,this.workspace.changelog?.files.map(r=>r.absoluteFilepath),this.docsWorkspace,this.#s).toChangelogNode({parentSlug:this.#c,viewers:[]}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#b(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned}}#u(t,r,n){r=this.#e.resolveSubpackage(r);let i=r!=null?fRr.getSubpackageId(r):void 0;return t.map(a=>Cxa(a)._visit({link:u=>({id:this.#s.get(u.url),type:"link",title:u.text,icon:u.icon,url:Yc.Url(u.url)}),page:u=>this.#d(u,n),package:u=>this.#v(u,n),section:u=>this.#_(u,n),item:({value:u})=>this.#p(u,i,n),endpoint:u=>this.#P(u,i,n)})).filter($M)}#d(t,r){let n=Yc.V1.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/"),urlSlug:t.slug??nH(t.title)});return{id:this.#s.get(n),type:"page",pageId:n,title:t.title,slug:i.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#v(t,r){let n=t.overviewAbsolutePath!=null?Yc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,i=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=fRr.getSubpackageId(a),f=this.#s.get(n??`${this.apiDefinitionId}:${u}`);this.#r.has(u)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${u}`),this.#r.add(u),this.#a.set(f,[u]);let d=t.slug??(cLt(a)?a.urlSlug:this.apiSection.slug??nH(this.apiSection.title)),c=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#u(t.contents,a,c);return{id:f,type:"apiPackage",children:o,title:t.title??(cLt(a)?a.displayName??ian(a.name):this.apiSection.title),slug:c.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??nH(t.package),f=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#u(t.contents,void 0,f);return{id:this.#s.get(n??`${this.apiDefinitionId}:${nH(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:f.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}}#_(t,r){let n=t.overviewAbsolutePath!=null?Yc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,i=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#s.get(n??i??r.get()),u=t.referencedSubpackages.map(o=>{let l=this.#e.getSubpackageByIdOrLocator(o);return l!=null?fRr.getSubpackageId(l):void 0}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter($M);this.#a.set(a,u),u.forEach(o=>{this.#r.has(o)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${o}`),this.#r.add(o)});let f=t.slug??nH(t.title),d=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),c=this.#u(t.contents,void 0,d);return{id:a,type:"apiPackage",children:c,title:t.title,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#p(t,r,n){t=t.trim();let i=this.#e.getSubpackageByIdOrLocator(t);if(i!=null){let a=fRr.getSubpackageId(i),u=this.#s.get(`${this.apiDefinitionId}:${a}`);this.#r.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#r.add(a),this.#a.set(u,[a]);let f=cLt(i)?i.urlSlug:"",d=n.apply({urlSlug:f});return{id:u,type:"apiPackage",children:[],title:cLt(i)?i.displayName??ian(i.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}return this.#P({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0},r,n)}#P(t,r,n){let i=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.endpoints.get(KF.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(i!=null){let f=this.#e.getEndpointId(i);if(f==null)throw new Error(`Expected Endpoint ID for ${i.id}. Got undefined.`);this.#t.has(f)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${f}`),this.#t.add(f);let d=t.slug!=null?n.append(t.slug):n.apply(i);return{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"endpoint",method:i.method,endpointId:f,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),isResponseStream:i.response?.type.type==="stream",title:t.title??i.name??VDe(i.path.parts),slug:d.get(),icon:t.icon,hidden:t.hidden,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let a=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.webSockets.get(KF.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let f=this.#e.getWebSocketId(a);if(f==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#n.has(f)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${f}`),this.#n.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webSocket",webSocketId:f,title:t.title??a.name??VDe(a.path.parts),slug:(t.slug!=null?n.append(t.slug):n.apply(a)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(a.availability),playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let u=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.webhooks.get(KF.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Yc.V1.WebhookId(t.endpoint));if(u!=null){let f=this.#e.getWebhookId(u);if(f==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#i.has(f)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${f}`),this.#i.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webhook",webhookId:f,method:u.method,title:t.title??u.name??k1("/",...u.path),slug:(t.slug!=null?n.append(t.slug):n.apply(u)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return this.mergeEndpointPairs([...t,...r]).filter(n=>n.type==="apiPackage"?n.children.length>0:!0)}#g(t){if(t.type==="apiPackage"){let r=Yc.V1.SlugGenerator.init(t.slug),i=(this.#a.get(t.id)??[]).flatMap(f=>this.#m(f,r)),a=t.children.map(f=>this.#g(f)),u=this.#y(a,i);return{...t,children:u,pointsTo:Yc.V1.followRedirects(u)}}return t}#j(t,r){let n=[];return t.endpoints.forEach(i=>{let a=this.#e.getEndpointId(i);if(a==null)throw new Error(`Expected Endpoint ID for ${i.id}. Got undefined.`);if(this.#t.has(a))return;let u=r.apply(i);n.push({id:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:i.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),isResponseStream:i.response?.type.type==="stream",title:i.name??VDe(i.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),t.websockets.forEach(i=>{let a=this.#e.getWebSocketId(i);if(a==null)throw new Error(`Expected WebSocket ID for ${i.id}. Got undefined.`);this.#n.has(a)||n.push({id:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:i.name??VDe(i.path.parts),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),t.webhooks.forEach(i=>{let a=this.#e.getWebhookId(i);if(a==null)throw new Error(`Expected Webhook ID for ${i.id}. Got undefined.`);this.#i.has(a)||n.push({id:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:i.method,title:i.name??ian(i.id),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),t.subpackages.forEach(i=>{if(this.#r.has(i))return;let a=this.#e.getSubpackageByIdOrLocator(i);if(a==null){this.taskContext.logger.error(`Subpackage ${i} not found in ${this.apiDefinitionId}`);return}let u=cLt(a)?r.apply(a):r,f=this.#m(i,u);f.length>0&&n.push({id:Yc.V1.NodeId(`${this.apiDefinitionId}:${i}`),type:"apiPackage",children:f,title:cLt(a)?a.displayName??ian(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:Yc.V1.followRedirects(f),noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),n=this.mergeEndpointPairs(n),this.apiSection.alphabetized&&(n=n.sort((i,a)=>{let u=i.type==="endpointPair"?i.nonStream.title:i.title,f=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(f)})),n}#m(t,r){let n=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return n==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#j(n,r)}#b(t){if(t)return{environments:t.environments!=null&&t.environments.length>0?t.environments.map(r=>Yc.V1.EnvironmentId(r)):void 0,button:t.button!=null&&t.button.href?{href:Yc.V1.Url(t.button.href)}:void 0}}mergeEndpointPairs(t){if(this.disableEndpointPairs)return t;let r=[],n=new Map;return t.forEach(i=>{if(i.type!=="endpoint"){r.push(i);return}let a=this.#e.endpoints.get(i.endpointId);if(a==null)throw new Error(`Endpoint ${i.endpointId} not found`);let u=`${a.method} ${VDe(a.path.parts)}`,f=n.get(u);if(n.set(u,i),f==null||f.isResponseStream===i.isResponseStream){r.push(i);return}let d=r.indexOf(f),c=i.isResponseStream?i:f,o=i.isResponseStream?f:i,l={id:Yc.V1.NodeId(`${this.apiDefinitionId}:${o.endpointId}+${c.endpointId}`),type:"endpointPair",stream:c,nonStream:o};r[d]=l}),r}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}};var hnd=Yo(require("crypto"),1);function p6w(e){return hnd.default.createHash("sha256").update(e).digest("hex")}var LTa=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#n(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),p6w(r===0?t:`${t}-${r}`)}#i(t){let r=this.#n(t),n=0;for(;this.#t.has(r);)if(r=this.#n(t),n++,n>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Yc.V1.NodeId(this.#i(t))}};function ynd(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0}}var UTa=Yo(m6t(),1);var DD=Yo(m6t(),1);var dRr=Yo(m6t(),1);function vnd(e){return e._visit({alias:t=>({type:"alias",value:Ex(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:$5(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>dRr.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:dRr.FernRegistry.PropertyKey(r.name.wireValue),valueType:Ex(r.valueType),availability:$5(r.availability)})),extraProperties:v6w(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(n=>({key:dRr.FernRegistry.PropertyKey(n.name.wireValue),valueType:Ex(n.valueType),availability:$5(n.availability),description:n.docs}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(n=>({description:n.docs??void 0,discriminantValue:n.discriminantValue.wireValue,displayName:n.displayName,availability:n.availability!=null?$5(n.availability):void 0,additionalProperties:lp.types.SingleUnionTypeProperties._visit(n.shape,{samePropertiesAsObject:i=>({extends:[dRr.FernRegistry.TypeId(i.typeId)],properties:r,extraProperties:void 0}),singleProperty:i=>({extends:[],properties:[{key:dRr.FernRegistry.PropertyKey(i.name.wireValue),valueType:Ex(i.type),description:void 0,availability:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+n.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:Ex(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function Ex(e){return e._visit({container:t=>lp.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:Ex(r)}),map:({keyType:r,valueType:n})=>({type:"map",keyType:Ex(r),valueType:Ex(n)}),optional:r=>({type:"optional",itemType:Ex(r),defaultValue:void 0}),set:r=>({type:"set",itemType:Ex(r)}),literal:r=>lp.types.Literal._visit(r,{boolean:n=>({type:"literal",value:{type:"booleanLiteral",value:n}}),string:n=>({type:"literal",value:{type:"stringLiteral",value:n}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:dRr.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:lp.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>h6w(t.v2),float:()=>({type:"double",minimum:22250738585072014e-324,maximum:17976931348623157e292,default:0}),double:()=>y6w(t.v2),string:()=>_6w(t.v2),long:()=>({type:"long",default:0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:!1}),dateTime:()=>({type:"datetime",default:new Date(0).toISOString()}),date:()=>({type:"date",default:new Date(0).toISOString()}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",default:"0"}),bigInteger:()=>({type:"bigInteger",default:BigInt(0).toString()}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function _6w(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",regex:t?.pattern,minLength:t?.minLength,maxLength:t?.minLength,default:e!=null&&e.type==="string"?e.default:void 0}}function h6w(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function y6w(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function v6w(e){return typeof e=="boolean"?uT.unknown():typeof e=="string"?{type:"id",value:dRr.FernRegistry.TypeId(e),default:void 0}:Ex(e)}function Hqu(e,t){let r=e.service!=null?t.services[e.service]:void 0,n=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,i=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?g6w(r,t):[],webhooks:n!=null?b6w(n):[],websockets:i!=null?[m6w(i,t)]:[],types:e.types.map(a=>DD.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>DD.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?DD.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function b6w(e){return e.map(t=>({description:t.docs??void 0,id:DD.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Ldi(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:Ex(r.valueType),availability:$5(r.availability)})),payload:A6w(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function g6w(e,t){let r=[];for(let n of e.endpoints){let i=n.autogeneratedExamples[0],a=[];if(n.userSpecifiedExamples.length>0&&i!=null)a.push(...n.userSpecifiedExamples.map(f=>Wqu({autogeneratedExample:i,userSpecifiedExample:f,irEndpoint:n,ir:t})));else if(i!=null)a.push(Wqu({autogeneratedExample:i,irEndpoint:n,ir:t}));else if(n.response?.body?.type==="fileDownload"){let f=NPi({ir:t,service:e,endpoint:{...n,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(f.type==="success"){let d={...Wqu({autogeneratedExample:f,irEndpoint:n,ir:t}),responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(d)}}let u={availability:$5(n.availability??e.availability),auth:n.auth,description:n.docs??void 0,method:j6w(n.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?O6w({environmentsConfig:t.environments,endpoint:n}):void 0,id:DD.FernRegistry.EndpointId(n.name.originalName),originalEndpointId:n.id,name:n.displayName??Ldi(n.name.originalName),path:n.basePath!=null?{pathParameters:n.pathParameters.map(f=>({description:f.docs??void 0,key:DD.FernRegistry.PropertyKey(f.name.originalName),type:Ex(f.valueType),availability:void 0})),parts:[...C8n(n.basePath),...C8n(n.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...n.pathParameters].map(f=>({description:f.docs??void 0,key:DD.FernRegistry.PropertyKey(f.name.originalName),type:Ex(f.valueType),availability:void 0})),parts:[...t.basePath!=null?C8n(t.basePath):[],...C8n(e.basePath),...C8n(n.path)]},queryParameters:n.queryParameters.map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:Ex(f.valueType),availability:$5(f.availability)})),headers:[...e.headers,...n.headers].map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:Ex(f.valueType),availability:$5(f.availability)})),request:n.requestBody!=null?D6w(n.requestBody):void 0,response:n.response!=null?S6w(n.response):void 0,errors:void 0,errorsV2:E6w(n.errors,t),examples:a};r.push(u)}return r}function m6w(e,t){return{auth:e.auth,availability:$5(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?P6w({environmentsConfig:t.environments,channel:e}):[],id:DD.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??Ldi(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:DD.FernRegistry.PropertyKey(r.name.originalName),type:Ex(r.valueType),availability:void 0})),parts:C8n(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:Ex(r.valueType),description:r.docs,availability:$5(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:Ex(r.valueType),availability:$5(r.availability)})),messages:e.messages.map(r=>({type:DD.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:M6w(r.body),description:r.docs,availability:$5(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((n,i)=>(n[DD.FernRegistry.PropertyKey(i.name.originalName)]=i.value.jsonExample,n),{}),queryParameters:r.queryParameters.reduce((n,i)=>(n[i.name.wireValue]=i.value.jsonExample,n),{}),headers:r.headers.reduce((n,i)=>(n[i.name.wireValue]=i.value.jsonExample,n),{}),messages:r.messages.map(n=>({type:DD.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}))}}function $5(e){if(e!=null)switch(e.status){case"DEPRECATED":return DD.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return DD.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return DD.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return DD.FernRegistry.Availability.Beta;default:Lc(e.status)}}function O6w({environmentsConfig:e,endpoint:t}){let r=e.environments,n=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:DD.FernRegistry.EnvironmentId(i.id),baseUrl:i.url}));case"multipleBaseUrls":if(n==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(i=>{let a=i.urls[n];if(a==null)throw new Error(`Expected environment ${i.id} to contain url for ${n}`);return{id:DD.FernRegistry.EnvironmentId(i.id),baseUrl:a}});default:Lc(r)}}function P6w({environmentsConfig:e,channel:t}){let r=e.environments;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:DD.FernRegistry.EnvironmentId(n.id),baseUrl:w6w(n.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:Lc(r)}}function w6w(e,t){return e.replace(/^[^:]+/,t)}function j6w(e){return lp.http.HttpMethod._visit(e,{get:()=>DD.FernRegistry.HttpMethod.Get,post:()=>DD.FernRegistry.HttpMethod.Post,put:()=>DD.FernRegistry.HttpMethod.Put,patch:()=>DD.FernRegistry.HttpMethod.Patch,delete:()=>DD.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function C8n(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:DD.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function D6w(e){let t=lp.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??D4.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(n=>DD.FernRegistry.TypeId(n.typeId)),properties:r.properties.map(n=>({description:n.docs??void 0,key:DD.FernRegistry.PropertyKey(n.name.wireValue),valueType:Ex(n.valueType),availability:$5(n.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??D4.APPLICATION_JSON,shape:{type:"reference",value:Ex(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(n=>n._visit({file:i=>{let a=i._visit({file:u=>({type:"file",key:DD.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:DD.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:i=>({type:"bodyProperty",key:DD.FernRegistry.PropertyKey(i.name.wireValue),valueType:Ex(i.valueType),contentType:i.contentType,description:i.docs,availability:$5(i.availability)}),_other:()=>{}})).filter($M)},description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function S6w(e){if(e.body==null)return;let t,r=lp.http.HttpResponseBody._visit(e.body,{fileDownload:n=>(t=n.docs,{type:"fileDownload",contentType:void 0}),json:n=>(t=n.docs,{type:"reference",value:Ex(n.responseBodyType)}),text:()=>{},streamParameter:()=>{},streaming:n=>{if(n.type==="text")return t=n.docs,{type:"streamingText"};if(n.type==="json")return t=n.docs,{type:"stream",shape:{type:"reference",value:Ex(n.payload)},terminator:n.terminator};if(n.type==="sse")return t=n.docs,{type:"stream",shape:{type:"reference",value:Ex(n.payload)},terminator:n.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});if(r!=null)return{type:r,statusCode:e.statusCode,description:t}}function E6w(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let n of e){let i=t.errors[n.error.errorId];i&&r.push({type:i.type==null?void 0:{type:"alias",value:Ex(i.type)},statusCode:i.statusCode,description:i.docs??void 0,name:i.name.name.originalName,availability:void 0,examples:i.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let n of e){let i=t.errors[n.error.errorId];if(i){let a=[{key:DD.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:i.discriminantValue.name.originalName}},description:i.docs,availability:void 0}];i.type!=null&&a.push({key:DD.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:Ex(i.type),description:i.docs,availability:void 0}),r.push({type:i.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:i.statusCode,description:i.docs??void 0,availability:void 0,name:i.name.name.originalName,examples:i.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function Wqu({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:n}){let i=n.headers.map(f=>{let d=f.valueType.type==="container"&&f.valueType.container.type==="literal"?f.valueType.container.literal._visit({boolean:c=>`${c}`,string:c=>c,_other:()=>{}}):void 0;if(d!=null)return{name:f.name,value:{jsonExample:d,shape:lp.ExampleTypeReferenceShape.primitive(lp.ExamplePrimitive.string({original:d}))}}}).filter($M),a=e?.example??t.example,{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((f,d)=>(f[DD.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,f),{}),queryParameters:a.queryParameters.reduce((f,d)=>(f[d.name.wireValue]=d.value.jsonExample,f),{}),headers:[...i,...a.serviceHeaders,...a.endpointHeaders].reduce((f,d)=>(f[d.name.wireValue]=d.value.jsonExample,f),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:f=>{if(a.request==null)return;let d={};if(lS(a.request.jsonExample)){let c=a.request.jsonExample;for(let o of f.properties)o._visit({file:l=>{let g=c[l.key.wireValue];if(l.type==="file")d[l.key.wireValue]={type:"filename",value:typeof g=="string"?g:"<file1>"};else if(l.type==="fileArray"){let O=(Array.isArray(g)?g:[g]).filter(P=>typeof P=="string");d[l.key.wireValue]={type:"filenames",value:O}}},bodyProperty:l=>{d[l.name.wireValue]={type:"json",value:c[l.name.wireValue]}},_other:Gqt})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:lp.http.ExampleResponse._visit(a.response,{ok:f=>f._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+f.type)}}),error:({error:f})=>{let d=n.errors[f.errorId];if(d==null)throw new Error("Cannot find error "+f.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:f=>f._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:f=>f.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:f=>f._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(c=>c.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:c,data:o})=>({event:c,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+f.type)}}),error:f=>f.body!=null?{type:"json",value:f.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(f=>aDe._visit(f,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter($M)}}function A6w(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>DD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:DD.FernRegistry.PropertyKey(t.name.wireValue),valueType:Ex(t.valueType),availability:$5(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:Ex(e.payloadType)},description:e.docs};default:Lc(e)}}function M6w(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>DD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:DD.FernRegistry.PropertyKey(t.name.wireValue),valueType:Ex(t.valueType),availability:$5(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:Ex(e.bodyType)};default:Lc(e)}}var Qqu=Yo(m6t(),1);function bnd(e,t,r){let n=e.schemes[0];if(e.schemes.length===1&&n!=null)switch(n.type){case"basic":return{type:"basicAuth",passwordName:n.password.originalName,usernameName:n.username.originalName};case"bearer":return{type:"bearerAuth",tokenName:n.token.originalName};case"header":return{type:"header",headerWireValue:n.name.wireValue,nameOverride:n.name.name.originalName,prefix:n.prefix};case"oauth":{let i=n.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Qqu.FernRegistry.EndpointId(n.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:Qqu.FernRegistry.JqString(i)}}}:{type:"bearerAuth",tokenName:"token"}}default:Lc(n)}}function WDe({ir:e,snippetsConfig:t,playgroundConfig:r}){let n={types:{},subpackages:{},rootPackage:Hqu(e.rootPackage,e),auth:bnd(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(i=>({availability:$5(i.availability),description:i.docs??void 0,key:i.name.wireValue,type:Ex(i.valueType)})),navigation:void 0};for(let[i,a]of Object.entries(e.types))n.types[UTa.FernRegistry.TypeId(i)]={description:a.docs??void 0,name:a.name.name.originalName,shape:vnd(a.shape),availability:$5(a.availability)};for(let[i,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;n.subpackages[UTa.FernRegistry.api.v1.SubpackageId(i)]={subpackageId:UTa.FernRegistry.api.v1.SubpackageId(i),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...Hqu(a,e)}}return n}var Jqu=Yo(m6t(),1);async function Gqu({organization:e,workspace:t,context:r,token:n,audiences:i,snippetsConfig:a,playgroundConfig:u}){let f=await aQ({workspace:t,audiences:i,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:r}),d=Ttn({token:n.value}),c=WDe({ir:f,snippetsConfig:a,playgroundConfig:u});r.logger.debug("Calling registerAPI... ",JSON.stringify(c,void 0,4));let o=await d.api.v1.register.registerApiDefinition({orgId:Jqu.FernRegistry.OrgId(e),apiId:Jqu.FernRegistry.ApiId(f.apiName.originalName),definition:c});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:f};switch(o.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",o.error)}}var x6w=new uan({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function gnd(e,t,r){return fPi(sPi(WDe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),KF.ApiDefinitionId(t),x6w))}function mnd(e){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.js!=null&&e.js.files.forEach(r=>{t.add(r.absolutePath)}),t}function hMr(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}Pnd.default.extend(wnd.default);var T6w=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),Ond=0,C6w=async({ir:e})=>(Ond++,`${e.apiName.snakeCase.unsafeName}-${Ond}`),yMr=class{domain;docsWorkspace;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;constructor(t,r,n,i,a,u=T6w,f=C6w){this.domain=t,this.docsWorkspace=r,this.fernWorkspaces=n,this.taskContext=i,this.editThisPage=a,this.uploadFiles=u,this.registerApi=f}#e=LTa.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;async resolve(){this._parsedDocsConfig=await bTe.parseDocsConfiguration({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.fernWorkspaces.forEach(d=>{d.changelog?.files.forEach(c=>{let o=jq(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[o]=c.contents})}),this.markdownFilesToFullSlugs=this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages);for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=await FTu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(d),context:this.taskContext});for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=await LTu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(d),context:this.taskContext});let t=mnd(this.parsedDocsConfig);for(let[d,c]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:o,markdown:l}=iPi(c,{absolutePathToMdx:this.resolveFilepath(d),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Ms.of(d)]=l;for(let g of o)t.add(g)}let r=Array.from(t).map(d=>({absoluteFilePath:d,relativeFilePath:this.toRelativeFilepath(d)}));(await this.uploadFiles(r)).forEach(d=>{this.collectedFileIds.set(d.absoluteFilePath,d.fileId)});let i=this.getDocsBasePath();for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=RTu(c,this.collectedFileIds,new Map(Array.from(this.markdownFilesToFullSlugs.entries()).map(([o,l])=>[o,k1(i,l)])),{absolutePathToMdx:this.resolveFilepath(d),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let a={};Object.entries(this.parsedDocsConfig.pages).forEach(([d,c])=>{let o=q6w(this.editThisPage,d);a[VIt.PageId(d)]={markdown:c,editThisPageUrl:o?VIt.Url(o):void 0}});let u=await this.convertDocsConfiguration(),f={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let d=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let o=rT(this.docsWorkspace.absoluteFilePath,c);(await(0,VTa.stat)(o)).isDirectory()?(await eTe(o,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{d.add(O)}):o.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&d.add(o)})),f=Object.fromEntries(await Promise.all([...d].map(async c=>{let o=this.toRelativeFilepath(c),l=(await(0,VTa.readFile)(c)).toString();return[o,l]})))}return{config:u,pages:a,jsFiles:f}}resolveFilepath(t){if(t!=null)return rT(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[n,i]of Object.entries(t)){let u=(0,jnd.default)(i).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(n),u.trim())}return r}getDocsBasePath(){return new URL(hMr(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?VIt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(n=>({...n,url:VIt.Url(n.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(n=>({...n,value:VIt.Url(n.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:void 0,ga4:void 0,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},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,playground:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.fernWorkspaces.length===1&&this.fernWorkspaces[0]!=null)return this.fernWorkspaces[0];if(t.apiName!=null){let r=this.fernWorkspaces.find(n=>n.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}async toRootNode(){let t=Yc.V1.SlugGenerator.init(Yc.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),n=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:n,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}async toRootChild(t){return QTn(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t)})}toLandingPageNode(t,r){let n=Yc.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({urlSlug:t.slug??nH(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(n),title:t.title,slug:i.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:void 0}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:n}){let i=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,n):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(i,r.items,n):await this.toSidebarRootNode(i,r.items,n);return{type:"unversioned",id:i,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((i,a)=>this.toVersionNode(i,r,a===0)))}}async toVersionNode(t,r,n){let i=this.#e.get(t.version),a=r.setVersionSlug(t.version),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(i,t.navigation.items,a):await this.toSidebarRootNode(i,t.navigation.items,a);return{type:"version",id:i,versionId:Yc.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:n,availability:t.availability!=null?I6w(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,r):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0}}async toSidebarRootNode(t,r,n){let i=this.#e.get(`${t}/root`),a=await Promise.all(r.map(f=>this.toNavigationChild(i,f,n))),u=[];return a.forEach(f=>{switch(f.type){case"apiReference":case"section":u.push(f);return;case"changelog":case"link":case"page":{let d=u[u.length-1];d?.type!=="sidebarGroup"&&(d={id:this.#e.get(`${i}/group`),type:"sidebarGroup",children:[]},u.push(d)),d.children.push(f);return}default:Lc(f)}}),{type:"sidebarRoot",id:i,children:u}}async toNavigationChild(t,r,n){return QTn(r)._visit({page:async i=>this.toPageNode(i,n),apiSection:async i=>this.toApiSectionNode(i,n),section:async i=>this.toSectionNode(t,i,n),link:async i=>this.toLinkNode(i),changelog:async i=>this.toChangelogNode(i,n)})}async toApiSectionNode(t,r){let n=this.getFernWorkspaceForApiSection(t),i=ynd(t.snippetsConfiguration),a=await aQ({workspace:n,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:this.taskContext}),u=await this.registerApi({ir:a,snippetsConfig:i,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),f=gnd(a,u,{oauth:t.playground?.oauth});return new FTa(t,f,r,n,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}async toChangelogNode(t,r){return new gan(this.markdownFilesToFullSlugs,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Yc.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let n=Yc.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({urlSlug:t.slug??nH(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:i.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:void 0}}async toSectionNode(t,r,n){let i=this.toRelativeFilepath(r.overviewAbsolutePath),a=i?Yc.PageId(i):void 0,u=this.#e.get(a??`${t}/section`),f=n.apply({urlSlug:r.slug??nH(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug});return{id:u,type:"section",overviewPageId:a,slug:f.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:r.hidden,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(d=>this.toNavigationChild(u,d,f))),authed:void 0,pointsTo:void 0,noindex:void 0}}async convertTabbedNavigation(t,r,n){let i=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:i,children:await Promise.all(r.map(a=>this.toTabChild(i,a,n)))}}async toTabChild(t,r,n){return QTn(r.child)._visit({link:({href:i})=>this.toTabLinkNode(r,i),layout:({layout:i})=>this.toTabNode(t,r,i,n),changelog:({changelog:i})=>this.toTabChangelogNode(r,i,n)})}async toTabChangelogNode(t,r,n){return new gan(this.markdownFilesToFullSlugs,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:n,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:Yc.V1.Url(r),icon:t.icon}}async toTabNode(t,r,n,i){let a=this.#e.get(`${t}/tab`),u=i.apply({urlSlug:r.slug??nH(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,n,u)}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):VIt.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:n}=this.parsedDocsConfig,i=r?.[t],a=n?.[t];return{logo:this.getFileId(i),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let n=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${n}`,variants:t.variants.map(i=>({fontFile:this.getFileId(i.absolutePath),weight:i.weight,style:i.style!=null?[i.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter($M),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:VIt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":n,...i}=this.parsedDocsConfig.metadata;return{...i,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(n)}}convertFileIdOrUrl(t){if(t!=null)return QTn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:VIt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function q6w(e,t){if(e?.github==null)return;let{owner:r,repo:n,branch:i="main",host:a="https://github.com"}=e.github;return`${hMr(a)}/${r}/${n}/blob/${i}/fern/${t}`}function I6w(e){switch(e){case"beta":return Yc.V1.NavigationV1Availability.Beta;case"deprecated":return Yc.V1.NavigationV1Availability.Deprecated;case"ga":return Yc.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Yc.V1.NavigationV1Availability.Stable;default:Lc(e)}}var M0d=Yo(xnd(),1),v3u=Yo(Q6u(),1),x0d=Yo(require("http"),1),Gqa=Yo(require("path"),1);var tsd=require("events"),wCa=Yo(require("fs"),1),Aan=Yo(require("path"),1);var zud=Yo(require("os"),1),Rud=300,bRr=20,i1i=1e7,Fud=zud.default.platform();var v8w=Fud==="darwin",J6u=Fud==="win32",gRr=v8w||J6u,Lud=3e3,Uud=2e4,G6u=1250;var pLt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(pLt||(pLt={}));var Ean;(function(e){e.CHANGE="change",e.RENAME="rename"})(Ean||(Ean={}));var a1i;(function(e){e.CHANGE="change",e.ERROR="error"})(a1i||(a1i={}));var Lm;(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"})(Lm||(Lm={}));var xk;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(xk||(xk={}));var b8w=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,f,d=0,c=0,o=()=>{let C=Date.now(),F=C-d,K=C-c,ee=F>=t||K>=a;return[C,ee]},l=C=>{if(c=C,!u)return;let F=u;u=void 0,e.apply(void 0,F)},g=()=>{B(0)},O=()=>{f&&(g(),l(Date.now()))},P=C=>{if(c=C,n)return l(C)},j=C=>{if(i&&u)return l(C);u=void 0},M=()=>{f=void 0;let[C,F]=o();return F?j(C):q(C)},q=C=>{let F=C-d,K=C-c,ee=t-F,J=a-K,G=Math.min(ee,J);return B(G)},B=C=>{f&&clearTimeout(f),!(C<=0)&&(f=setTimeout(M,C))},I=(...C)=>{let[F,K]=o(),ee=!!f;if(u=C,d=F,(K||!f)&&B(t),K)return ee?l(F):P(F)};return I.cancel=g,I.flush=O,I},gCa=b8w;var Z6u=Yo(require("fs"),1),OCa=Yo(require("path"),1);var Ax=Yo(require("fs"),1),oQ=require("util");var vMr=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},_Lt=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var $6u=Yo(require("process"),1),Vud=$6u.default.getuid?!$6u.default.getuid():!1,Wud=1e4,Aae=()=>{};var o1i={isChangeErrorOk:e=>{if(!o1i.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Vud&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!o1i.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(!o1i.isNodeError(e))throw e;if(!o1i.isChangeErrorOk(e))throw e}},Zz=o1i;var K6u=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Wud,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()}}}}},Hud=new K6u;var bMr=(e,t)=>function(n){return function i(...a){return Hud.schedule().then(u=>{let f=c=>(u(),c),d=c=>{if(u(),Date.now()>=n)throw c;if(t(c)){let o=Math.round(100*Math.random());return new Promise(g=>setTimeout(g,o)).then(()=>i.apply(void 0,a))}throw c};return e.apply(void 0,a).then(f,d)})}},gMr=(e,t)=>function(n){return function i(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>n)throw u;if(t(u))return i.apply(void 0,a);throw u}}};var g8w={attempt:{chmod:vMr((0,oQ.promisify)(Ax.default.chmod),Zz.onChangeError),chown:vMr((0,oQ.promisify)(Ax.default.chown),Zz.onChangeError),close:vMr((0,oQ.promisify)(Ax.default.close),Aae),fsync:vMr((0,oQ.promisify)(Ax.default.fsync),Aae),mkdir:vMr((0,oQ.promisify)(Ax.default.mkdir),Aae),realpath:vMr((0,oQ.promisify)(Ax.default.realpath),Aae),stat:vMr((0,oQ.promisify)(Ax.default.stat),Aae),unlink:vMr((0,oQ.promisify)(Ax.default.unlink),Aae),chmodSync:_Lt(Ax.default.chmodSync,Zz.onChangeError),chownSync:_Lt(Ax.default.chownSync,Zz.onChangeError),closeSync:_Lt(Ax.default.closeSync,Aae),existsSync:_Lt(Ax.default.existsSync,Aae),fsyncSync:_Lt(Ax.default.fsync,Aae),mkdirSync:_Lt(Ax.default.mkdirSync,Aae),realpathSync:_Lt(Ax.default.realpathSync,Aae),statSync:_Lt(Ax.default.statSync,Aae),unlinkSync:_Lt(Ax.default.unlinkSync,Aae)},retry:{close:bMr((0,oQ.promisify)(Ax.default.close),Zz.isRetriableError),fsync:bMr((0,oQ.promisify)(Ax.default.fsync),Zz.isRetriableError),open:bMr((0,oQ.promisify)(Ax.default.open),Zz.isRetriableError),readFile:bMr((0,oQ.promisify)(Ax.default.readFile),Zz.isRetriableError),rename:bMr((0,oQ.promisify)(Ax.default.rename),Zz.isRetriableError),stat:bMr((0,oQ.promisify)(Ax.default.stat),Zz.isRetriableError),write:bMr((0,oQ.promisify)(Ax.default.write),Zz.isRetriableError),writeFile:bMr((0,oQ.promisify)(Ax.default.writeFile),Zz.isRetriableError),closeSync:gMr(Ax.default.closeSync,Zz.isRetriableError),fsyncSync:gMr(Ax.default.fsyncSync,Zz.isRetriableError),openSync:gMr(Ax.default.openSync,Zz.isRetriableError),readFileSync:gMr(Ax.default.readFileSync,Zz.isRetriableError),renameSync:gMr(Ax.default.renameSync,Zz.isRetriableError),statSync:gMr(Ax.default.statSync,Zz.isRetriableError),writeSync:gMr(Ax.default.writeSync,Zz.isRetriableError),writeFileSync:gMr(Ax.default.writeFileSync,Zz.isRetriableError)}},Qud=g8w;var mCa=Yo(require("fs"),1),u1i=Yo(require("path"),1);var Jud={then:e=>{e()}};var Y6u=()=>{};var X6u=()=>{let e=Y6u,t=Y6u,r=!1,n=!1;return{promise:new Promise((d,c)=>{e=o=>(r=!0,d(o)),t=o=>(n=!0,c(o))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}};X6u.wrap=async e=>{let t=X6u();return await e(t),t.promise};var Gud=X6u;var $ud=e=>Array.isArray(e)?e:[e],Kud=e=>typeof e=="function",Yud=()=>{let{promise:e,resolve:t}=Gud(),r=0,n=()=>{r+=1},i=()=>{r-=1,!r&&t()};return(()=>{n(),queueMicrotask(i)})(),{promise:e,increment:n,decrement:i}};var m8w=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,a=t?.ignore??[],u=$ud(a).map(It=>Kud(It)?It:cr=>It.test(cr)),f=It=>u.some(cr=>cr(It)),d=t?.signal??{aborted:!1},c=t?.onDirents||(()=>{}),o=[],l=new Set,g={},O=[],P=new Set,j={},M=[],q=new Set,B={},I={},C=new Set,F={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},K={directories:o,directoriesNames:l,directoriesNamesToPaths:g,files:O,filesNames:P,filesNamesToPaths:j,symlinks:M,symlinksNames:q,symlinksNamesToPaths:B,map:I},{promise:ee,increment:J,decrement:G}=Yud(),te=0,Xe=(It,cr,Hr,Gt)=>{C.has(cr)||te>=i||(te+=1,It.directories.push(cr),It.directoriesNames.add(Hr),o.push(cr),l.add(Hr),g.propertyIsEnumerable(Hr)||(g[Hr]=[]),g[Hr].push(cr),C.add(cr),!(Gt>=n)&&(te>=i||or(cr,Gt+1)))},Re=(It,cr,Hr)=>{C.has(cr)||te>=i||(te+=1,It.files.push(cr),It.filesNames.add(Hr),O.push(cr),P.add(Hr),j.propertyIsEnumerable(Hr)||(j[Hr]=[]),j[Hr].push(cr),C.add(cr))},Pt=(It,cr,Hr,Gt)=>{C.has(cr)||te>=i||(te+=1,It.symlinks.push(cr),It.symlinksNames.add(Hr),M.push(cr),q.add(Hr),B.propertyIsEnumerable(Hr)||(B[Hr]=[]),B[Hr].push(cr),C.add(cr),r&&(Gt>=n||te>=i||jr(cr,Gt+1)))},Ct=(It,cr,Hr,Gt,wn)=>{d.aborted||f(cr)||(Gt.isDirectory()?Xe(It,cr,Hr,wn):Gt.isFile()?Re(It,cr,Hr):Gt.isSymbolicLink()&&Pt(It,cr,Hr,wn))},Wt=(It,cr,Hr,Gt)=>{if(d.aborted)return;let wn=cr===u1i.default.sep?"":u1i.default.sep,An=Hr.name,Ht=`${cr}${wn}${An}`;f(Ht)||(Hr.isDirectory()?Xe(It,Ht,An,Gt):Hr.isFile()?Re(It,Ht,An):Hr.isSymbolicLink()&&Pt(It,Ht,An,Gt))},Bt=(It,cr,Hr,Gt)=>{for(let wn=0,An=Hr.length;wn<An;wn++)Wt(It,cr,Hr[wn],Gt)},or=(It,cr)=>{d.aborted||cr>n||te>=i||(J(),mCa.default.readdir(It,{withFileTypes:!0},(Hr,Gt)=>{if(Hr||d.aborted||!Gt.length)return G();(c(Gt)||Jud).then(()=>{let An=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Bt(An,It,Gt,cr),G()})}))},jr=async(It,cr)=>{J(),mCa.default.realpath(It,(Hr,Gt)=>{if(Hr||d.aborted)return G();mCa.default.stat(Gt,async(wn,An)=>{if(wn||d.aborted)return G();let Ht=u1i.default.basename(Gt),er=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Ct(er,Gt,Ht,An,cr),G()})})};return(async(It,cr=1)=>(It=u1i.default.normalize(It),C.add(It),or(It,cr),await ee,d.aborted?F:K))(e)},Xud=m8w;var hLt={lang:{debounce:gCa,attempt:e=>{try{return e()}catch(t){return hLt.lang.castError(t)}},castArray:e=>hLt.lang.isArray(e)?e:[e],castError:e=>hLt.lang.isError(e)?e:hLt.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(hLt.lang.isNaN(e))return hLt.lang.isNaN(t);if(hLt.lang.isPrimitive(e)||hLt.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(OCa.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Z6u.default.realpathSync.native(e):Z6u.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===OCa.default.sep&&t.length-e.length>OCa.default.sep.length,poll:(e,t=Uud)=>Qud.retry.stat(t)(e,{bigint:!0}).catch(hLt.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await Xud(e,{depth:r,limit:n,ignore:t,signal:i});return[u.directories,u.files]}}}},yw=hLt;var PCa=Yo(require("path"),1);var k6u=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||yw.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=Rud){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,a=async(f,d)=>{let c=this.options.ignoreInitial?[]:f,o=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...c,...o]);this.onTargetEvents(l)},u=yw.lang.debounce(()=>{this.watcher.isClosed()||(r=a(n,i),n=[],i=new Set)},t);return async(f,d="",c=!1)=>{c?await this.eventsPopulate([d],n,!0):i.add(d),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[a,u]=i,f=r[u];return a===f||a===Lm.CHANGE&&f===Lm.ADD||(r[u]=a,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let a=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,i]),u===Lm.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):u===Lm.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let a=this.options.recursive?this.options.depth??bRr:Math.min(1,this.options.depth??bRr),u=this.options.limit??i1i,[f,d]=await yw.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),c=[...f,...d];return await Promise.all(c.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let a of this.watcher._poller.stats.keys())yw.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Lm.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!gRr&&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(Lm.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Lm.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(PCa.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Lm.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(PCa.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(Lm.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Lm.ADD?this.onTargetAdd(n):r===Lm.ADD_DIR?this.onTargetAddDir(n):r===Lm.CHANGE?this.onTargetChange(n):r===Lm.UNLINK?this.onTargetUnlink(n):r===Lm.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=Ean.CHANGE,r){if(this.watcher.isClosed())return;let n=PCa.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){J6u&&t.code==="EPERM"?this.onWatcherChange(Ean.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(a1i.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(a1i.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Ean.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&gRr&&this.options.native!==!1?this.options.depth??bRr:Math.min(1,this.options.depth??bRr),n=this.options.limit??i1i,[i,a]=await yw.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...i,...a];await Promise.all(u.map(f=>{if(!this.watcher._poller.stats.has(f)&&!this.watcher.isIgnored(f,this.options.ignore))return this.onWatcherEvent(Ean.CHANGE,f,t)}))}}},Zud=k6u;var Tk={interval:100,intervalId:void 0,fns:new Map,init:()=>{Tk.intervalId||(Tk.intervalId=setInterval(Tk.resolve,Tk.interval))},reset:()=>{Tk.intervalId&&(clearInterval(Tk.intervalId),delete Tk.intervalId)},add:(e,t)=>{Tk.fns.set(e,Date.now()+t),Tk.init()},remove:e=>{Tk.fns.delete(e)},resolve:()=>{if(!Tk.fns.size)return Tk.reset();let e=Date.now();for(let[t,r]of Tk.fns)r>=e||(Tk.remove(t),t())}},s1i=Tk;var c1i=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=G6u){let{ino:n,targetPath:i,events:a,locks:u}=t,f=()=>{let l=this._watcher._poller.paths.find(n||-1,g=>g!==i);if(l&&l!==i){if(yw.fs.getRealPath(i,!0)===l)return;this._watcher.event(a.rename,l,i)}else this._watcher.event(a.add,i)};if(!n)return f();let d=()=>{u.add.delete(n),s1i.remove(c)},c=()=>{d(),f()};s1i.add(c,r);let o=()=>{let l=u.unlink.get(n);if(!l)return;d();let g=l();i===g?a.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(a.change,i):this._watcher.event(a.rename,g,i)};u.add.set(n,o),o()}getLockUnlink(t,r=G6u){let{ino:n,targetPath:i,events:a,locks:u}=t,f=()=>{this._watcher.event(a.unlink,i)};if(!n)return f();let d=()=>{u.unlink.delete(n),s1i.remove(c)},c=()=>{d(),f()};s1i.add(c,r);let o=()=>(d(),i);u.unlink.set(n,o),u.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Lm.ADD,pLt.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,Lm.ADD_DIR,pLt.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,Lm.UNLINK,pLt.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,Lm.UNLINK_DIR,pLt.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}}};c1i.DIR_EVENTS={add:Lm.ADD_DIR,rename:Lm.RENAME_DIR,unlink:Lm.UNLINK_DIR};c1i.FILE_EVENTS={add:Lm.ADD,change:Lm.CHANGE,rename:Lm.RENAME,unlink:Lm.UNLINK};var kud=c1i;var eIu=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(yw.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(yw.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(yw.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(yw.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return yw.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);yw.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},tIu=eIu;var rIu=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}},esd=rIu;var nIu=class{constructor(){this.inos={},this.paths=new tIu,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let a=i[t];if(a&&!(n&&a[1]!==n))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await yw.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new esd(n)}reset(){this.inos={},this.paths=new tIu,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,Lm.ADD,i),[Lm.ADD];if(i.isDirectory())return this.updateIno(t,Lm.ADD_DIR,i),[Lm.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Lm.UNLINK,n),[Lm.UNLINK];if(n.isDirectory())return this.updateIno(t,Lm.UNLINK_DIR,n),[Lm.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Lm.CHANGE,i),[Lm.CHANGE]);if(i.isDirectory())return this.updateIno(t,Lm.UNLINK,n),this.updateIno(t,Lm.ADD_DIR,i),[Lm.UNLINK,Lm.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Lm.UNLINK_DIR,n),this.updateIno(t,Lm.ADD,i),[Lm.UNLINK_DIR,Lm.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Lm.UNLINK_DIR,n),this.updateIno(t,Lm.ADD_DIR,i),[Lm.UNLINK_DIR,Lm.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=n.isFile()?pLt.FILE:pLt.DIR;i[t]=[n.ino,a]}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)}}},iIu=nIu;var aIu=class e extends tsd.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(xk.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(xk.CLOSE,i)),this._readyWait=new Promise(i=>this.on(xk.READY,i)),this._locker=new kud(this),this._roots=new Set,this._poller=new iIu,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&&(yw.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(xk.CLOSE))}error(t){if(this.isClosed())return!1;let r=yw.lang.castError(t);return this.emit(xk.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(xk.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(xk.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&yw.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&yw.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 a of[...i])r&&a.filePath!==r||this.watcherClose(a);if(n)for(let a in this._watchers)yw.fs.isSubPath(t,a)&&this.watchersClose(a,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 a=new Zud(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=yw.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(f=>f.handler===n&&(!f.filePath||f.filePath===i)&&f.options.ignore===r.ignore&&!!f.options.native==!!r.native&&(!r.recursive||f.options.recursive)))return!0;let u=Aan.default.dirname(t);for(let f=1;f<1/0;f++){if(this._watchers[u]?.find(o=>(f===1||o.options.recursive&&f<=(o.options.depth??bRr))&&o.handler===n&&(!o.filePath||o.filePath===i)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&gRr&&o.options.native!==!1)))return!0;if(!gRr)break;let c=Aan.default.dirname(t);if(u===c)break;u=c}return!1}async watchDirectories(t,r,n,i,a){if(this.isClosed())return;t=yw.lang.uniq(t).sort();let u;for(let f of t)if(!this.isIgnored(f,r.ignore)&&!this.watcherExists(f,r,n,i))try{let d=!r.recursive||gRr&&r.native!==!1?r:{...r,recursive:!1},o={watcher:wCa.default.watch(f,d),handler:n,options:r,folderPath:f,filePath:i},l=u=await this.watcherAdd(o,a);if(this._roots.has(i||f)){let O={...r,ignoreInitial:!0,recursive:!1},P=Aan.default.dirname(f),j=f;await this.watchDirectories([P],O,n,j,l)}}catch(d){this.error(d)}return u}async watchDirectory(t,r,n,i,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||gRr&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,a));{r={...r,recursive:!0};let u=r.depth??bRr,f=r.limit??i1i,[d]=await yw.fs.readdir(t,r.ignore,u,f,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let c=await this.watchDirectories([t],r,n,i,a);if(d.length){let o=yw.fs.getDepth(t);for(let l of d){let g=yw.fs.getDepth(l),O=Math.max(0,u-(g-o)),P={...r,depth:O};await this.watchDirectories([l],P,n,i,a||c)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},a=(c,o)=>{o===t&&(d(),n())},u=new e(a),f=()=>{this._subwatchers.add(i),this.on(xk.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(i),this.removeListener(xk.CLOSE,d),u.close()};return f()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=Aan.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,a=new iIu,u=await this.watchPolling(t,r,async()=>{i||!(await a.update(t,r.pollingTimeout)).length||i||(i=!0,u(),n())})}async watchPolling(t,r,n){if(this.isClosed())return yw.lang.noop;if(this.pollerExists(t,r))return yw.lang.noop;let i={...r,interval:r.pollingInterval??Lud},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(xk.CLOSE,f),wCa.default.watchFile(t,i,n)},f=()=>{this._pollers.delete(a),this.removeListener(xk.CLOSE,f),wCa.default.unwatchFile(t,n)};return yw.lang.attempt(u),()=>yw.lang.attempt(f)}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=yw.lang.uniq(t).sort(),t.every((a,u)=>t.every((f,d)=>d===u||!yw.fs.isSubPath(a,f))))await Promise.all(t.map(a=>this.watchPath(a,r,n)));else for(let a of t)await this.watchPath(a,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=Aan.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await yw.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 a=Aan.default.dirname(t);return(await yw.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=yw.lang.noop){if(yw.lang.isFunction(t))return this.watch([],{},t);if(yw.lang.isUndefined(t))return this.watch([],r,n);if(yw.lang.isFunction(r))return this.watch(t,{},r);if(yw.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=yw.lang.castArray(t);i.forEach(a=>this._roots.add(a)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==yw.lang.noop&&this.on(xk.ALL,n),r.readdirMap=void 0,this.ready())}},rsd=aIu;var x5w=Yo(osd(),1),T5w=Yo(yIu(),1),C5w=Yo(bIu(),1),q5w=Yo(DIu(),1),EIu=Yo(ncd(),1);var j0d=Yo(g2a(),1),CLt=require("fs/promises"),Qqa=require("os"),d3u=Yo(require("path"),1),D0d=Yo(Nne(),1),S0d=Yo(Mpd(),1),p3u=Yo(f3u(),1),DJw="etag",_3u="preview",SJw="bundle",h3u=".fern";function EJw(){return yf(v_.of((0,Qqa.homedir)()),Ms.of(h3u),Ms.of(_3u))}function Jqa(){return yf(v_.of((0,Qqa.homedir)()),Ms.of(h3u),Ms.of(_3u),Ms.of(SJw))}function AJw(){return yf(v_.of((0,Qqa.homedir)()),Ms.of(h3u),Ms.of(_3u),Ms.of(DJw))}async function E0d({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let n=await(0,p3u.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!n.ok)return{type:"failure"};let i=n.body,u=await new S0d.default.Parser().parseStringPromise(i),f=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],d=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=AJw();if(r){let B=await Wh(c),I;if(B&&(t.debug("Reading existing ETag"),I=(await(0,CLt.readFile)(c)).toString()),I!=null&&I===f)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle")}t.debug("Creating tmp directory to download docs preview bundle");let o=await D0d.default.dir({prefix:"fern"}),l=v_.of(o.path);t.debug(`Downloading docs preview bundle from ${d3u.default.join(e,d)}`);let g=await(0,p3u.fetcher)({url:`${d3u.default.join(e,d)}`,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!g.ok)return t.error("Failed to download docs preview bundle."),{type:"failure"};let O=yf(l,Ms.of("output.zip")),P=g.body;if(P==null)return{type:"failure"};let j=Buffer.from(P);await(0,CLt.writeFile)(O,j),t.debug(`Wrote output.zip to ${O}`);let M=EJw();await Wh(M)&&await(0,CLt.rm)(M,{recursive:!0}),await(0,CLt.mkdir)(M,{recursive:!0}),t.debug(`rm -rf ${M}`);let q=Jqa();return await(0,CLt.mkdir)(q,{recursive:!0}),await(0,j0d.default)(O,q),await(0,CLt.writeFile)(c,f),t.debug(`Downloaded bundle to ${q}`),{type:"success"}}async function A0d({domain:e,project:t,context:r}){let n=t.docsWorkspaces,i=t.apiWorkspaces;if(n==null)throw new Error("No docs workspace found in project");let a=await Promise.all(i.map(async g=>await g.toFernWorkspace({context:r},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),u=new y3u(r),f={},c=await new yMr(e,n,a,r,void 0,async g=>g.map(O=>{let P=a8r();return f[P]={type:"url",url:Yc.Url(`/_local${bXo(O.absoluteFilePath)}`)},{absoluteFilePath:O.absoluteFilePath,relativeFilePath:O.relativeFilePath,fileId:P}}),async g=>u.addReferencedAPI(g)).resolve(),o=W2u({writeShape:c,files:{}}),l=Q2u({dbShape:o.config});return{apis:u.getAPIsForDefinition(),config:l,files:{},filesV2:f,pages:o.pages,search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0}}var y3u=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:n}){try{let i=a8r(),a=sPi(WDe({ir:t,snippetsConfig:r,playgroundConfig:n}),MU.ApiDefinitionId(i),new uan({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=fPi(a);return this.apis[i]=u,i}catch(i){let a=i;throw this.context.logger.error(`Failed to read referenced API: ${a?.message} ${a?.stack}`),a.stack!=null&&this.context.logger.error(a?.stack),i}}getAPIsForDefinition(){return this.apis}};var MJw={pages:{},apis:{},files:{},filesV2:{},config:{navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0,playground:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function b3u({initialProject:e,reloadProject:t,validateProject:r,context:n,port:i,bundlePath:a}){if(a!=null)n.logger.info(`Using bundle from path: ${a}`);else try{let I="https://prod-local-preview-bundle2.s3.amazonaws.com/";if(I==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await E0d({bucketUrl:I,logger:n.logger,preferCached:!0})}catch(I){let C=Jqa();if(I instanceof Error&&n.logger.debug(`Failed to download latest docs bundle: ${I.message}`),await Wh(C))n.logger.warn("Falling back to cached bundle...");else{n.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=cb(e.config._absolutePath),f=(0,v3u.default)(),d=x0d.default.createServer(f),c=new EIu.default({server:d}),o=new Set;function l(I){for(let C of o)C.send(JSON.stringify(I))}c.on("connection",function(C){o.add(C),C.on("close",function(){o.delete(C)})}),f.use((0,M0d.default)());let g=new URL(hMr(e.docsWorkspaces?.config.instances[0]?.url??`localhost:${i}`)),O=e,P,j=async()=>{n.logger.info("Reloading docs...");let I=Date.now();try{O=await t(),n.logger.info("Validating docs..."),await r(O);let C=await A0d({domain:`${g.host}${g.pathname}`,project:O,context:n});return n.logger.info(`Reload completed in ${Date.now()-I}ms`),C}catch(C){return P==null?n.logger.error("Failed to read docs configuration. Rendering blank page."):n.logger.error("Failed to read docs configuration. Rendering last successful configuration."),C instanceof Error&&C instanceof Error&&C.stack&&n.logger.debug(`${C.message}
1990
+ `)}]:t.flatMap((c,o)=>iQ({rawTypeReference:f,example:c,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:[...u,`${o}`]}))},optional:f=>t==null?[]:iQ({rawTypeReference:f,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a,breadcrumbs:u}),unknown:()=>[],literal:f=>{switch(f.type){case"boolean":return LDe(d=>d===f.boolean,f.boolean.toString())(t);case"string":return LDe(d=>d===f.string,`"${f.string}"`)(t);default:Lc(f)}}}})}function tqw({primitiveType:e,example:t}){return e.v2!=null?kA._visit(e.v2,{integer:r=>rqw({example:t,rules:r.validation}),long:()=>rrd(t),uint:()=>ktd(t),uint64:()=>erd(t),double:r=>nqw({example:t,rules:r.validation}),float:()=>trd(t),boolean:()=>nrd(t),string:r=>iqw({example:t,rules:r.validation}),uuid:()=>ird(t),date:()=>ord(t),dateTime:()=>ard(t),base64:()=>S8n(t),bigInteger:()=>S8n(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):vP._visit(e.v1,{integer:()=>srd(t),long:()=>rrd(t),uint:()=>ktd(t),uint64:()=>erd(t),double:()=>crd(t),float:()=>trd(t),boolean:()=>nrd(t),string:()=>S8n(t),uuid:()=>ird(t),dateTime:()=>ard(t),date:()=>ord(t),base64:()=>S8n(t),bigInteger:()=>S8n(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function rqw({example:e,rules:t}){let r=srd(e);if(r.length>0||t==null)return r;let n=e;return t.min!=null&&(t.exclusiveMin&&n<=t.min||!t.exclusiveMin&&n<t.min)?[{message:`Expected integer to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&n>=t.max||!t.exclusiveMax&&n>t.max)?[{message:`Expected integer to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&n%t.multipleOf!==0?[{message:`Expected integer to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function nqw({example:e,rules:t}){let r=crd(e);if(r.length>0||t==null)return r;let n=e;return t.min!=null&&(t.exclusiveMin&&n<=t.min||!t.exclusiveMin&&n<t.min)?[{message:`Expected double to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&n>=t.max||!t.exclusiveMax&&n>t.max)?[{message:`Expected double to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&n%t.multipleOf!==0?[{message:`Expected double to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function iqw({example:e,rules:t}){let r=S8n(e);if(r.length>0||t==null)return r;let n=e;return t.minLength!=null&&n.length<t.minLength?[{message:`Expected string length to be greater than or equal to ${t.minLength}. Example is ${e}, which is of length ${n.length}.`}]:t.maxLength!=null&&n.length>t.maxLength?[{message:`Expected string length to be less than or equal to ${t.maxLength}. Example is ${e}, which is of length ${n.length}.`}]:t.pattern!=null&&!new RegExp(t.pattern).test(n)?[{message:`Expected string to match pattern ${t.pattern}. Example is ${e}.`}]:[]}var S8n=LDe(e=>typeof e=="string","a string"),srd=LDe(e=>Number.isInteger(e),"an integer"),ktd=LDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),erd=LDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),trd=LDe(e=>typeof e=="number","a float"),crd=LDe(e=>typeof e=="number","a double"),rrd=LDe(e=>Number.isInteger(e),"an integer"),nrd=LDe(e=>typeof e=="boolean","a boolean"),ird=LDe(e=>typeof e=="string"&&k2w.test(e),"a UUID"),ard=LDe(e=>typeof e=="string"&&urd.test(e),"an ISO 8601 timestamp"),ord=LDe(e=>typeof e=="string"&&eqw.test(e)&&urd.test(e),"a date");function LDe(e,t){return r=>e(r)?[]:F2e(r,t)}function CPi({expected:e,actual:t}){if(e._type==="unknown")return!0;if(e._type==="primitive")return t._type==="primitive"&&e.primitive.v1===t.primitive.v1;if(e._type==="container")switch(e.container._type){case"list":case"set":return t._type==="container"&&t.container._type===e.container._type&&CPi({expected:e.container.itemType,actual:t.container.itemType});case"optional":return CPi({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"map":return t._type==="container"&&t.container._type===e.container._type&&CPi({expected:e.container.keyType,actual:t.container.keyType})&&CPi({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:aqw({expected:e.container.literal,actual:t.container.literal});default:Lc(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;Lc(e)}function aqw({expected:e,actual:t}){switch(e.type){case"boolean":return t.type==="boolean"?e.boolean===t.boolean:!1;case"string":return t.type==="string"?e.string===t.string:!1;default:Lc(e)}}async function STa({_enum:e,file:t}){let r=await Promise.all(e.enum.map(async i=>({...await Z$(i),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof i=="string"?i:i.value,name:E8n(i).name,opts:{casingOverrides:typeof i!="string"?i.casing:void 0}})}))),n;if(e.default!=null&&(n=r.find(i=>i.name.wireValue===e.default),n==null))throw new Error(`Default value ${e.default} not found in enum values`);return{default:n,values:r}}function lrd(e,t){let r=t.enum.find(n=>typeof n=="string"?!1:n.value===e);return{name:typeof r=="string"?e:r?.name??e,wasExplicitlySet:!1}}function E8n(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function Tqu({typeName:e,typeDeclaration:t,example:r,typeResolver:n,exampleResolver:i,fileContainingType:a,fileContainingExample:u,workspace:f}){return zz(t,{alias:d=>dS.alias({value:lT({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f})}),object:d=>frd({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f}),discriminatedUnion:d=>{let c=han(d);if(!lS(r))throw new Error("Example is not an object");let o=r[c];if(o==null)throw new Error("Example is missing discriminant: "+c);if(typeof o!="string")throw new Error("Discriminant value is not a string");let l=d.union[o];if(l==null)throw new Error(`${o} is not one of the specified discriminant values.`);let g=typeof l=="string"?l:typeof l.type=="string"?l.type:void 0;return dS.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:cRr(d).name,wireValue:c}),singleUnionType:uqw({rawValueType:g,rawSingleUnionType:l,fileContainingType:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,example:r,discriminant:c,discriminantValueForExample:o,workspace:f})})},enum:d=>{if(typeof r!="string")throw new Error("Enum example is not a string");return dS.enum({value:u.casingsGenerator.generateNameAndWireValue({name:lrd(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,o]of d.union.entries())if(iQ({rawTypeReference:typeof o=="string"?o:o.type,example:r,typeResolver:n,exampleResolver:i,file:a,workspace:f,breadcrumbs:[]}).length===0)return dS.undiscriminatedUnion({index:c,singleUnionType:lT({example:r,rawTypeBeingExemplified:typeof o=="string"?o:o.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:n,exampleResolver:i,workspace:f})});throw new Error("Example doesn't match any of the undiscriminated unions")}})}function lT({example:e,fileContainingExample:t,rawTypeBeingExemplified:r,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}){let{resolvedExample:f,file:d}=a.resolveExampleOrThrow({example:e,file:t}),c=a.resolveAllReferencesInExampleOrThrow({example:e,file:t}).resolvedExample;return{shape:Dtn({type:r,_default:void 0,validation:void 0,visitor:{primitive:l=>oqw({example:f,typeBeingExemplified:l.v1}),map:({keyType:l,valueType:g})=>{if(!lS(f))throw new Error("Example is not an object");return dO.container(gA.map({map:Object.entries(f).map(([O,P])=>({key:lT({example:O,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}),value:lT({example:P,fileContainingExample:d,rawTypeBeingExemplified:g,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})})),keyType:n.parseTypeReference(l),valueType:n.parseTypeReference(g)}))},list:l=>{if(!Array.isArray(f))throw new Error("Example is not a list");return dO.container(gA.list({list:f.map(g=>lT({example:g,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})),itemType:n.parseTypeReference(l)}))},set:l=>{if(!Array.isArray(f))throw new Error("Example is not a list");return dO.container(gA.set({set:f.map(g=>lT({example:g,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u})),itemType:n.parseTypeReference(l)}))},optional:l=>dO.container(gA.optional({optional:f!=null?lT({example:f,fileContainingExample:d,rawTypeBeingExemplified:l,fileContainingRawTypeReference:n,typeResolver:i,exampleResolver:a,workspace:u}):void 0,valueType:n.parseTypeReference(l)})),literal:l=>{switch(l.type){case"boolean":return dO.container(gA.literal({literal:Pv.boolean(l.boolean)}));case"string":return dO.container(gA.literal({literal:Pv.string({original:l.string})}));default:Lc(l)}},named:l=>{let g=i.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:r,file:n}),O=n.parseTypeReference(l);if(O.type!=="named")throw new Error("Type reference is not to a named type.");let P={typeId:O.typeId,fernFilepath:O.fernFilepath,name:O.name};return dO.named({typeName:P,shape:Tqu({typeName:P,typeDeclaration:g.declaration,fileContainingType:g.file,fileContainingExample:d,example:f,typeResolver:i,exampleResolver:a,workspace:u})})},unknown:()=>dO.unknown(c)}}),jsonExample:c}}function oqw({example:e,typeBeingExemplified:t}){return vP._visit(t,{string:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},dateTime:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.datetime({datetime:new Date(e),raw:e}))},date:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.date(e))},base64:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},uint:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.uint(e))},uint64:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.uint64(e))},integer:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.integer(e))},float:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.float(e))},double:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.double(e))},long:()=>{if(typeof e!="number")throw new Error("Example is not a number");return dO.primitive(Pv.long(e))},boolean:()=>{if(typeof e!="boolean")throw new Error("Example is not a boolean");return dO.primitive(Pv.boolean(e))},uuid:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.uuid(e))},bigInteger:()=>{if(typeof e!="string")throw new Error("Example is not a string");return dO.primitive(Pv.string({original:e}))},_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function frd({typeName:e,rawObject:t,example:r,fileContainingType:n,fileContainingExample:i,typeResolver:a,exampleResolver:u,workspace:f}){if(!lS(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return dS.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[c,o])=>{let l=drd({typeName:e,wirePropertyKey:c,rawObject:t,typeResolver:a,file:n});if(l==null)throw new Error("Could not find original type declaration for property: "+c);let g=lT({example:o,fileContainingExample:i,rawTypeBeingExemplified:typeof l.rawPropertyType=="string"?l.rawPropertyType:l.rawPropertyType.type,fileContainingRawTypeReference:l.file,typeResolver:a,exampleResolver:u,workspace:f});return d.push({name:i.casingsGenerator.generateNameAndWireValue({name:nQ({propertyKey:c,property:l.rawPropertyType}).name,wireValue:c}),value:g,originalTypeDeclaration:l.typeName}),d},[]):[]})}function drd({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:n,file:i}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:i}:qPi({wirePropertyKey:t,extends_:r.extends,typeResolver:n,file:i})}function qPi({wirePropertyKey:e,extends_:t,typeResolver:r,file:n}){if(t!=null){let i=typeof t=="string"?[t]:t;for(let a of i){let u=r.resolveNamedTypeOrThrow({referenceToNamedType:a,file:n});if(u._type!=="named"||!mA(u.declaration))throw new Error("Extension is not of a named object");let f=drd({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(f!=null)return f}}}function uqw({rawValueType:e,rawSingleUnionType:t,fileContainingType:r,fileContainingExample:n,typeResolver:i,exampleResolver:a,example:u,discriminant:f,discriminantValueForExample:d,workspace:c}){let o=n.casingsGenerator.generateNameAndWireValue({name:D8n({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:Bz.noProperties()};let l=xqu({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:i});switch(l.propertiesType){case"singleProperty":{if(!lS(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:Bz.singleProperty(lT({example:u[l.name.wireValue],rawTypeBeingExemplified:e,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:n,workspace:c}))}}case"samePropertiesAsObject":{if(!lS(u))throw new Error("Example is not an object");let{[f]:g,...O}=u,P=i.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});if(!mA(P.declaration))throw new Error(`${e} is not an object`);let j={typeId:l.typeId,fernFilepath:l.fernFilepath,name:l.name};return{wireDiscriminantValue:o,shape:Bz.samePropertiesAsObject({typeId:s1.generateTypeId(j),object:frd({rawObject:P.declaration,example:O,fileContainingType:P.file,fileContainingExample:n,typeResolver:i,exampleResolver:a,typeName:j,workspace:c})})}}default:Lc(l)}}async function ETa({file:e,queryParameterKey:t,queryParameter:r}){let{name:n}=_Mr({queryParameterKey:t,queryParameter:r}),i=e.parseTypeReference(r);return{...await Z$(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:n}),valueType:i,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1}}function _Mr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function sqw(e){let t=JSON.stringify(e);return prd.default.createHash("sha256").update(t).digest("hex")}function _rd({service:e,endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,variableResolver:u,file:f,workspace:d}){let c=lqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:a,variableResolver:u,file:f,workspace:d});return{id:r.name??sqw(r),name:r.name!=null?f.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:hqw({file:f,service:e,endpoint:t,example:r,pathParams:c}),...c,...fqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:a,file:f,workspace:d}),queryParameters:r["query-parameters"]!=null?Object.entries(r["query-parameters"]).map(([o,l])=>{let g=typeof t.request!="string"?t.request?.["query-parameters"]?.[o]:void 0;if(g==null)throw new Error(`Query parameter ${o} does not exist`);return{name:f.casingsGenerator.generateNameAndWireValue({name:_Mr({queryParameterKey:o,queryParameter:g}).name,wireValue:o}),value:lT({example:l,rawTypeBeingExemplified:typeof g=="string"?g:g.type,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:f,fileContainingExample:f,workspace:d}),shape:cqw({queryParameter:g})}}):[],request:dqw({endpoint:t,example:r,typeResolver:n,exampleResolver:a,file:f,workspace:d}),response:pqw({endpoint:t,example:r,typeResolver:n,errorResolver:i,exampleResolver:a,file:f,workspace:d})}}function cqw({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?NF.exploded():NF.single()}function lqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:i,variableResolver:a,file:u,workspace:f}){let d=[],c=[],o=[],l=({name:g,pathParameterDeclaration:O,examplePathParameter:P})=>{let j=IPi({parameter:O,variableResolver:a,file:u});return{name:g,value:lT({example:P,rawTypeBeingExemplified:j.rawType,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:j.file,fileContainingExample:u,workspace:f})}};if(r["path-parameters"]!=null)for(let[g,O]of Object.entries(r["path-parameters"])){let P=u.rootApiFile["path-parameters"]?.[g],j=e["path-parameters"]?.[g],M=t["path-parameters"]?.[g];if(P!=null)d.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:P,examplePathParameter:O}));else if(M!=null)o.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:M,examplePathParameter:O}));else if(j!=null)c.push(l({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:j,examplePathParameter:O}));else throw new Error(`Path parameter ${g} does not exist`)}return{rootPathParameters:d,endpointPathParameters:o,servicePathParameters:c}}function fqw({service:e,endpoint:t,example:r,typeResolver:n,exampleResolver:i,file:a,workspace:u}){let f=[],d=[];if(r.headers!=null)for(let[c,o]of Object.entries(r.headers)){let l=typeof t.request!="string"?t.request?.headers?.[c]:void 0,g=e.headers?.[c];if(l!=null)d.push({name:a.casingsGenerator.generateNameAndWireValue({name:sLt({headerKey:c,header:l}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else if(g!=null)f.push({name:a.casingsGenerator.generateNameAndWireValue({name:sLt({headerKey:c,header:g}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof g=="string"?g:g.type,typeResolver:n,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else throw new Error(`Header ${c} does not exist`)}return{endpointHeaders:d,serviceHeaders:f}}function dqw({endpoint:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=typeof e.request!="string"?e.request?.body:e.request;if(u==null||typeof u=="string"&&syi(u)!=null)return;if(!v6(u))return b$.reference(lT({example:t.request,rawTypeBeingExemplified:typeof u!="string"?u.type:u,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}));if(!t.request)return;if(!lS(t.request))throw new Error(`Example is not an object. Got: ${JSON.stringify(t.request)}`);let f=[];for(let[d,c]of Object.entries(t.request)){let o=u.properties?.[d],l=typeof o=="string"?o:o?.type;if(!(l!=null&&ACe(l)!=null))if(o!=null)f.push({name:i.casingsGenerator.generateNameAndWireValue({name:nQ({propertyKey:d,property:o}).name,wireValue:d}),value:lT({example:c,rawTypeBeingExemplified:typeof o!="string"?o.type:o,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),originalTypeDeclaration:void 0});else{let g=qPi({extends_:u.extends,wirePropertyKey:d,typeResolver:r,file:i});if(g==null)throw new Error("Could not find original type declaration for property: "+d);f.push({name:i.casingsGenerator.generateNameAndWireValue({name:nQ({propertyKey:d,property:g.rawPropertyType}).name,wireValue:d}),value:lT({example:c,rawTypeBeingExemplified:typeof g.rawPropertyType=="string"?g.rawPropertyType:g.rawPropertyType.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:g.file,fileContainingExample:i,workspace:a}),originalTypeDeclaration:g.typeName})}}return b$.inlinedRequestBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t.request,file:i}).resolvedExample,properties:f})}function pqw({endpoint:e,example:t,typeResolver:r,errorResolver:n,exampleResolver:i,file:a,workspace:u}){return t.response==null?T4.ok(cN.body(void 0)):Etn(e,t.response,{body:f=>{if(f.error!=null){let d=n.getDeclarationOrThrow(f.error,a);return T4.error({error:uRr({errorName:f.error,file:a}),body:d.declaration.type!=null?lT({example:f.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return T4.ok(cN.body(_qw({endpoint:e,example:f,typeResolver:r,exampleResolver:i,file:a,workspace:u})))},stream:f=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return T4.ok(cN.stream(f.stream.map(c=>{if(d!=null)return lT({example:c,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter($M)))},events:f=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return T4.ok(cN.sse(f.stream.map(({event:c,data:o})=>{if(d==null)return;let l=lT({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:c,data:l}}).filter($M)))}})}function _qw({endpoint:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=typeof e.response!="string"?e.response?.type:e.response;if(u!=null&&t.body!=null)return lT({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a})}function hqw({file:e,service:t,endpoint:r,example:n,pathParams:i}){let a=k1(e.rootApiFile["base-path"]??"",t["base-path"],r.path);if(n["path-parameters"]!=null)for(let u of[...i.endpointPathParameters,...i.servicePathParameters,...i.rootPathParameters])a=a.replaceAll(`{${u.name.originalName}}`,`${u.value.jsonExample}`);return a=a.replaceAll("//","/"),a.startsWith("/")||(a=`/${a}`),a}async function hrd({endpoint:e,file:t,typeResolver:r}){return{body:await yqw({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}async function yqw({endpoint:e,file:t,typeResolver:r}){let n=await vqw({endpoint:e,file:t,typeResolver:r}),i=await bqw({endpoint:e,file:t,typeResolver:r});if(n!=null&&i!=null){let a;switch(n.type){case"fileDownload":{a=Fie.fileDownload({...n});break}case"json":{a=Fie.json({...n.value});break}case"text":{a=Fie.text({...n});break}default:Lc(n)}return A3.streamParameter({nonStreamResponse:a,streamResponse:i})}else{if(n!=null)return n;if(i!=null)return A3.streaming(i)}}async function vqw({endpoint:e,file:t,typeResolver:r}){let{response:n}=e;if(n!=null){let i=typeof n!="string"?n.docs:void 0,a=typeof n=="string"?n:n.type;return ACe(a)!=null?A3.fileDownload({docs:i}):cyi(a)!=null?A3.text({docs:i}):await gqw(n,i,t,r)}}async function bqw({endpoint:e,file:t,typeResolver:r}){let{["response-stream"]:n}=e;if(n!=null){let i=typeof n!="string"?n.docs:void 0,a=typeof n=="string"?n:n.type,u=typeof n=="string"?"json":n.format??"json";return C6n(a)?Lie.text({docs:i}):typeof n!="string"&&u==="sse"?Lie.sse({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0}):Lie.json({docs:i,payload:t.parseTypeReference(a),terminator:typeof n!="string"?n.terminator:void 0})}}async function gqw(e,t,r,n){let i=r.parseTypeReference(e),a=n.resolveTypeOrThrow({type:typeof e!="string"?e.type:e,file:r}),u=typeof e!="string"?e.property:void 0;return u!=null?A3.json(N6t.nestedPropertyAsResponse({docs:t,responseBodyType:i,responseProperty:await MPi({typeResolver:n,file:r,resolvedType:a,property:u})})):A3.json(N6t.response({docs:t,responseBodyType:i}))}async function yrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return PCe.cursor({page:await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.cursor}),next:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.next_cursor}),results:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results})})}async function vrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:i}){return PCe.offset({page:await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.offset}),results:await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results}),step:i.step!=null?await e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i.step}):void 0,hasNextPage:i.hasNextPage!=null?await e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.hasNextPage}):void 0})}function brd(e){return mqw(e)?{type:"offset",offset:HIt(e.offset),results:dMr(e.results),step:e.step!=null?HIt(e.step):void 0,hasNextPage:e["has-next-page"]!=null?dMr(e["has-next-page"]):void 0}:{type:"cursor",cursor:HIt(e.cursor),next_cursor:dMr(e.next_cursor),results:dMr(e.results)}}function mqw(e){return e.offset!=null&&e.results!=null}async function grd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n}){let i=typeof n.pagination=="boolean"?t.rootApiFile.pagination:n.pagination;if(!i)return;let a=brd(i);switch(a.type){case"cursor":return await yrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});case"offset":return vrd({propertyResolver:e,file:t,endpointName:r,endpointSchema:n,paginationPropertyComponents:a});default:Lc(a)}}function mrd({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let n=typeof r=="string"?r:r.error,i=uRr({errorName:n,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:i}})}function ATa({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function Ord({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:ATa({source:e}),name:sRr.generateName(r)}}async function Prd({file:e,serviceDeclaration:t,sourceResolver:r}){if(t.source==null)return gCe.http();let n=await r.resolveSourceOrThrow({source:t.source,file:e});if(n==null||n.type!=="protobuf")return gCe.http();let i=Ord({source:n,serviceNameOverride:t.transport?.grpc?.["service-name"]});if(i==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return gCe.grpc({service:i})}async function wrd({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:n,errorResolver:i,typeResolver:a,propertyResolver:u,exampleResolver:f,variableResolver:d,sourceResolver:c,globalErrors:o,workspace:l}){let g=await A8n({pathParameters:r["path-parameters"],location:mCe.Service,file:n,variableResolver:d}),O=await Prd({file:n,serviceDeclaration:r,sourceResolver:c}),P={fernFilepath:n.fernFilepath};return{availability:Dae(r.availability),name:P,displayName:r["display-name"]??void 0,basePath:R2e(r["base-path"]),headers:r.headers!=null?await Promise.all(Object.entries(r.headers).map(([M,q])=>L2e({headerKey:M,header:q,file:n}))):[],pathParameters:g,encoding:jqw(O),transport:O,endpoints:await Promise.all(Object.entries(r.endpoints).map(async([M,q])=>{let B=await A8n({pathParameters:q["path-parameters"],location:mCe.Endpoint,file:n,variableResolver:d}),I={...await Z$(q),id:"",name:n.casingsGenerator.generateName(M),displayName:q["display-name"],auth:q.auth??r.auth,idempotent:q.idempotent??r.idempotent??!1,baseUrl:q.url??r.url??e,method:q.method!=null?wqw(q.method):zie.Post,basePath:q["base-path"]!=null?R2e(q["base-path"]):void 0,path:R2e(q.path),fullPath:R2e(q["base-path"]!=null?k1(q["base-path"],q.path):n.rootApiFile["base-path"]!=null?k1(n.rootApiFile["base-path"],r["base-path"],q.path):k1(r["base-path"],q.path)),pathParameters:B,allPathParameters:q["base-path"]!=null?B:[...t,...g,...B],queryParameters:typeof q.request!="string"&&q.request?.["query-parameters"]!=null?await Promise.all(Object.entries(q.request["query-parameters"]).map(async([C,F])=>await ETa({file:n,queryParameterKey:C,queryParameter:F}))):[],headers:typeof q.request!="string"&&q.request?.headers!=null?await Promise.all(Object.entries(q.request.headers).map(([C,F])=>L2e({headerKey:C,header:F,file:n}))):[],requestBody:Ntd({request:q.request,file:n}),sdkRequest:await Utd({service:r,request:q.request,endpoint:q,endpointKey:M,file:n,typeResolver:a,propertyResolver:u}),response:await hrd({endpoint:q,file:n,typeResolver:a}),errors:[...mrd({errors:q.errors,file:n}),...o],userSpecifiedExamples:q.examples!=null?q.examples.map(C=>({example:_rd({service:r,endpoint:q,example:C,typeResolver:a,errorResolver:i,exampleResolver:f,variableResolver:d,file:n,workspace:l}),codeSamples:C["code-samples"]?.map(F=>Wtd({codeSample:F,file:n}))})):[],autogeneratedExamples:[],pagination:await grd({propertyResolver:u,file:n,endpointName:M,endpointSchema:q})};return I.id=s1.generateEndpointId(P,I),I}))}}async function A8n({pathParameters:e,location:t,file:r,variableResolver:n}){return e==null?[]:await Promise.all(Object.entries(e).map(([i,a])=>Oqw({parameterName:i,parameter:a,location:t,file:r,variableResolver:n})))}async function Oqw({parameterName:e,parameter:t,location:r,file:n,variableResolver:i}){return{...await Z$(t),name:n.casingsGenerator.generateName(e),valueType:Pqw({parameter:t,variableResolver:i,file:n}),location:r,variable:bIn(t)?i.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function Pqw({parameter:e,variableResolver:t,file:r}){let n=IPi({parameter:e,variableResolver:t,file:r});return n.file.parseTypeReference(n.rawType)}function IPi({parameter:e,variableResolver:t,file:r}){let n=MTa({parameter:e,variableResolver:t,file:r});if(n==null)throw new Error("Cannot resolve path parameter");return n}function MTa({parameter:e,variableResolver:t,file:r}){if(bIn(e)){let n=typeof e=="string"?e:e.variable,i=t.getDeclaration(n,r);return i==null?void 0:{rawType:typeof i.declaration=="string"?i.declaration:i.declaration.type,file:i.file}}else return{file:r,rawType:typeof e=="string"?e:e.type}}function wqw(e){switch(e){case"GET":return zie.Get;case"POST":return zie.Post;case"PUT":return zie.Put;case"PATCH":return zie.Patch;case"DELETE":return zie.Delete;default:Lc(e)}}async function L2e({headerKey:e,header:t,file:r}){let{name:n}=sLt({headerKey:e,header:t});return{...await Z$(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:n}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function sLt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function jqw(e){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Lc(e)}}var k$={};kc(k$,{validateObjectExample:()=>j8n,validateTypeExample:()=>DTa,validateTypeReferenceExample:()=>iQ});function jrd(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function xTa({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}async function Drd({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:s1.generateEndpointIdFromResolvedEndpoint(i),serviceId:s1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:xTa({fernFilePath:i.file.fernFilepath})?void 0:s1.generateSubpackageId(i.file.fernFilepath)},requestProperties:{refreshToken:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.refresh_token})},responseProperties:{accessToken:await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.access_token}),expiresIn:n.responseProperties.expires_in!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.expires_in}):void 0,refreshToken:n.responseProperties.refresh_token!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.refresh_token}):void 0}}}async function Srd({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:n}){let i=await e.resolveEndpointOrThrow({endpoint:n.endpoint,file:r});return{endpointReference:{endpointId:s1.generateEndpointIdFromResolvedEndpoint(i),serviceId:s1.generateServiceIdFromFernFilepath(i.file.fernFilepath),subpackageId:xTa({fernFilePath:i.file.fernFilepath})?void 0:s1.generateSubpackageId(i.file.fernFilepath)},requestProperties:{clientId:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.client_id}),clientSecret:await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.client_secret}),scopes:n.requestProperties.scopes!=null?await t.resolveRequestPropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.requestProperties.scopes}):void 0},responseProperties:{accessToken:await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.access_token}),expiresIn:n.responseProperties.expires_in!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.expires_in}):void 0,refreshToken:n.responseProperties.refresh_token!=null?await t.resolveResponsePropertyOrThrow({file:r,endpoint:n.endpoint,propertyComponents:n.responseProperties.refresh_token}):void 0}}}async function Erd({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:n,tokenEndpoint:i,refreshTokenEndpoint:a}){let u=await Srd({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:i});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let f=a!=null?await Drd({propertyResolver:e,endpointResolver:t,file:r,refreshTokenEndpoint:a}):void 0;return{clientIdEnvVar:n["client-id-env"],clientSecretEnvVar:n["client-secret-env"],tokenPrefix:n["token-prefix"],scopes:n.scopes,tokenEndpoint:u,refreshEndpoint:f}}var BPi={requestProperties:{type:"access_token",client_id:["client_id"],client_secret:["client_secret"],scopes:void 0},responseProperties:{type:"access_token",access_token:["access_token"],expires_in:void 0,refresh_token:void 0}},Cqu={requestProperties:{type:"refresh_token",refresh_token:["refresh_token"]},responseProperties:{type:"access_token",access_token:["access_token"],refresh_token:void 0,expires_in:void 0}};function Ard(e){return{endpoint:e["get-token"].endpoint,requestProperties:Dqw({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:Sqw({responseProperties:e["get-token"]?.["response-properties"]})}}function Mrd(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:Eqw({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:Aqw({responseProperties:e["refresh-token"]?.["response-properties"]})}}function Dqw({requestProperties:e}){if(e==null)return BPi.requestProperties;let t=e["client-id"],r=e["client-secret"],n=e.scopes;return{type:"access_token",client_id:t!=null?HIt(t):BPi.requestProperties.client_id,client_secret:r!=null?HIt(r):BPi.requestProperties.client_secret,scopes:n!=null?HIt(n):BPi.requestProperties.scopes}}function Sqw({responseProperties:e}){return xrd({responseProperties:e,defaultValue:BPi.responseProperties})}function Eqw({requestProperties:e}){if(e==null)return Cqu.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?HIt(t):Cqu.requestProperties.refresh_token}}function Aqw({responseProperties:e}){return xrd({responseProperties:e,defaultValue:Cqu.responseProperties})}function xrd({responseProperties:e,defaultValue:t}){if(e==null)return t;let r=e["access-token"],n=e["expires-in"],i=e["refresh-token"];return{type:"access_token",access_token:r!=null?dMr(r):t.access_token,expires_in:n!=null?dMr(n):t.expires_in,refresh_token:i!=null?dMr(i):t.refresh_token}}async function Brd({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:n}){if(e.auth==null)return{docs:void 0,requirement:SNr.All,schemes:[]};let i=typeof e.auth!="string"?e.auth.docs:void 0;return lyi(e.auth,{single:async a=>{let u=await Trd({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n});return{docs:i,requirement:SNr.All,schemes:[u]}},any:async({any:a})=>({docs:i,requirement:SNr.Any,schemes:await Promise.all(a.map(async u=>await Trd({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:n})))})})}async function Trd({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:n,endpointResolver:i}){let a=(f,d)=>{let c=t?.[f];if(c==null)throw new Error("Unknown auth scheme: "+f);return hsu(c,{header:async o=>AH.header({docs:d,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??f,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:async o=>qrd({file:r,docs:d,rawScheme:o}),bearer:async o=>Crd({file:r,docs:d,rawScheme:o}),oauth:async o=>await Ird({file:r,docs:d,rawScheme:o,propertyResolver:n,endpointResolver:i})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return Crd({file:r,docs:void 0,rawScheme:void 0});case"basic":return qrd({file:r,docs:void 0,rawScheme:void 0});case"oauth":return await Ird({file:r,docs:void 0,rawScheme:void 0,propertyResolver:n,endpointResolver:i});default:return a(u,typeof e!="string"?e.docs:void 0)}}function Crd({file:e,docs:t,rawScheme:r}){return AH.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function qrd({file:e,docs:t,rawScheme:r}){return AH.basic({docs:t,username:e.casingsGenerator.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.casingsGenerator.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}async function Ird({file:e,docs:t,rawScheme:r,propertyResolver:n,endpointResolver:i}){switch(r?.type){case"client-credentials":return AH.oauth({docs:t,configuration:ENr.clientCredentials(await Erd({propertyResolver:n,endpointResolver:i,file:e,oauthScheme:r,tokenEndpoint:Ard(r),refreshTokenEndpoint:Mrd(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}async function Nrd({file:e,rawApiFileSchema:t}){if(t.version!=null)return MNr.header({header:await Mqw({file:e,header:t.version.header}),value:await xqw({file:e,versionDeclaration:t.version})})}async function Mqw({file:e,header:t}){return typeof t=="string"?await L2e({file:e,headerKey:t,header:{type:"string"}}):await L2e({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}async function xqw({file:e,versionDeclaration:t}){return await STa({_enum:{default:t.default,enum:t.values},file:e})}async function zrd({channel:e,typeResolver:t,exampleResolver:r,variableResolver:n,file:i,workspace:a}){let u=[];for(let[f,d]of Object.entries(e.messages??{}))u.push({type:f,availability:Dae(d.availability),docs:d.docs,origin:d.origin,body:qqw({body:d.body,file:i}),displayName:d["display-name"]});return{availability:Dae(e.availability),path:R2e(e.path),auth:e.auth,name:i.fernFilepath.file??i.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?await Promise.all(Object.entries(e.headers).map(([f,d])=>L2e({headerKey:f,header:d,file:i}))):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?await A8n({pathParameters:e["path-parameters"],location:mCe.Endpoint,file:i,variableResolver:n}):[],queryParameters:e["query-parameters"]!=null?await Promise.all(Object.entries(e["query-parameters"]).map(async([f,d])=>{let{name:c}=_Mr({queryParameterKey:f,queryParameter:d}),o=i.parseTypeReference(d);return{...await Z$(d),name:i.casingsGenerator.generateNameAndWireValue({wireValue:f,name:c}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1}})):[],messages:Object.values(u),examples:(e.examples??[]).map(f=>{let d=Bqw({channel:e,example:f,typeResolver:t,exampleResolver:r,variableResolver:n,file:i,workspace:a});return{name:f.name!=null?i.casingsGenerator.generateName(f.name):void 0,docs:f.docs,url:zqw({channel:e,example:f,pathParams:d}),...d,...Nqw({channel:e,example:f,typeResolver:t,exampleResolver:r,file:i,workspace:a}),queryParameters:f["query-parameters"]!=null?Object.entries(f["query-parameters"]).map(([c,o])=>{let l=e["query-parameters"]?.[c];if(l==null)throw new Error(`Query parameter ${c} does not exist`);return{name:i.casingsGenerator.generateNameAndWireValue({name:_Mr({queryParameterKey:c,queryParameter:l}).name,wireValue:c}),value:lT({example:o,rawTypeBeingExemplified:typeof l=="string"?l:l.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),shape:Tqw({queryParameter:l})}}):[],messages:f.messages.map(c=>{let o=e.messages?.[c.type];if(o==null)throw new Error(`Message ${c.type} does not exist`);return{type:c.type,body:Cqw({message:o,example:c.body,typeResolver:t,exampleResolver:r,file:i,workspace:a})}})}})}}function Tqw({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?NF.exploded():NF.single()}function Cqw({message:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){if(!Rqw(e.body))return F6t.reference(lT({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}));if(!lS(t))throw new Error("Example must be an object");let u=[];for(let[f,d]of Object.entries(t)){let c=e.body.properties?.[f];if(c!=null)u.push({name:i.casingsGenerator.generateNameAndWireValue({name:nQ({propertyKey:f,property:c}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof c!="string"?c.type:c,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a}),originalTypeDeclaration:void 0});else{let o=qPi({extends_:e.body.extends,wirePropertyKey:f,typeResolver:r,file:i});if(o==null)throw new Error("Could not find original type declaration for property: "+f);u.push({name:i.casingsGenerator.generateNameAndWireValue({name:nQ({propertyKey:f,property:o.rawPropertyType}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof o.rawPropertyType=="string"?o.rawPropertyType:o.rawPropertyType.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:o.file,fileContainingExample:i,workspace:a}),originalTypeDeclaration:o.typeName})}}return F6t.inlinedBody({jsonExample:n.resolveAllReferencesInExampleOrThrow({example:t,file:i}).resolvedExample,properties:u})}function qqw({body:e,file:t}){return typeof e=="string"?jCe.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):Iqw(e)?jCe.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):jCe.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:WIt(e.extends??[]).map(r=>CU({typeName:r,file:t})),properties:[]})}function Iqw(e){return e.type!=null}function Bqw({channel:e,example:t,typeResolver:r,exampleResolver:n,variableResolver:i,file:a,workspace:u}){let f=[],d=({name:c,pathParameterDeclaration:o,examplePathParameter:l})=>{let g=IPi({parameter:o,variableResolver:i,file:a});return{name:c,value:lT({example:l,rawTypeBeingExemplified:g.rawType,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:g.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null)for(let[c,o]of Object.entries(t["path-parameters"])){let l=e["path-parameters"]?.[c];if(l!=null)f.push(d({name:a.casingsGenerator.generateName(c),pathParameterDeclaration:l,examplePathParameter:o}));else throw new Error(`Path parameter ${c} does not exist`)}return{pathParameters:f}}function Nqw({channel:e,example:t,typeResolver:r,exampleResolver:n,file:i,workspace:a}){let u=[];if(t.headers!=null)for(let[f,d]of Object.entries(t.headers)){let c=e.headers?.[f];if(c!=null)u.push({name:i.casingsGenerator.generateNameAndWireValue({name:sLt({headerKey:f,header:c}).name,wireValue:f}),value:lT({example:d,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:i,fileContainingExample:i,workspace:a})});else throw new Error(`Heder ${f} does not exist`)}return{headers:u}}function zqw({channel:e,example:t,pathParams:r}){let n=e.path;if(t["path-parameters"]!=null)for(let i of[...r.pathParameters])n=n.replaceAll(`{${i.name.originalName}}`,`${i.value.jsonExample}`);return n}function Rqw(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function qqu({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let n=Object.values(t)[0];if(n!=null)return{defaultEnvironment:e??void 0,environments:zEr(n,{singleBaseUrl:()=>q6t.singleBaseUrl(Fqw({environments:t,casingsGenerator:r})),multipleBaseUrls:i=>q6t.multipleBaseUrls(Lqw({baseUrls:Object.keys(i.urls),environments:t,casingsGenerator:r}))})}}function Fqw({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,n])=>zEr(n,{singleBaseUrl:i=>({docs:typeof i=="string"?void 0:i.docs,id:r,name:t.generateName(r),url:Rrd(typeof i=="string"?i:i.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function Lqw({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(n=>({id:n,name:r.generateName(n)})),environments:Object.entries(t).map(([n,i])=>zEr(i,{multipleBaseUrls:a=>({docs:a.docs,id:n,name:r.generateName(n),urls:by(a.urls,u=>Rrd(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${n} does not have multiple base URLs`)}}))}}function Rrd(e){return e.endsWith("/")?e.slice(0,-1):e}function Frd({errorName:e,errorDeclaration:t,file:r,typeResolver:n,exampleResolver:i,workspace:a}){let u=[];if(t.type!=null&&t.examples!=null)for(let f of t.examples)u.push({name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,docs:f.docs,jsonExample:i.resolveAllReferencesInExampleOrThrow({example:f.value,file:r}).resolvedExample,shape:lT({example:f.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})});return{name:uRr({errorName:e,file:r}),discriminantValue:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:e}),docs:typeof t!="string"?t.docs:void 0,statusCode:t["status-code"],type:t.type!=null?r.parseTypeReference(t.type):void 0,examples:u}}var Lrd="content";function Urd(e,t){if(e==null||e.strategy==="status-code")return z6t.statusCode();switch(e.strategy){case"property":return z6t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:Lrd,wireValue:Lrd})});default:Lc(e)}}function Vrd({readme:e,services:t}){let r=new Iqu(t);return{apiReferenceLink:e.apiReferenceLink,bannerLink:e.bannerLink,introduction:e.introduction,defaultEndpoint:e.defaultEndpoint!=null?r.getEndpointForReadmeOrThrow(e.defaultEndpoint).id:void 0,features:e.features!=null?Object.fromEntries(Object.entries(e.features).map(([n,i])=>[n,i.map(a=>r.getEndpointForReadmeOrThrow(a).id)])):void 0}}var Iqu=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=Vqw({endpoint:t}),n=this.getEndpointKeyForReadmeEndpoint(r);return this.endpoints[n]}getEndpointForReadmeOrThrow(t){let r=this.getEndpointForReadme(t);if(r==null)throw new Error(`Endpoint not found for ${JSON.stringify(t)}`);return r}buildEndpoints(t){let r={};for(let n of Object.values(t))for(let i of n.endpoints)r[this.getEndpointKeyForHttpEndpoint(i)]=i;return r}getEndpointKeyForReadmeEndpoint(t){return this.getEndpointKey({method:t.method,path:t.path,stream:t.stream??!1})}getEndpointKeyForHttpEndpoint(t){return this.getEndpointKey({method:t.method,path:Uqw(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:n}){return`${t}|${r}|${n}`}};function Uqw(e){let t="";e.fullPath.head.length>0&&(t=k1(t,e.fullPath.head));for(let r of e.fullPath.parts)t=k1(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=k1(t,r.tail));return t.startsWith("/")?t:`/${t}`}function Vqw({endpoint:e}){if(typeof e=="string"){let t=e.split(" ");if(t.length!==2||t[0]==null||t[1]==null)throw new Error(`invalid endpoint string: ${e}`);return{method:t[0],path:t[1]}}return e}async function Wrd({webhooks:e,file:t,typeResolver:r,exampleResolver:n,workspace:i}){let a=[];for(let[u,f]of Object.entries(e))a.push({id:s1.generateWebhookId(t.fernFilepath,u),availability:Dae(f.availability),displayName:f["display-name"],docs:f.docs,method:f.method,name:t.casingsGenerator.generateName(u),headers:f.headers!=null?await Promise.all(Object.entries(f.headers).map(([d,c])=>L2e({headerKey:d,header:c,file:t}))):[],payload:Wqw({payload:f.payload,file:t}),examples:f.examples!=null?Qqw({webhook:f,examples:f.examples,file:t,typeResolver:r,exampleResolver:n,workspace:i}):void 0});return a}function Wqw({payload:e,file:t}){return typeof e=="string"?Hie.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):TTa(e)?Hie.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):Hie.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:WIt(e.extends).map(r=>CU({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,n])=>Hqw({propertyKey:r,propertyDefinition:n,docs:typeof n!="string"?n.docs:void 0,availability:typeof n!="string"?Dae(n.availability):void 0,file:t})):[]})}function Hqw({propertyKey:e,propertyDefinition:t,docs:r,availability:n,file:i}){return{docs:r,availability:n,name:i.casingsGenerator.generateNameAndWireValue({wireValue:e,name:nQ({propertyKey:e,property:t}).name}),valueType:i.parseTypeReference(t)}}function Qqw({webhook:e,examples:t,file:r,typeResolver:n,exampleResolver:i,workspace:a}){let u=typeof e.payload=="string"?e.payload:TTa(e.payload)?e.payload.type:void 0;if(u!=null)return t.map(f=>({docs:e.docs,name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,payload:lT({example:f.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}));if(!lS(e.payload))throw new Error(`Example webhook payload is not an object. Got: ${JSON.stringify(e.payload)}`);return t.map(f=>({docs:e.docs,name:f.name!=null?r.casingsGenerator.generateName(f.name):void 0,payload:lT({example:f.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:n,exampleResolver:i,workspace:a})}))}function TTa(e){return e.type!=null}function M8n(e){let t={};for(let[r,n]of Object.entries(e))if(typeof n!="string")for(let i of n.audiences??[])t[i]==null&&(t[i]=new Set),t[i]?.add(r);return t}function Hrd({name:e,source:t}){return wD.userDefined({file:ATa({source:t}),name:sRr.generateName(e)})}function Qrd({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=Jqw({type:e.proto.type});if(t!=null)return t}}function Jqw({type:e}){switch(e){case"google.protobuf.Any":return wD.wellKnown(uh.any());case"google.protobuf.Api":return wD.wellKnown(uh.api());case"google.protobuf.BoolValue":return wD.wellKnown(uh.boolValue());case"google.protobuf.BytesValue":return wD.wellKnown(uh.bytesValue());case"google.protobuf.DoubleValue":return wD.wellKnown(uh.doubleValue());case"google.protobuf.Duration":return wD.wellKnown(uh.duration());case"google.protobuf.Empty":return wD.wellKnown(uh.empty());case"google.protobuf.Enum":return wD.wellKnown(uh.enum());case"google.protobuf.EnumValue":return wD.wellKnown(uh.enumValue());case"google.protobuf.Field":return wD.wellKnown(uh.field());case"google.protobuf.FieldCardinality":return wD.wellKnown(uh.fieldCardinality());case"google.protobuf.FieldKind":return wD.wellKnown(uh.fieldKind());case"google.protobuf.FieldMask":return wD.wellKnown(uh.fieldMask());case"google.protobuf.FloatVlaue":return wD.wellKnown(uh.floatValue());case"google.protobuf.Int32Value":return wD.wellKnown(uh.int32Value());case"google.protobuf.Int64Value":return wD.wellKnown(uh.int64Value());case"google.protobuf.ListValue":return wD.wellKnown(uh.listValue());case"google.protobuf.Method":return wD.wellKnown(uh.method());case"google.protobuf.Mixin":return wD.wellKnown(uh.mixin());case"google.protobuf.NullValue":return wD.wellKnown(uh.nullValue());case"google.protobuf.Option":return wD.wellKnown(uh.option());case"google.protobuf.SourceContext":return wD.wellKnown(uh.sourceContext());case"google.protobuf.StringValue":return wD.wellKnown(uh.stringValue());case"google.protobuf.Struct":return wD.wellKnown(uh.struct());case"google.protobuf.Syntax":return wD.wellKnown(uh.syntax());case"google.protobuf.Timestamp":return wD.wellKnown(uh.timestamp());case"google.protobuf.Type":return wD.wellKnown(uh.type());case"google.protobuf.Uint32Value":return wD.wellKnown(uh.uint32Value());case"google.protobuf.Uint64Value":return wD.wellKnown(uh.uint64Value());case"google.protobuf.Value":return wD.wellKnown(uh.value())}}async function Jrd({generic:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type,i=E3(n);if(i==null)throw new Error(`Invalid generic type definition: ${n}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:n,file:t});if(i.arguments&&mA(a.declaration)){let u=E3(a.typeName)?.arguments??[],f=Object.entries(a.declaration.properties??{}).map(([d,c])=>{let o=c;return typeof c=="string"&&u?.includes(c)&&(o=i.arguments?.[u.indexOf(c)]??c),[d,o]});return Sq.object({extends:WIt(a.declaration.extends).map(d=>CU({typeName:d,file:t})),properties:await APi({properties:Object.fromEntries(f)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${n}`)}async function Grd({alias:e,file:t,typeResolver:r}){let n=typeof e=="string"?e:e.type;return bCe(n)?await Jrd({generic:n,file:t,typeResolver:r}):Sq.alias({aliasOf:t.parseTypeReference(e),resolvedType:Gqw({aliasOf:n,file:t,typeResolver:r})})}function Gqw({aliasOf:e,file:t,typeResolver:r}){let n=r.resolveTypeOrThrow({type:e,file:t});switch(n._type){case"primitive":return MH.primitive(n.originalTypeReference.primitive);case"container":return MH.container(n.originalTypeReference.container);case"unknown":return MH.unknown();case"named":{let i=mA(n.declaration)?R6t.Object:UNr(n.declaration)?R6t.Union:V6t(n.declaration)?R6t.Enum:mIn(n.declaration)?R6t.UndiscriminatedUnion:Lc(n.declaration);return MH.named({name:n.name,shape:i})}}}function $rd({union:e,file:t}){return Sq.undiscriminatedUnion({members:e.union.map(r=>typeof r=="string"?{docs:void 0,type:t.parseTypeReference(r)}:{type:t.parseTypeReference(r),docs:r.docs})})}function Krd(e){let t=[];if(e.extends!=null){let r=typeof e.extends=="string"?[e.extends]:e.extends;t.push(...r)}return e.properties!=null&&t.push(...Object.values(e.properties).map(r=>typeof r=="string"?r:r.type)),t}function Nqu({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:n=new Bqu}){let i=zz(e,{alias:u=>{let f=typeof u=="string"?u:u.type,d=E3(f);if(d!=null){let c=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:f,file:t}),l=E3(o.typeName)?.arguments;if(mA(o.declaration)){let g=Krd(o.declaration);l&&g.filter(O=>!l.includes(O)).forEach(O=>c.add(O))}return Array.from(c)}return[f]},object:u=>Krd(u),discriminatedUnion:u=>{let f=[];return u["base-properties"]!=null&&f.push(...Object.values(u["base-properties"]).map(d=>typeof d=="string"?d:d.type)),f.push(...Object.values(u.union).reduce((d,c)=>{let o=typeof c=="string"?c:c.type;return typeof o=="string"&&d.push(o),d},[])),f},undiscriminatedUnion:u=>Object.values(u.union).reduce((f,d)=>{let c=typeof d=="string"?d:d.type;return typeof c=="string"&&f.push(c),f},[]),enum:()=>[]}),a=[];for(let u of i){let f=P$({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:d,valueType:c})=>[...d,...c],list:d=>d,optional:d=>d,set:d=>d,named:d=>[d],literal:()=>[],unknown:()=>[]}});for(let d of f){let c=CU({typeName:d,file:t});if(!n.hasTypeNameBeenSeen(c)){n.addTypeName(c),a.push(c);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(bCe(o.typeName))continue;a.push(...Nqu({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:n}))}}}return a}var Bqu=class{cache=new Set;addTypeName(t){this.cache.add(this.computeCacheKey(t))}hasTypeNameBeenSeen(t){return this.cache.has(this.computeCacheKey(t))}computeCacheKey(t){return t.fernFilepath.allParts.map(r=>r.originalName).join("/")+":"+t.name.originalName}};async function Yrd({typeName:e,typeDeclaration:t,file:r,typeResolver:n,exampleResolver:i,sourceResolver:a,workspace:u}){let f=await Z$(t),d=CU({typeName:e,file:r}),c=Nqu({typeDeclaration:t,file:r,typeResolver:n}),o={};mA(t)&&(o=M8n(t.properties??{}));let l=await Kqw({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...f,inline:!1,name:d,shape:await $qw({typeDeclaration:t,file:r,typeResolver:n}),referencedTypes:new Set(c.map(g=>g.typeId)),encoding:Yqw({typeDeclaration:t,source:l}),source:l,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(g=>({name:g.name!=null?r.casingsGenerator.generateName(g.name):void 0,docs:g.docs,jsonExample:i.resolveAllReferencesInExampleOrThrow({example:g.value,file:r}).resolvedExample,shape:Tqu({typeName:d,example:g.value,typeResolver:n,exampleResolver:i,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(c.map(g=>g.fernFilepath))}}async function $qw({typeDeclaration:e,file:t,typeResolver:r}){return await zz(e,{alias:n=>Grd({alias:n,file:t,typeResolver:r}),object:n=>Itd({object:n,file:t}),discriminatedUnion:n=>Ytd({union:n,file:t,typeResolver:r}),undiscriminatedUnion:n=>$rd({union:n,file:t}),enum:async n=>Sq.enum(await STa({_enum:n,file:t}))})}async function Kqw({file:e,typeDeclaration:t,typeName:r,sourceResolver:n}){if(typeof t=="string"||t.source==null&&t.encoding==null)return;if(t.encoding!=null){let a=Qrd({encoding:t.encoding});if(a!=null)return BEr.proto(a)}if(t.source==null)return;let i=await n.resolveSourceOrThrow({source:t.source,file:e});if(!(i==null||i.type!=="protobuf"))return BEr.proto(Hrd({source:i,name:r}))}function Yqw({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?Xqw(e.encoding):Zqw(t)}function Xqw(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function Zqw(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function Xrd(e,t){let r=t[e];if(r==null)throw new GSr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function Zrd(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,e6w({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(n=>kqw({endpoint:n,ir:e}))}]))}}function kqw({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>krd(r,t))}}}function e6w({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>krd(r,t))}}}return e}function krd(e,t){let r=zqu(e.typeId,t);return end({objectTypeDeclaration:r,ir:t})}function zqu(e,t){let r=Xrd(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return zqu(r.shape.resolvedType.name.typeId,t)}throw new GSr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function end({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(n=>{let i=zqu(n.typeId,t);return end({objectTypeDeclaration:i,ir:t})});return[...e.properties,...r]}var CTa=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;subpackages=new Set;constructor({types:t,properties:r,errors:n,environments:i,services:a,endpoints:u,webhooks:f,subpackages:d,queryParameters:c,requestProperties:o,webhookPayloadProperties:l}){this.environments=i,this.types=t,this.properties=r,this.errors=n,this.services=a,this.endpoints=u,this.webhooks=f,this.webhookPayloadProperties=l,this.subpackages=d,this.requestProperties=o,this.queryParameters=c}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=s1.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let n=this.properties[t];return n==null?!0:n.has(r)}hasError(t){let r=s1.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=s1.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let n=this.requestProperties[t];return n==null?!0:n.has(r)}hasQueryParameter(t,r){let n=this.queryParameters[t];return n==null?!0:n.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasWebhookPayloadProperty(t,r){let n=this.webhookPayloadProperties[t];return n==null?!0:n.has(r)}};var qTa=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=t6w(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:n,descendantTypeIdsByAudience:i,propertiesByAudience:a}){let u=s1.generateTypeId(t),f={typeId:u,allDescendants:r,descendantsByAudience:i,referencedSubpackages:n};this.types[u]=f,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let n=s1.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath),this.types[n]?.referencedSubpackages.forEach(i=>{this.addSubpackages(i)}))}markEnvironmentForAudiences(t,r,n){t&&(this.hasAudience(r)||n)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){return this.typesReferencedByService}addError(t){let r=s1.generateErrorId(t.name),n=new Set,i=new Set;t.type!=null&&G5(t.type,n,i);let a={errorId:r,referencedTypes:n,referencedSubpackages:i};this.errors[r]=a}addEndpoint(t,r,n){let i=s1.generateServiceId(t.name),a=r.id,u=new Set,f=new Set,d=new Set;for(let c of[...t.headers,...r.headers])G5(c.valueType,u,d);for(let c of[...t.pathParameters,...r.pathParameters])G5(c.valueType,u,d);for(let c of r.queryParameters)G5(c.valueType,u,d);if(n!=null&&n.request!=null&&typeof n.request!="string"){let c=M8n(n.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:c}}r.requestBody!=null&&T5._visit(r.requestBody,{inlinedRequestBody:c=>{for(let o of c.extends)Rqu(o,u,d);for(let o of c.properties)G5(o.valueType,u,d);if(n!=null&&typeof n.request=="object"&&typeof n.request.body=="object"&&v6(n.request.body)){let o=M8n(n.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:c})=>{G5(c,u,d)},fileUpload:({properties:c})=>{for(let o of c)Rie._visit(o,{file:cl,bodyProperty:({valueType:l})=>{G5(l,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&A3._visit(r.response.body,{fileDownload:cl,json:c=>{G5(c.responseBodyType,u,d)},streaming:c=>{c._visit({sse:o=>G5(o.payload,u,d),json:o=>G5(o.payload,u,d),text:cl,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.type)}})},streamParameter:c=>{c.streamResponse._visit({sse:o=>G5(o.payload,u,d),json:o=>G5(o.payload,u,d),text:cl,_other:()=>{throw new Error("Unknown streamingResponse type: "+c.streamResponse.type)}}),c.nonStreamResponse.type==="json"&&G5(c.nonStreamResponse.value.responseBodyType,u,d)},text:cl,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(c=>{f.add(s1.generateErrorId(c.error)),d.add(c.error.fernFilepath)});for(let c of u)this.markTypeForService(c,i);this.endpoints[a]={endpointId:a,referencedTypes:u,referencedErrors:f,referencedSubpackages:d}}markEndpointForAudience(t,r,n){if(this.hasAudience(n)){let i=s1.generateServiceId(t);this.servicesNeededForAudience.add(i),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(f=>{this.addSubpackages(f)})}),this.servicesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath)}}addWebhook(t,r,n){let i=r.id;if(i==null)return;let a=new Set,u=new Set;r.payload!=null&&Hie._visit(r.payload,{inlinedPayload:f=>{for(let d of f.extends)Rqu(d,a,u);for(let d of f.properties)G5(d.valueType,a,u);if(n?.payload!=null&&typeof n.payload=="object"&&!TTa(n.payload)){let d=M8n(n.payload.properties??{});this.webhookProperties[i]={webhookId:i,propertiesByAudience:d}}},reference:({payloadType:f})=>{G5(f,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t.fernFilepath),this.webhooks[i]={webhookId:i,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,n){let i=r.id;i!=null&&this.hasAudience(n)&&(this.webhooksNeededForAudience.add(i),this.addSubpackages(t.fernFilepath))}build(){let t=new Set,r=new Set;for(let f of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(f);for(let c of d.referencedErrors){if(r.has(c))continue;r.add(c);let o=this.getErrorNode(c);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let f of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(f);this.addReferencedTypes(t,d.referencedTypes)}let n={},i={},a={},u={};if(this.audiences.type==="filtered"){for(let[f,d]of Object.entries(this.properties)){if(!t.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}c.size>0&&(n[f]=c),n[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}i[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.parametersByAudience[o];l?.forEach(g=>{c.add(g)})}a[f]=c.size>0?c:void 0}for(let[f,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(f))continue;let c=new Set;for(let o of this.audiences.audiences){let l=d.propertiesByAudience[o];l?.forEach(g=>{c.add(g)})}u[f]=c.size>0?c:void 0}}return new CTa({types:t,properties:n,errors:r,requestProperties:i,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience})}markTypeForService(t,r){let n=this.typesReferencedByService[t];n==null?this.typesReferencedByService[t]=new Set(r):n.add(r)}addReferencedTypes(t,r){for(let n of r){if(t.has(n))continue;t.add(n);let i=this.getTypeNode(n);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=i.descendantsByAudience[a];if(u!=null)u.forEach(f=>{t.add(f)});else{i.allDescendants.forEach(f=>{t.add(f)});break}}else i.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(n=>r.audiences.has(n));default:Lc(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let n={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(s1.generateSubpackageId(n))}}};function t6w(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Lc(e)}}function G5(e,t,r){uT._visit(e,{container:n=>{r6w(n,t,r)},named:n=>{Rqu(n,t,r)},primitive:cl,unknown:cl,_other:cl})}function Rqu(e,t,r){t.add(s1.generateTypeId(e)),r.add(e.fernFilepath)}function r6w(e,t,r){Eq._visit(e,{list:n=>{G5(n,t,r)},map:n=>{G5(n.keyType,t,r),G5(n.valueType,t,r)},optional:n=>{G5(n,t,r)},set:n=>{G5(n,t,r)},literal:cl,_other:cl})}function rnd({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let n=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:ON({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)}}:void 0;return n!==void 0?Bz.samePropertiesAsObject(n):void 0},singleProperty:r=>{let n=ON({filteredIr:e,exampleTypeReference:r});return n!==void 0?Bz.singleProperty(n):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function ON({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:n=>({...t,shape:dO.container(gA.list({...n,list:n.list.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),set:n=>({...t,shape:dO.container(gA.set({...n,set:n.set.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter(i=>i!==void 0)}))}),optional:n=>{let i=n.optional!=null?ON({filteredIr:e,exampleTypeReference:n.optional}):void 0;return i!=null?{...t,shape:dO.container(gA.optional({optional:i,valueType:n.valueType}))}:void 0},map:n=>({...t,shape:dO.container(gA.map({...n,map:n.map.map(i=>{let a=ON({filteredIr:e,exampleTypeReference:i.key}),u=ON({filteredIr:e,exampleTypeReference:i.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(i=>i!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:n=>{let i=ON({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.alias({...n,value:i})})}:void 0},enum:n=>({...t,shape:dO.named({...r,shape:dS.enum(n)})}),object:n=>({...t,shape:dO.named({...r,shape:dS.object({...n,properties:n.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:ON({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})})}),union:n=>{let i=rnd({filteredIr:e,singleUnionTypeProperties:n.singleUnionType.shape});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.union({...n,singleUnionType:{...n.singleUnionType,shape:i}})})}:void 0},undiscriminatedUnion:n=>{let i=ON({filteredIr:e,exampleTypeReference:n.singleUnionType});return i!==void 0?{...t,shape:dO.named({...r,shape:dS.undiscriminatedUnion({...n,singleUnionType:i})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Fqu({filteredIr:e,pathParameters:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function n6w({filteredIr:e,queryParameters:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function tnd({filteredIr:e,headers:t}){return t.map(r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...r,value:n}:void 0}).filter(r=>r!==void 0)}function i6w({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(n=>n.originalTypeDeclaration?e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue):!0).map(n=>{let i=ON({filteredIr:e,exampleTypeReference:n.value});return i!==void 0?{...n,value:i}:void 0}).filter(n=>n!==void 0)}),reference:r=>{let n=ON({filteredIr:e,exampleTypeReference:r});return n!==void 0?b$.reference(n):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function a6w({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:n=>T4.ok(cN.body(n!=null?ON({filteredIr:e,exampleTypeReference:n}):void 0)),stream:n=>T4.ok(cN.stream(n.map(i=>ON({filteredIr:e,exampleTypeReference:i})).filter($M))),sse:n=>T4.ok(cN.sse(n.map(({event:i,data:a})=>{let u=ON({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:i,data:u}:void 0}).filter($M))),_other:({type:n})=>{throw new Error(`Received unknown type for OK example: ${n}`)}}),error:({error:r,body:n})=>T4.error({error:r,body:n!=null?ON({filteredIr:e,exampleTypeReference:n}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function Lqu({filteredIr:e,example:t}){return{...t,rootPathParameters:Fqu({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Fqu({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Fqu({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:tnd({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:tnd({filteredIr:e,headers:t.endpointHeaders}),queryParameters:n6w({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?i6w({filteredIr:e,requestBody:t.request}):void 0,response:a6w({filteredIr:e,response:t.response})}}function nnd({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let n=ON({filteredIr:e,exampleTypeReference:r.value});return n!==void 0?{...t,shape:dS.alias({...r,value:n})}:void 0},enum:()=>t,object:r=>({...t,shape:dS.object({...r,properties:r.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:ON({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})}),union:r=>{let n=rnd({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return n!==void 0?{...t,shape:dS.union({...r,singleUnionType:{...r.singleUnionType,shape:n}})}:void 0},undiscriminatedUnion:r=>{let n=ON({filteredIr:e,exampleTypeReference:r.singleUnionType});return n!==void 0?{...t,shape:dS.undiscriminatedUnion({...r,singleUnionType:n})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var ITa=class{subpackages={};rootPackage={docs:void 0,fernFilepath:{allParts:[],packagePath:[],file:void 0},websocket:void 0,service:void 0,types:[],errors:[],subpackages:[],webhooks:void 0,navigationConfig:void 0};addPackageRedirection({from:t,to:r}){let n=this.getPackageForFernFilepath(t);if(n.navigationConfig!=null)throw new Error("Found duplicate navigationConfig for package");n.navigationConfig={pointsTo:s1.generateSubpackageId(r)}}addDocs(t,r){let n=this.getPackageForFernFilepath(t);if(n.docs!=null)throw new Error("Found duplicate docs for package");n.docs=r}addSubpackage(t){this.getPackageForFernFilepath(t)}addType(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).types.push(t)}addError(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).errors.push(t)}addService(t,r){let n=this.getPackageForFernFilepath(r.name.fernFilepath);if(n.service!=null)throw new Error("Found duplicate service for "+t);n.service=t}addWebhookGroup(t,r){let n=this.getPackageForFernFilepath(r);if(n.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);n.webhooks=t}addWebSocketChannel(t,r){let n=this.getPackageForFernFilepath(r);if(n.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);n.websocket=t}build(t){t!=null&&(Object.entries(this.subpackages).forEach(([n,i])=>{t.hasSubpackageId(n)?this.subpackages[n]={...i,types:i.types.filter(a=>t.hasTypeId(a)),errors:i.errors.filter(a=>t.hasErrorId(a)),service:i.service!=null&&t.hasServiceId(i.service)?i.service:void 0,subpackages:i.subpackages.filter(a=>t.hasSubpackageId(a))}:delete this.subpackages[n]}),this.rootPackage={...this.rootPackage,types:this.rootPackage.types.filter(n=>t.hasTypeId(n)),errors:this.rootPackage.errors.filter(n=>t.hasErrorId(n)),service:this.rootPackage.service!=null&&t.hasServiceId(this.rootPackage.service)?this.rootPackage.service:void 0,subpackages:this.rootPackage.subpackages.filter(n=>t.hasSubpackageId(n)),webhooks:this.rootPackage.webhooks!=null?this.rootPackage.webhooks:void 0});let r=new Set(this.getAllChildrenWithEndpoints(this.rootPackage));return{subpackages:by(this.subpackages,(n,i)=>({...n,hasEndpointsInTree:r.has(i)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!ind(this.rootPackage.subpackages,t))throw new Error("Sorted subpackages differ from unsorted packages in root");this.rootPackage.subpackages=t}sortSubpackage(t,r){let n=this.subpackages[t];if(n==null)throw new Error("Subpackage does not exist: "+t);if(!ind(n.subpackages,r))throw new Error("Sorted subpackages differ from unsorted packages");n.subpackages=r}getAllSubpackagesWithEndpoints(t){let r=this.subpackages[t];if(r==null)throw new Error("Subpackage does not exist: "+t);let n=this.getAllChildrenWithEndpoints(r);return(n.length>0||r.service!=null)&&n.push(t),n}getAllChildrenWithEndpoints(t){return t.subpackages.flatMap(r=>[...this.getAllSubpackagesWithEndpoints(r)])}getPackageForFernFilepath(t,r=0,n=this.rootPackage){let i=t.allParts[r];if(i==null)return n;let a=n.subpackages.map(c=>{let o=this.subpackages[c];if(o==null)throw new Error("Subpackage ID is invalid: "+c);return o}),u=r+1,f={allParts:t.allParts.slice(0,u),packagePath:t.packagePath.slice(0,u),file:u===t.allParts.length?t.file:void 0},d=a.find(c=>c.name.originalName===i.originalName);if(d==null){let c=s1.generateSubpackageId(f),o={docs:void 0,fernFilepath:f,name:i,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[c]=o,n.subpackages.push(c),d=o}return this.getPackageForFernFilepath(t,u,d)}};function ind(e,t){if(e.length!==t.length)return!1;let r=new Set(e);for(let n of t)if(!r.has(n))return!1;return!0}function and({reference:e,referencedIn:t,imports:r}){let[n,i,...a]=e.split(".");if(n==null||a.length>0)return;if(i==null)return{endpointName:n,relativeFilepath:t};let f=r[n];if(f!=null)return{endpointName:i,relativeFilepath:oRr({referencedIn:t,importPath:f})}}var yan=class{workspace;constructor(t){this.workspace=t}async resolveEndpointOrThrow({endpoint:t,file:r}){let n=await this.resolveEndpoint({endpoint:t,file:r});if(n==null)throw new Error("Cannot resolve endpoint: "+t+" in file "+r.relativeFilepath);return n}async resolveEndpointByMethodAndPath({method:t,path:r}){let n;return await Jz(this.workspace,async(i,a,u)=>{let f=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:sRr,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[d,c]of Object.entries(a.service?.endpoints??{}))c.method===t&&c.path===r&&(n={endpointId:d,endpoint:c,file:f})}),await Enn(this.workspace,async(i,a)=>{let u=qO({relativeFilepath:i,definitionFile:a,casingsGenerator:sRr,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[f,d]of Object.entries(a.service?.endpoints??{}))d.method===t&&d.path===r&&(n={endpointId:f,endpoint:d,file:u})}),n}async resolveEndpoint({endpoint:t,file:r}){let i=new fyi().tryParse(t);if(i!=null)return await this.resolveEndpointByMethodAndPath(i);let a=this.getDeclarationOfEndpoint({referenceToEndpoint:t,file:r});if(a==null)return;let u=a.file.definitionFile.service?.endpoints?.[a.endpointName];if(u!=null)return{endpointId:a.endpointName,endpoint:u,file:a.file}}getDeclarationOfEndpoint({referenceToEndpoint:t,file:r}){let n=and({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=cae(this.workspace,n.relativeFilepath);if(!(i==null||i.service?.endpoints?.[n.endpointName]==null))return{endpointName:n.endpointName,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var van=class{workspace;constructor(t){this.workspace=t}getDeclarationOrThrow(t,r){let n=this.getDeclaration(t,r);if(n==null)throw new Error("Error does not exist: "+t);return n}getDeclaration(t,r){let n=FDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=cae(this.workspace,n.relativeFilepath);if(i==null)return;let a=i.errors?.[n.typeName];if(a!=null)return{declaration:a,file:qO({definitionFile:i,relativeFilepath:n.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var UDe=class{typeResolver;constructor(t){this.typeResolver=t}resolveAllReferencesInExample({example:t,file:r}){if(typeof t=="string"){let n=this.resolveExample({example:t,file:r});return n==null||typeof n.resolvedExample=="string"?n:this.resolveAllReferencesInExample({example:n.resolvedExample,file:n.file})}else if(lS(t)){let n={};for(let[i,a]of Object.entries(t)){let u=this.resolveAllReferencesInExample({example:a,file:r});if(u==null)return;n[i]=u.resolvedExample}return{resolvedExample:n}}else if(Array.isArray(t)){let n=[];for(let i of t){let a=this.resolveAllReferencesInExample({example:i,file:r});if(a==null)return;n.push(a.resolvedExample)}return{resolvedExample:n}}return{resolvedExample:t}}resolveAllReferencesInExampleOrThrow({example:t,file:r}){let n=this.resolveAllReferencesInExample({example:t,file:r});if(n==null)throw new Error("Failed to resolve examples");return n}resolveExample({example:t,file:r}){if(typeof t!="string")return{resolvedExample:t,file:r};if(t.startsWith(`\\${uFt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(uFt))return{resolvedExample:t,file:r};let n=this.parseExampleReference(t);if(n==null)return;let i=this.typeResolver.getDeclarationOfNamedType({referenceToNamedType:n.rawTypeReference,file:r});if(i==null||typeof i.declaration=="string"||i.declaration.examples==null)return;let a=i.declaration.examples.find(u=>u.name===n.exampleName);if(a!=null)return this.resolveExample({example:a.value,file:i.file})}resolveExampleOrThrow({example:t,file:r}){let n=this.resolveExample({example:t,file:r});if(n==null)throw new Error("Cannot resolve example: "+t);return n}parseExampleReference(t){let[r,n,i,...a]=t.split(".");if(!(r==null||n==null||a.length>0))return i==null?{rawTypeReference:r.slice(uFt.length),exampleName:n}:{rawTypeReference:`${r}.${n}`.slice(uFt.length),exampleName:i}}};var BTa=class{typeResolver;endpointResolver;constructor(t,r){this.typeResolver=t,this.endpointResolver=r,this.typeResolver=t,this.endpointResolver=r}async resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n}){let i=await this.resolveRequestProperty({file:t,endpoint:r,propertyComponents:n});if(i==null)throw new Error("Cannot resolve request property from endpoint: "+r+" in file "+t.relativeFilepath);return i}async resolveRequestProperty({file:t,endpoint:r,propertyComponents:n}){let i=await this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t});if(i.endpoint.request==null)return;if(typeof i.endpoint.request!="string")return this.resolveRequestPropertyFromInlinedRequest({typeResolver:this.typeResolver,file:i.file,requestType:i.endpoint.request,propertyComponents:n});let a=await this.resolveObjectProperty({file:i.file,typeName:i.endpoint.request,propertyComponents:n});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:n,file:t}),property:Uie.body(a)}}async resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n}){let i=await this.resolveResponseProperty({file:t,endpoint:r,propertyComponents:n});if(i==null)throw new Error("Cannot resolve response property from endpoint: "+r+" in file "+t.relativeFilepath);return i}async resolveResponseProperty({file:t,endpoint:r,propertyComponents:n}){let i=await this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t}),a=await this.resolveObjectProperty({file:i.file,typeName:(typeof i.endpoint.response!="string"?i.endpoint.response?.type:i.endpoint.response)??"",propertyComponents:n});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:n,file:t}),property:a}}async resolveRequestPropertyFromInlinedRequest({typeResolver:t,file:r,requestType:n,propertyComponents:i}){if(i.length===1){let a=i[0]??"",u=typeof n["query-parameters"]!=null?n["query-parameters"]?.[a]:void 0;if(u!=null)return{property:Uie.query(await ETa({file:r,queryParameterKey:a,queryParameter:u})),propertyPath:void 0}}return this.resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:n,propertyComponents:i})}async resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:n,propertyComponents:i}){if(n.body==null)return;if(typeof n.body=="string"){let u=await this.resolveObjectProperty({file:r,typeName:n.body,propertyComponents:i});return u==null?void 0:{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Uie.body(u)}}if(v6(n.body)){let u=await Aqu({typeResolver:t,file:r,objectSchema:n.body,propertyComponents:i});return u==null?void 0:{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Uie.body(u)}}let a=await this.resolveObjectProperty({file:r,typeName:n.body.type,propertyComponents:i});if(a!=null)return{propertyPath:await this.propertyPathFromPropertyComponents({propertyComponents:i,file:r}),property:Uie.body(a)}}async resolveObjectProperty({file:t,typeName:r,propertyComponents:n}){let i=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return await Equ({typeResolver:this.typeResolver,file:xPi(i)??t,resolvedType:i,propertyComponents:n})}async propertyPathFromPropertyComponents({propertyComponents:t,file:r}){return t.length<=1?[]:t.slice(0,-1).map(n=>r.casingsGenerator.generateName(n))}};var ond=require("fs/promises"),NTa=class{async parse({absoluteFilePath:t}){let r=await(0,ond.readFile)(t,"utf-8"),n=r.match(/option\s+csharp_namespace\s*=\s*"([^"]+)";/),i=r.match(/package\s+([a-zA-Z_][\w.]*);/),a=r.match(/service\s+([a-zA-Z_]\w*)\s*{/);return{csharpNamespace:n?.[1],packageName:i?.[1],serviceName:a?.[1]}}};var zTa=class{context;workspace;sourceCache;constructor(t,r){this.context=t,this.workspace=r,this.sourceCache=new Map}async resolveSourceOrThrow({source:t,file:r}){let n=await this.resolveSource({source:t,file:r});if(n==null){if(vca(t))throw new Error(`Cannot resolve source ${t.proto} from file ${r.relativeFilepath}`);this.context.logger.warn(`Cannot resolve source ${t.openapi} from file ${r.relativeFilepath}`)}return n}async resolveSource({source:t,file:r}){return vca(t)?await this.resolveProtobufSource({source:t,file:r}):await this.resolveOpenAPISource({source:t,file:r})}async resolveProtobufSource({source:t,file:r}){let n=yf(this.workspace.absoluteFilePath,Ms.of(t.proto));if(this.sourceCache.has(n))return this.sourceCache.get(n);if(!await Wh(n))return;let a=await new NTa().parse({absoluteFilePath:n}),u={type:"protobuf",absoluteFilePath:n,relativeFilePath:Ms.of(t.proto),csharpNamespace:a.csharpNamespace,packageName:a.packageName,serviceName:a.serviceName};return this.sourceCache.set(n,u),u}async resolveOpenAPISource({source:t,file:r}){let n=yf(this.workspace.absoluteFilePath,Ms.of(t.openapi));if(this.sourceCache.has(n))return this.sourceCache.get(n);if(!await Wh(n))return;let i={type:"openapi",absoluteFilePath:n,relativeFilePath:Ms.of(t.openapi)};return this.sourceCache.set(n,i),i}};var eM=class{workspace;constructor(t){this.workspace=t}resolveTypeOrThrow({type:t,file:r}){let n=this.resolveType({type:t,file:r});if(n==null)throw new Error("Cannot resolve type: "+t+" in file "+r.relativeFilepath);return n}getDeclarationOfNamedTypeOrThrow({referenceToNamedType:t,file:r}){let n=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(n==null)throw new Error("Cannot find declaration of type: "+t+" in file "+r.relativeFilepath);return n}getDeclarationOfNamedType({referenceToNamedType:t,file:r}){let n=FDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(n==null)return;let i=cae(this.workspace,n.relativeFilepath);if(i==null)return;let a=i.types?.[n.typeName];if(a==null){let u=E3(n.typeName);if(u!=null){for(let f of Object.keys(i.types??{})??[])if(u.name&&f.startsWith(u.name)&&f.endsWith(">")){let d=i.types?.[f];return d!=null?{typeName:f,declaration:d,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:n.typeName,declaration:a,file:qO({relativeFilepath:n.relativeFilepath,definitionFile:i,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:n=[]}){return P$({type:t,_default:void 0,validation:void 0,visitor:{primitive:i=>({_type:"primitive",primitive:i,originalTypeReference:uT.primitive(i)}),unknown:()=>({_type:"unknown",originalTypeReference:uT.unknown()}),map:({keyType:i,valueType:a})=>i!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:i,valueType:a},originalTypeReference:uT.container(Eq.map({keyType:i.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:i=>i!=null?{_type:"container",container:{_type:"list",itemType:i},originalTypeReference:uT.container(Eq.list(i.originalTypeReference))}:void 0,optional:i=>i!=null?{_type:"container",container:{_type:"optional",itemType:i},originalTypeReference:uT.container(Eq.optional(i.originalTypeReference))}:void 0,set:i=>i!=null?{_type:"container",container:{_type:"set",itemType:i},originalTypeReference:uT.container(Eq.set(i.originalTypeReference))}:void 0,literal:i=>({_type:"container",container:{_type:"literal",literal:i},originalTypeReference:uT.container(Eq.literal(i))}),named:i=>{let a=this.getDeclarationOfNamedType({referenceToNamedType:i,file:r});if(a==null)return;let u={typeName:a.typeName,file:a.file.relativeFilepath,reference:i};if(!n.some(f=>f.file===u.file&&f.typeName===u.typeName))return this.resolveNamedTypeFromDeclaration({referenceToNamedType:i,referencedIn:r,rawDeclaration:a,objectPath:[...n,u]})}}})}resolveNamedTypeOrThrow({referenceToNamedType:t,file:r}){let n=this.resolveNamedType({referenceToNamedType:t,file:r});if(n==null)throw new Error("Cannot resolve type: "+t);return n}resolveNamedType({referenceToNamedType:t,file:r}){let n=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(n!=null)return this.resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:n})}resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:n,objectPath:i=[]}){let{declaration:a,file:u}=n;if(gIn(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:i});let f=jTa({type:t,_default:void 0,validation:void 0,file:r});if(!(f.type!=="named"||cae(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:n.typeName,name:f,declaration:a,filepath:u.relativeFilepath,objectPath:i,originalTypeReference:f,file:u}}};var JIt=class e{static VARIABLE_PREFIX="$";getDeclarationOrThrow(t,r){let n=this.getDeclaration(t,r);if(n==null)throw new Error("Variable does not exist: "+t);return n}getDeclaration(t,r){if(!t.startsWith(e.VARIABLE_PREFIX))return;let n=r.rootApiFile.variables?.[t.substring(1)];if(n!=null)return{declaration:n,file:pMr({casingsGenerator:r.casingsGenerator,rootApiFile:r.rootApiFile})}}getVariableIdOrThrow(t){let r=this.getVariableId(t);if(r==null)throw new Error("Variable reference does not start with "+e.VARIABLE_PREFIX);return r}getVariableId(t){if(t.startsWith(e.VARIABLE_PREFIX))return t.substring(e.VARIABLE_PREFIX.length)}};function RTa(e,t){if(t){for(let[r,n]of Object.entries(t))if(typeof n!="string"&&r===e)return n.audiences}}function und({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":{let r=e??aD.STRING;return{type:"success",example:Pv.string({original:r}),jsonExample:r}}case"BASE_64":return{type:"success",example:Pv.base64(aD.BASE64),jsonExample:aD.BASE64};case"BOOLEAN":return{type:"success",example:Pv.boolean(aD.BOOLEAN),jsonExample:aD.BOOLEAN};case"DATE":return{type:"success",example:Pv.date(aD.DATE),jsonExample:aD.DATE};case"DATE_TIME":return{type:"success",example:Pv.datetime({datetime:new Date(aD.DATE_TIME),raw:aD.DATE_TIME}),jsonExample:aD.DATE_TIME};case"DOUBLE":return{type:"success",example:Pv.double(aD.DOUBLE),jsonExample:aD.DOUBLE};case"FLOAT":return{type:"success",example:Pv.float(aD.FLOAT),jsonExample:aD.FLOAT};case"INTEGER":return{type:"success",example:Pv.integer(aD.INT),jsonExample:aD.INT};case"UINT_64":return{type:"success",example:Pv.uint64(aD.INT64),jsonExample:aD.INT64};case"UINT":return{type:"success",example:Pv.uint(aD.UINT),jsonExample:aD.UINT};case"BIG_INTEGER":return{type:"success",example:Pv.bigInteger(aD.INT64.toString()),jsonExample:`${aD.INT64}`};case"LONG":return{type:"success",example:Pv.long(aD.INT64),jsonExample:aD.INT64};case"UUID":return{type:"success",example:Pv.uuid(aD.UUID),jsonExample:aD.UUID};default:Lc(t.v1)}}function snd({fieldName:e,containerType:t,maxDepth:r,currentDepth:n,typeDeclarations:i,skipOptionalProperties:a}){if(n>=r)return lRr({containerType:t});switch(t.type){case"list":{let u=YF({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?lRr({containerType:t}):{type:"success",example:gA.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:gA.literal({literal:t.literal._visit({boolean:u=>Pv.boolean(u),string:u=>Pv.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return lRr({containerType:t});let u=YF({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?lRr({containerType:t}):{type:"success",example:gA.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"set":{let u=YF({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"?lRr({containerType:t}):{type:"success",example:gA.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=YF({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a}),f=YF({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:n+1,typeDeclarations:i,skipOptionalProperties:a});return u.type==="failure"||f.type==="failure"?lRr({containerType:t}):{type:"success",example:gA.map({map:[{key:u.example,value:f.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:f.jsonExample}}}default:Lc(t)}}function lRr({containerType:e}){switch(e.type){case"list":return{type:"success",example:gA.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:gA.literal({literal:e.literal._visit({boolean:t=>Pv.boolean(t),string:t=>Pv.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:gA.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"set":return{type:"success",example:gA.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:gA.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Lc(e)}}function x8n({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function lnd({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=YF({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:d}=u;return{type:"success",example:dS.alias({value:f}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:dS.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u=cnd({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:i,maxDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:f,jsonExample:d}=u;return{type:"success",example:dS.object(f),jsonExample:d}}case"undiscriminatedUnion":{let u=0;for(let f of r.shape.members){let d=YF({fieldName:e,typeReference:f.type,typeDeclarations:t,currentDepth:i+1,maxDepth:n,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:c,jsonExample:o}=d;return{type:"success",example:dS.undiscriminatedUnion({index:u,singleUnionType:c}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant;for(let f of r.shape.types){let d=f.shape._visit({noProperties:()=>({type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Bz.noProperties()}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue}}),samePropertiesAsObject:c=>{let o=t[c.typeId];if(o==null)throw new Error(`Failed to find type declaration with id ${c.typeId}`);if(o.shape.type!=="object")throw new Error(`Same properties as object union is not an object ${o.shape.type}`);let l=cnd({currentDepth:i,maxDepth:n,fieldName:e,objectTypeDeclaration:o.shape,typeDeclaration:o,typeDeclarations:t,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:g,jsonExample:O}=l;return{type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Bz.samePropertiesAsObject({typeId:o.name.typeId,object:g})}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,...typeof O=="object"?O:{}}}},singleProperty:c=>{let o=YF({currentDepth:i+1,maxDepth:n,fieldName:e,typeReference:c.type,typeDeclarations:t,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:l,jsonExample:g}=o;return{type:"success",example:dS.union({discriminant:u,singleUnionType:{wireDiscriminantValue:f.discriminantValue,shape:Bz.singleProperty(l)}}),jsonExample:{[u.wireValue]:f.discriminantValue.wireValue,[c.name.wireValue]:g}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(d.type!=="failure")return d}}}return{type:"failure",message:"Failed to generate example for type reference"}}function cnd({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:n,maxDepth:i,currentDepth:a,skipOptionalProperties:u}){let f={},d=[];for(let c of[...r.properties??[],...r.extendedProperties??[]]){let o=YF({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:n,currentDepth:a+1,maxDepth:i,skipOptionalProperties:u});if(o.type==="failure"&&!x8n({typeDeclarations:n,typeReference:c.valueType}))return{type:"failure",message:`Failed to generate required property ${c.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:l,jsonExample:g}=o;d.push({name:c.name,originalTypeDeclaration:t.name,value:l}),f[c.name.wireValue]=g}return{type:"success",example:dS.object({properties:d}),jsonExample:f}}function YF({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a}){if(i>n)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)throw new Error(`Failed to find type declaration with id ${t.typeId}`);let f=lnd({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(f.type==="failure")return f;let{example:d,jsonExample:c}=f;return{type:"success",example:{jsonExample:c,shape:dO.named({shape:d,typeName:u.name})},jsonExample:c}}case"container":{let u=snd({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:n,currentDepth:i,skipOptionalProperties:a});if(u.type==="failure"){let{example:c,jsonExample:o}=lRr({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:dO.container(c)},jsonExample:o}}let{example:f,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:dO.container(f)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:f}=und({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:dO.primitive(f)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:dO.unknown(u)},jsonExample:u}}}}var fnd=Yo(p1u(),1);function NPi({ir:e,endpoint:t,service:r,typeDeclarations:n,skipOptionalRequestProperties:i,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:T4.ok(cN.body(void 0)),docs:void 0},f=[{params:t.pathParameters,add:c=>u.endpointPathParameters.push(c)},{params:r.pathParameters,add:c=>u.servicePathParameters.push(c)},{params:e.pathParameters,add:c=>u.rootPathParameters.push(c)}];for(let c of f)for(let o of c.params){let l=YF({fieldName:o.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:o.valueType,skipOptionalProperties:i});if(l.type==="failure")return l;let{example:g}=l;c.add({name:o.name,value:g})}for(let c of t.queryParameters){if(i&&x8n({typeDeclarations:n,typeReference:c.valueType}))continue;let o=YF({fieldName:c.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:c.valueType,skipOptionalProperties:i});if(o.type==="failure")return o;let{example:l}=o;u.queryParameters.push({name:c.name,shape:c.allowMultiple?NF.exploded():NF.single(),value:l})}let d=[{params:t.headers,add:c=>u.endpointHeaders.push(c)},{params:r.headers,add:c=>u.serviceHeaders.push(c)}];for(let c of d)for(let o of c.params){if(i&&x8n({typeDeclarations:n,typeReference:o.valueType}))continue;let l=YF({fieldName:o.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:n,typeReference:o.valueType,skipOptionalProperties:i});if(l.type==="failure")return l;let{example:g}=l;c.add({name:o.name,value:g})}if(t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let c={},o=[];for(let l of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let g=YF({fieldName:l.name.wireValue,typeReference:l.valueType,typeDeclarations:n,currentDepth:1,maxDepth:10,skipOptionalProperties:i});if(g.type==="failure"&&!x8n({typeDeclarations:n,typeReference:l.valueType}))return{type:"failure",message:`Failed to generate required property ${l.name.wireValue} b/c ${g.message}`};if(g.type==="failure")continue;let{example:O,jsonExample:P}=g;o.push({name:l.name,originalTypeDeclaration:void 0,value:O}),c[l.name.wireValue]=P}u.request=b$.inlinedRequestBody({jsonExample:c,properties:o});break}case"reference":{let c=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.request=b$.reference(o);break}default:Lc(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let c=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(c.type==="failure")return c;let{example:o,jsonExample:l}=c;u.response=T4.ok(cN.body({...o,jsonExample:l}));break}case"streamParameter":return{type:"failure",message:"Stream parameter unsupported"};case"streaming":return{type:"failure",message:"Streaming unsupported"};case"text":return{type:"failure",message:"Text unsupported"};default:Lc(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=T4.error({body:void 0,error:a.declaration.name});else{let c=YF({currentDepth:0,maxDepth:10,typeDeclarations:n,typeReference:a.declaration.type,skipOptionalProperties:i});if(c.type==="failure")return c;let{example:o}=c;u.response=T4.error({body:o,error:a.declaration.name})}return{type:"success",example:{id:(0,fnd.default)(u),url:o6w(t,u),...u},jsonExample:void 0}}function o6w(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(i=>{let a=i.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[i.name.originalName]=u});let n=e.fullPath.head+e.fullPath.parts.map(i=>r[i.pathParameter]+i.tail).join("");return n.startsWith("/")||n===""?n:`/${n}`}async function aQ({fdrApiDefinitionId:e,workspace:t,generationLanguage:r,keywords:n,smartCasing:i,disableExamples:a,audiences:u,readme:f,packageName:d,version:c,context:o}){let l=oLt({generationLanguage:r,keywords:n,smartCasing:i}),g=new qTa(u),O=pMr({casingsGenerator:l,rootApiFile:t.definition.rootApiFile.contents}),P=(t.definition.rootApiFile.contents.errors??[]).map(Hr=>({error:uRr({errorName:Hr,file:O}),docs:void 0})),j=new eM(t),M=new yan(t),q=new BTa(j,M),B=new van(t),I=new UDe(j),C=new JIt,F=new zTa(o,t),K={fdrApiDefinitionId:e,apiVersion:await Nrd({file:O,rawApiFileSchema:t.definition.rootApiFile.contents}),apiName:l.generateName(t.definition.rootApiFile.contents.name),apiDisplayName:t.definition.rootApiFile.contents["display-name"],apiDocs:await mTa(t.definition.rootApiFile.contents.docs),auth:await Brd({rawApiFileSchema:t.definition.rootApiFile.contents,file:O,propertyResolver:q,endpointResolver:M}),headers:t.definition.rootApiFile.contents.headers!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents.headers).map(([Hr,Gt])=>L2e({headerKey:Hr,header:Gt,file:O}))):[],idempotencyHeaders:t.definition.rootApiFile.contents["idempotency-headers"]!=null?await Promise.all(Object.entries(t.definition.rootApiFile.contents["idempotency-headers"]).map(([Hr,Gt])=>L2e({headerKey:Hr,header:Gt,file:O}))):[],types:{},errors:{},services:{},constants:jrd(l),environments:qqu({casingsGenerator:l,rawApiFileSchema:t.definition.rootApiFile.contents}),errorDiscriminationStrategy:Urd(t.definition.rootApiFile.contents["error-discrimination"],O),basePath:t.definition.rootApiFile.contents["base-path"]!=null?R2e(t.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:await A8n({pathParameters:t.definition.rootApiFile.contents["path-parameters"],file:O,location:mCe.Root,variableResolver:C}),variables:t.definition.rootApiFile.contents.variables!=null?Object.entries(t.definition.rootApiFile.contents.variables).map(([Hr,Gt])=>({docs:typeof Gt!="string"?Gt.docs:void 0,id:Hr,name:O.casingsGenerator.generateName(Hr),type:O.parseTypeReference(Gt)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0},ee=new ITa,J=async Hr=>{ee.addSubpackage(Hr.fernFilepath),await VP(Hr.definitionFile,{imports:cl,docs:Gt=>{Gt!=null&&ee.addDocs(Hr.fernFilepath,Gt)},types:async Gt=>{if(Gt!=null)for(let[wn,An]of Object.entries(Gt)){if(bCe(wn))continue;let Ht=await Yrd({typeName:wn,typeDeclaration:An,file:Hr,typeResolver:j,exampleResolver:I,sourceResolver:F,workspace:t}),er=Ht.typeDeclaration;a&&(er.userProvidedExamples=[],er.autogeneratedExamples=[]);let dn=Ht.descendantFilepaths,fn=s1.generateTypeId(er.name);K.types[fn]=er,ee.addType(fn,er),g.addType({declaredTypeName:er.name,descendantTypeIds:er.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:Ht.propertiesByAudience,descendantFilepaths:dn}),g.markTypeForAudiences(er.name,qtd(An))}},errors:Gt=>{if(Gt==null)return;if(t.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[An,Ht]of Object.entries(Gt)){let er=Frd({errorName:An,errorDeclaration:Ht,file:Hr,typeResolver:j,exampleResolver:I,workspace:t}),dn=s1.generateErrorId(er.name);K.errors[dn]=er,ee.addError(dn,er),g.addError(er)}},service:async Gt=>{if(Gt==null)return;let wn=await wrd({rootDefaultUrl:Hr.defaultUrl??t.definition.rootApiFile.contents["default-url"],rootPathParameters:K.pathParameters,serviceDefinition:Gt,file:Hr,errorResolver:B,typeResolver:j,propertyResolver:q,exampleResolver:I,sourceResolver:F,globalErrors:P,variableResolver:C,workspace:t}),An=s1.generateServiceId(wn.name);K.services[An]=wn,ee.addService(An,wn);let Ht={};wn.endpoints.forEach(er=>{a&&(er.autogeneratedExamples=[],er.userSpecifiedExamples=[]);let dn=Gt.endpoints[er.name.originalName];g.addEndpoint(wn,er,dn),Ht[er.name.originalName]=er}),Gt.audiences!=null&&g.markEndpointForAudience(wn.name,wn.endpoints,Gt.audiences),Object.entries(Gt.endpoints).map(([er,dn])=>{let fn=Ht[er];fn!=null&&dn.audiences!=null&&g.markEndpointForAudience(wn.name,[fn],dn.audiences)})},webhooks:async Gt=>{if(Gt==null)return;let wn=s1.generateWebhookGroupId(Hr.fernFilepath),An=await Wrd({webhooks:Gt,file:Hr,typeResolver:j,exampleResolver:I,workspace:t}),Ht={};for(let er of An)Ht[er.name.originalName]=er;Object.entries(Gt).forEach(([er,dn])=>{let fn=Ht[er];fn!=null&&(g.addWebhook(Hr,fn,dn),dn.audiences!=null&&g.markWebhookForAudiences(Hr,fn,dn.audiences))}),K.webhookGroups[wn]=An,ee.addWebhookGroup(wn,Hr.fernFilepath)},channel:async Gt=>{if(Gt==null)return;let wn=s1.generateWebSocketChannelId(Hr.fernFilepath),An=await zrd({channel:Gt,file:Hr,variableResolver:C,typeResolver:j,exampleResolver:I,workspace:t});K.websocketChannels!=null&&(K.websocketChannels[wn]=An,ee.addWebSocketChannel(wn,Hr.fernFilepath))}})};await Jz(t,async(Hr,Gt,wn)=>{await J(qO({relativeFilepath:Hr,definitionFile:Gt,casingsGenerator:l,rootApiFile:t.definition.rootApiFile.contents,defaultUrl:wn.defaultUrl}))}),await Enn(t,async(Hr,Gt)=>{if(Gt.navigation!=null)if(typeof Gt.navigation=="string")ee.addPackageRedirection({from:jae({relativeFilepath:Hr,casingsGenerator:l}),to:jae({relativeFilepath:yf(cb(Hr),Ms.of(Gt.navigation)),casingsGenerator:l})});else{let wn=Gt.navigation.map(An=>s1.generateSubpackageId(jae({relativeFilepath:yf(cb(Hr),Ms.of(An)),casingsGenerator:l})));Hr===$A?ee.sortRootPackage(wn):ee.sortSubpackage(s1.generateSubpackageId(jae({relativeFilepath:Hr,casingsGenerator:l})),wn)}}),K.serviceTypeReferenceInfo=s6w(g);let G=a?K:u6w(K,o),te=t.definition.rootApiFile.contents,Xe=qqu({casingsGenerator:l,rawApiFileSchema:te}),Re=Xe?.environments._visit({singleBaseUrl:Hr=>Hr.environments.filter(Gt=>RTa(Gt.id,te.environments)!=null).length===0,multipleBaseUrls:Hr=>Hr.environments.filter(Gt=>RTa(Gt.id,te.environments)!=null).length===0,_other:()=>!1});Xe?.environments.environments.forEach(Hr=>{g.markEnvironmentForAudiences(Hr,RTa(Hr.id,te.environments)??[],Re)});let Pt=g.hasNoAudiences()?void 0:g.build(),Ct=c6w(G,Pt),Wt=t.definition.rootApiFile.contents.auth!=null&&Object.values(Ct.services).every(Hr=>Hr.endpoints.every(Gt=>Gt.auth)),Bt=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.response?.body?.type==="streaming")),or=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.pagination!=null)),jr=Object.values(Ct.services).some(Hr=>Hr.endpoints.some(Gt=>Gt.response?.body?.type==="fileDownload")),Vr=f!=null?Vrd({readme:f,services:K.services}):void 0,{types:It,services:cr}=Zrd(Ct);return{...Ct,...ee.build(Pt),types:It,services:cr,sdkConfig:{isAuthMandatory:Wt,hasStreamingEndpoints:Bt,hasPaginatedEndpoints:or,hasFileDownloadEndpoints:jr,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:c!=null&&d!=null?{header:"User-Agent",value:`${d}/${c}`}:void 0}},readmeConfig:Vr}}function u6w(e,t){for(let[r,n]of Object.entries(e.services))for(let i of n.endpoints){t.logger.debug(`Generating example for ${i.id}`);let a=NPi({ir:e,service:n,endpoint:i,typeDeclarations:e.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(a.type==="failure"){t.logger.debug(`Failed to generate example for ${i.id}. ${a.message}`);continue}let{example:u}=a;i.autogeneratedExamples=[{example:u}]}return e}function s6w(e){let t={},r=[],n=e.getTypesReferencedByService();for(let[i,a]of Object.entries(n)){if(a.size===1){let u=a.values().next().value;t[u]===void 0&&(t[u]=[]),t[u]?.push(i);continue}r.push(i)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function c6w(e,t){if(t==null)return e;let r=Pkr(e.types,u=>t.hasType(u)),n=Object.fromEntries(Object.entries(r).map(([u,f])=>{let d=[];if(f.userProvidedExamples=f.userProvidedExamples.map(c=>nnd({filteredIr:t,exampleType:c})).filter(c=>c!==void 0),f.shape.type==="object"){for(let c of f.shape.properties)t.hasProperty(u,c.name.wireValue)&&d.push(c);return[u,{...f,shape:Sq.object({...f.shape,properties:d})}]}return[u,f]})),i=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,f])=>{let d=f.filter(c=>t.hasWebhook(c)).map(c=>{let o=c.id;return c.payload.type==="inlinedPayload"&&o!=null&&(c.payload={...c.payload,properties:c.payload.properties.filter(l=>t.hasWebhookPayloadProperty(o,l.name.wireValue))}),c});return[u,d]})),a=e.environments;if(a){switch(a.environments.type){case"singleBaseUrl":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}case"multipleBaseUrls":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}}a.defaultEnvironment&&(t.hasEnvironmentId(a.defaultEnvironment)||(a.defaultEnvironment=void 0))}return{...e,environments:a,types:n,errors:Pkr(e.errors,u=>t.hasError(u)),services:by(Pkr(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(f=>t.hasEndpoint(f)).map(f=>(f.autogeneratedExamples=f.autogeneratedExamples.map(d=>({...d,example:Lqu({filteredIr:t,example:d.example})})),f.userSpecifiedExamples=f.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?Lqu({filteredIr:t,example:d.example}):void 0})),f.queryParameters.length>0&&(f.queryParameters=f.queryParameters.filter(d=>t.hasQueryParameter(f.id,d.name.wireValue))),f.requestBody?.type==="inlinedRequestBody"?{...f,requestBody:{...f.requestBody,properties:f.requestBody.properties.filter(d=>t.hasRequestProperty(f.id,d.name.wireValue))}}:f))})),webhookGroups:i,serviceTypeReferenceInfo:l6w(e.serviceTypeReferenceInfo,t)}}function l6w(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([n,i])=>{t.hasServiceId(n)&&(r[n]=i.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(n=>t.hasTypeId(n)),typesReferencedOnlyByService:r}}var Pnd=Yo(_Ta(),1),wnd=Yo(hTa(),1),VTa=require("fs/promises"),jnd=Yo(fxa(),1);function cLt(e){return typeof e.subpackageId=="string"}function VDe(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function ban(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var Uqu="__package__",fRr=class e{api;context;static create(t,r){return new e(t,r)}#e=new Map;#t=new Map;#n=new Map;#i=new Map;#r=new Map;#a=new Map;#o=new Map;#f=new Map;#c=new Map;#s=new Map;#u=new Map;static getSubpackageId(t){return cLt(t)?t.subpackageId:Uqu}getSubpackageByIdOrLocator(t){if(t==null)return;let r=KF.SubpackageId(t);return r===Uqu?this.api.rootPackage:this.api.subpackages[r]??this.#u.get(r)}resolveSubpackage(t){if(t!=null){for(;t?.pointsTo!=null;)t=this.api.subpackages[t.pointsTo];return t}}constructor(t,r){this.api=t,this.context=r,[t.rootPackage,...Object.values(t.subpackages)].forEach(n=>{let i=KF.SubpackageId(e.getSubpackageId(n)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(i,a),n.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let f=e.createEndpointId(u,i);this.#e.set(f,u);let d=[],c=[u.method];u.response?.type.type==="stream"&&c.push("STREAM"),c.forEach(o=>{d.push(`${o} ${VDe(u.path.parts)}`),d.push(`${o} ${ban(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,VDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,ban(u.path.parts))}`);let g=dnd(l);g!=null&&(d.push(`${o} ${k1(g,VDe(u.path.parts))}`),d.push(`${o} ${k1(g,ban(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.debug(`Registering endpoint locator: ${o}`),this.#f.set(o,u)})}),n.websockets.forEach(u=>{a.webSockets.set(u.id,u);let f=e.createWebSocketId(u,i);this.#t.set(f,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${VDe(u.path.parts)}`),d.push(`${o} ${ban(u.path.parts)}`),u.environments.forEach(l=>{d.push(`${o} ${k1(l.baseUrl,VDe(u.path.parts))}`),d.push(`${o} ${k1(l.baseUrl,ban(u.path.parts))}`);let g=dnd(l);g!=null&&(d.push(`${o} ${k1(g,VDe(u.path.parts))}`),d.push(`${o} ${k1(g,ban(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.debug(`Registering websocket locator: ${o}`),this.#c.set(o,u)})}),n.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#n.set(e.createWebhookId(u,i),u)})}),this.#e.forEach((n,i)=>{this.#i.set(n,i)}),this.#t.forEach((n,i)=>{this.#r.set(n,i)}),this.#n.forEach((n,i)=>{this.#a.set(n,i)}),this.#d(t.rootPackage,[])}#d(t,r){if(t==null)return;let n=cLt(t)?[...r,t.name]:r,i=n.length===0?[Uqu]:n;if([i.join("."),i.join("/"),`${i.join(".")}.yml`].forEach(u=>{this.context?.logger.debug(`Registering subpackage locator: ${u}`),this.#u.set(u,t)}),t.pointsTo!=null)return this.#d(this.api.subpackages[t.pointsTo],n);t.endpoints.forEach(u=>{let f=[...n,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering endpoint locator: ${c}`),this.#f.set(c,u)})}),t.websockets.forEach(u=>{let f=[...n,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering websocket locator: ${c}`),this.#c.set(c,u)})}),t.webhooks.forEach(u=>{let f=[...n,u.id];[f.join("."),f.join("/")].forEach(c=>{this.context?.logger.debug(`Registering webhook locator: ${c}`),this.#s.set(c,u)})}),t.subpackages.forEach(u=>{this.#d(this.api.subpackages[u],n)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#n}get endpointsByLocator(){return this.#f}get webSocketsByLocator(){return this.#c}get webhooksByLocator(){return this.#s}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#u}getEndpointId(t){return this.#i.get(t)}getWebSocketId(t){return this.#r.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return Yc.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return Yc.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return Yc.WebhookId(`${r}.${t.id}`)}};function dnd(e){if(e!=null){if(e.baseUrl.startsWith("/"))return e.baseUrl;if(e.baseUrl.startsWith("http")||e.baseUrl.startsWith("ws"))try{return new URL(e.baseUrl).pathname}catch{return}}}var T8n=Yo(_Ta(),1),_nd=Yo(hTa(),1);function pnd(e){let t=e.split(".")[0];if(t==null)return;let n=/(^\d{1,4})-(\d{1,2})-(\d{1,4})/.exec(t)?.[0];if(n!=null)try{return new Date(n)}catch{}}T8n.default.extend(_nd.default);var f6w="Changelog",d6w=["summary","index","overview"],gan=class{markdownToFullSlug;changelogFiles;docsWorkspace;idgen;constructor(t,r,n,i){this.markdownToFullSlug=t,this.changelogFiles=r,this.docsWorkspace=n,this.idgen=i}toChangelogNode(t){let r=t.title??f6w,n=[],i;for(let l of this.changelogFiles??[]){let g=PKo(l.split("/"));if(g==null)continue;let O=pnd(g);if(O==null){let j=g.split(".")[0]?.toLowerCase();j!=null&&d6w.includes(j)&&(i=l);continue}let P=this.toRelativeFilepath(l);n.push({date:O,pageId:Yc.PageId(P),absoluteFilepath:l})}let a=t.parentSlug.apply({fullSlug:i!=null?this.markdownToFullSlug.get(i)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??nH(r)}),u=n.map(l=>{let g=T8n.default.utc(l.date);return{id:this.idgen.get(l.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(l.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:l.date.toISOString(),pageId:l.pageId,noindex:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}),f=Vqu(u,l=>l.date,"desc"),d=i!=null?Yc.PageId(this.toRelativeFilepath(i)):void 0,c=this.idgen.get(d??"changelog"),o=this.groupByYear(c,f,a);return{id:c,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:o,overviewPageId:d,noindex:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}orUndefined(){return this.changelogFiles!=null&&this.changelogFiles.length>0?this:void 0}groupByYear(t,r,n){let i=new Map;for(let a of r){let u=T8n.default.utc(a.date).year(),f=i.get(u)??[];f.push(a),i.set(u,f)}return Vqu(Array.from(i.entries()).map(([a,u])=>{let f=n.append(a.toString()).get(),d=this.idgen.get(`${t}/year/${a}`);return{id:d,type:"changelogYear",title:a.toString(),year:a,slug:f,icon:void 0,hidden:void 0,children:this.groupByMonth(d,u,n),authed:void 0,viewers:void 0,orphaned:void 0}}),"year","desc")}groupByMonth(t,r,n){let i=new Map;for(let a of r){let u=T8n.default.utc(a.date).month()+1,f=i.get(u)??[];f.push(a),i.set(u,f)}return Vqu(Array.from(i.entries()).map(([a,u])=>{let f=(0,T8n.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:f.format("MMMM YYYY"),month:a,slug:n.append(a.toString()).get(),icon:void 0,hidden:void 0,children:u,authed:void 0,viewers:void 0,orphaned:void 0}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}};function Vqu(e,t,r="asc"){return e.concat().sort((n,i)=>{let a=typeof t=="function"?t(n):n[t],u=typeof t=="function"?t(i):i[t];return a<u?r==="asc"?-1:1:a>u?r==="asc"?1:-1:0})}var FTa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;apiDefinitionId;#e;#t=new Set;#n=new Set;#i=new Set;#r=new Set;#a=new Map;#o=[];#f;#c;#s;disableEndpointPairs;constructor(t,r,n,i,a,u,f,d){this.apiSection=t,this.workspace=i,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=f,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Yc.V1.ApiDefinitionId(r.id),this.#e=fRr.create(r,u),this.#s=d,this.#f=this.apiSection.overviewAbsolutePath!=null?Yc.V1.PageId(this.toRelativeFilepath(this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#c=n.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??nH(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#u(this.apiSection.navigation,this.#e.api.rootPackage,this.#c)),this.#o=this.#y(this.#o.map(o=>this.#g(o)),this.#j(this.#e.api.rootPackage,this.#c))}get(){let t=Yc.V1.followRedirects(this.#o),r=new gan(this.markdownFilesToFullSlugs,this.workspace.changelog?.files.map(n=>n.absoluteFilepath),this.docsWorkspace,this.#s).orUndefined();return{id:this.#s.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#c.get(),icon:this.apiSection.icon,hidden:this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#c,viewers:void 0}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#b(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned}}#u(t,r,n){r=this.#e.resolveSubpackage(r);let i=r!=null?fRr.getSubpackageId(r):void 0;return t.map(a=>Cxa(a)._visit({link:u=>({id:this.#s.get(u.url),type:"link",title:u.text,icon:u.icon,url:Yc.Url(u.url)}),page:u=>this.#d(u,n),package:u=>this.#v(u,n),section:u=>this.#_(u,n),item:({value:u})=>this.#p(u,i,n),endpoint:u=>this.#P(u,i,n)})).filter($M)}#d(t,r){let n=Yc.V1.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/"),urlSlug:t.slug??nH(t.title)});return{id:this.#s.get(n),type:"page",pageId:n,title:t.title,slug:i.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#v(t,r){let n=t.overviewAbsolutePath!=null?Yc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,i=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=fRr.getSubpackageId(a),f=this.#s.get(n??`${this.apiDefinitionId}:${u}`);this.#r.has(u)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${u}`),this.#r.add(u),this.#a.set(f,[u]);let d=t.slug??(cLt(a)?a.urlSlug:this.apiSection.slug??nH(this.apiSection.title)),c=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#u(t.contents,a,c);return{id:f,type:"apiPackage",children:o,title:t.title??(cLt(a)?a.displayName??ian(a.name):this.apiSection.title),slug:c.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??nH(t.package),f=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#u(t.contents,void 0,f);return{id:this.#s.get(n??`${this.apiDefinitionId}:${nH(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:f.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}}#_(t,r){let n=t.overviewAbsolutePath!=null?Yc.V1.PageId(this.toRelativeFilepath(t.overviewAbsolutePath)):void 0,i=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#s.get(n??i??r.get()),u=t.referencedSubpackages.map(o=>{let l=this.#e.getSubpackageByIdOrLocator(o);return l!=null?fRr.getSubpackageId(l):void 0}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter($M);this.#a.set(a,u),u.forEach(o=>{this.#r.has(o)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${o}`),this.#r.add(o)});let f=t.slug??nH(t.title),d=r.apply({fullSlug:i?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),c=this.#u(t.contents,void 0,d);return{id:a,type:"apiPackage",children:c,title:t.title,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:n,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}#p(t,r,n){t=t.trim();let i=this.#e.getSubpackageByIdOrLocator(t);if(i!=null){let a=fRr.getSubpackageId(i),u=this.#s.get(`${this.apiDefinitionId}:${a}`);this.#r.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#r.add(a),this.#a.set(u,[a]);let f=cLt(i)?i.urlSlug:"",d=n.apply({urlSlug:f});return{id:u,type:"apiPackage",children:[],title:cLt(i)?i.displayName??ian(i.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}return this.#P({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0},r,n)}#P(t,r,n){let i=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.endpoints.get(KF.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(i!=null){let f=this.#e.getEndpointId(i);if(f==null)throw new Error(`Expected Endpoint ID for ${i.id}. Got undefined.`);this.#t.has(f)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${f}`),this.#t.add(f);let d=t.slug!=null?n.append(t.slug):n.apply(i);return{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"endpoint",method:i.method,endpointId:f,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),isResponseStream:i.response?.type.type==="stream",title:t.title??i.name??VDe(i.path.parts),slug:d.get(),icon:t.icon,hidden:t.hidden,playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let a=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.webSockets.get(KF.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let f=this.#e.getWebSocketId(a);if(f==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#n.has(f)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${f}`),this.#n.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webSocket",webSocketId:f,title:t.title??a.name??VDe(a.path.parts),slug:(t.slug!=null?n.append(t.slug):n.apply(a)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(a.availability),playground:this.#b(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}let u=(r!=null?this.#e.subpackages.get(KF.SubpackageId(r))?.webhooks.get(KF.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Yc.V1.WebhookId(t.endpoint));if(u!=null){let f=this.#e.getWebhookId(u);if(f==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#i.has(f)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${f}`),this.#i.add(f),{id:this.#s.get(`${this.apiDefinitionId}:${f}`),type:"webhook",webhookId:f,method:u.method,title:t.title??u.name??k1("/",...u.path),slug:(t.slug!=null?n.append(t.slug):n.apply(u)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return this.mergeEndpointPairs([...t,...r]).filter(n=>n.type==="apiPackage"?n.children.length>0:!0)}#g(t){if(t.type==="apiPackage"){let r=Yc.V1.SlugGenerator.init(t.slug),i=(this.#a.get(t.id)??[]).flatMap(f=>this.#m(f,r)),a=t.children.map(f=>this.#g(f)),u=this.#y(a,i);return{...t,children:u,pointsTo:void 0}}return t}#j(t,r){let n=[];return t.endpoints.forEach(i=>{let a=this.#e.getEndpointId(i);if(a==null)throw new Error(`Expected Endpoint ID for ${i.id}. Got undefined.`);if(this.#t.has(a))return;let u=r.apply(i);n.push({id:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:i.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),isResponseStream:i.response?.type.type==="stream",title:i.name??VDe(i.path.parts),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),t.websockets.forEach(i=>{let a=this.#e.getWebSocketId(i);if(a==null)throw new Error(`Expected WebSocket ID for ${i.id}. Got undefined.`);this.#n.has(a)||n.push({id:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:i.name??VDe(i.path.parts),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:Yc.V1.convertAvailability(i.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),t.webhooks.forEach(i=>{let a=this.#e.getWebhookId(i);if(a==null)throw new Error(`Expected Webhook ID for ${i.id}. Got undefined.`);this.#i.has(a)||n.push({id:Yc.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:i.method,title:i.name??ian(i.id),slug:r.apply(i).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),t.subpackages.forEach(i=>{if(this.#r.has(i))return;let a=this.#e.getSubpackageByIdOrLocator(i);if(a==null){this.taskContext.logger.error(`Subpackage ${i} not found in ${this.apiDefinitionId}`);return}let u=cLt(a)?r.apply(a):r,f=this.#m(i,u);f.length>0&&n.push({id:Yc.V1.NodeId(`${this.apiDefinitionId}:${i}`),type:"apiPackage",children:f,title:cLt(a)?a.displayName??ian(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0})}),n=this.mergeEndpointPairs(n),this.apiSection.alphabetized&&(n=n.sort((i,a)=>{let u=i.type==="endpointPair"?i.nonStream.title:i.title,f=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(f)})),n}#m(t,r){let n=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return n==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#j(n,r)}#b(t){if(t)return{environments:t.environments!=null&&t.environments.length>0?t.environments.map(r=>Yc.V1.EnvironmentId(r)):void 0,button:t.button!=null&&t.button.href?{href:Yc.V1.Url(t.button.href)}:void 0}}mergeEndpointPairs(t){if(this.disableEndpointPairs)return t;let r=[],n=new Map;return t.forEach(i=>{if(i.type!=="endpoint"){r.push(i);return}let a=this.#e.endpoints.get(i.endpointId);if(a==null)throw new Error(`Endpoint ${i.endpointId} not found`);let u=`${a.method} ${VDe(a.path.parts)}`,f=n.get(u);if(n.set(u,i),f==null||f.isResponseStream===i.isResponseStream){r.push(i);return}let d=r.indexOf(f),c=i.isResponseStream?i:f,o=i.isResponseStream?f:i,l={id:Yc.V1.NodeId(`${this.apiDefinitionId}:${o.endpointId}+${c.endpointId}`),type:"endpointPair",stream:c,nonStream:o};r[d]=l}),r}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}};var hnd=Yo(require("crypto"),1);function p6w(e){return hnd.default.createHash("sha256").update(e).digest("hex")}var LTa=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#n(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),p6w(r===0?t:`${t}-${r}`)}#i(t){let r=this.#n(t),n=0;for(;this.#t.has(r);)if(r=this.#n(t),n++,n>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Yc.V1.NodeId(this.#i(t))}};function ynd(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0}}var UTa=Yo(m6t(),1);var DD=Yo(m6t(),1);var dRr=Yo(m6t(),1);function vnd(e){return e._visit({alias:t=>({type:"alias",value:Ex(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:$5(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>dRr.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:dRr.FernRegistry.PropertyKey(r.name.wireValue),valueType:Ex(r.valueType),availability:$5(r.availability)})),extraProperties:v6w(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(n=>({key:dRr.FernRegistry.PropertyKey(n.name.wireValue),valueType:Ex(n.valueType),availability:$5(n.availability),description:n.docs}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(n=>({description:n.docs??void 0,discriminantValue:n.discriminantValue.wireValue,displayName:n.displayName,availability:n.availability!=null?$5(n.availability):void 0,additionalProperties:lp.types.SingleUnionTypeProperties._visit(n.shape,{samePropertiesAsObject:i=>({extends:[dRr.FernRegistry.TypeId(i.typeId)],properties:r,extraProperties:void 0}),singleProperty:i=>({extends:[],properties:[{key:dRr.FernRegistry.PropertyKey(i.name.wireValue),valueType:Ex(i.type),description:void 0,availability:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+n.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:Ex(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function Ex(e){return e._visit({container:t=>lp.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:Ex(r)}),map:({keyType:r,valueType:n})=>({type:"map",keyType:Ex(r),valueType:Ex(n)}),optional:r=>({type:"optional",itemType:Ex(r),defaultValue:void 0}),set:r=>({type:"set",itemType:Ex(r)}),literal:r=>lp.types.Literal._visit(r,{boolean:n=>({type:"literal",value:{type:"booleanLiteral",value:n}}),string:n=>({type:"literal",value:{type:"stringLiteral",value:n}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:dRr.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:lp.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>h6w(t.v2),float:()=>({type:"double",minimum:22250738585072014e-324,maximum:17976931348623157e292,default:0}),double:()=>y6w(t.v2),string:()=>_6w(t.v2),long:()=>({type:"long",default:0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:!1}),dateTime:()=>({type:"datetime",default:new Date(0).toISOString()}),date:()=>({type:"date",default:new Date(0).toISOString()}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",default:"0"}),bigInteger:()=>({type:"bigInteger",default:BigInt(0).toString()}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function _6w(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",regex:t?.pattern,minLength:t?.minLength,maxLength:t?.minLength,default:e!=null&&e.type==="string"?e.default:void 0}}function h6w(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function y6w(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function v6w(e){return typeof e=="boolean"?uT.unknown():typeof e=="string"?{type:"id",value:dRr.FernRegistry.TypeId(e),default:void 0}:Ex(e)}function Hqu(e,t){let r=e.service!=null?t.services[e.service]:void 0,n=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,i=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?g6w(r,t):[],webhooks:n!=null?b6w(n):[],websockets:i!=null?[m6w(i,t)]:[],types:e.types.map(a=>DD.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>DD.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?DD.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function b6w(e){return e.map(t=>({description:t.docs??void 0,id:DD.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Ldi(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:Ex(r.valueType),availability:$5(r.availability)})),payload:A6w(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function g6w(e,t){let r=[];for(let n of e.endpoints){let i=n.autogeneratedExamples[0],a=[];if(n.userSpecifiedExamples.length>0&&i!=null)a.push(...n.userSpecifiedExamples.map(f=>Wqu({autogeneratedExample:i,userSpecifiedExample:f,irEndpoint:n,ir:t})));else if(i!=null)a.push(Wqu({autogeneratedExample:i,irEndpoint:n,ir:t}));else if(n.response?.body?.type==="fileDownload"){let f=NPi({ir:t,service:e,endpoint:{...n,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(f.type==="success"){let d={...Wqu({autogeneratedExample:f,irEndpoint:n,ir:t}),responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(d)}}let u={availability:$5(n.availability??e.availability),auth:n.auth,description:n.docs??void 0,method:j6w(n.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?O6w({environmentsConfig:t.environments,endpoint:n}):void 0,id:DD.FernRegistry.EndpointId(n.name.originalName),originalEndpointId:n.id,name:n.displayName??Ldi(n.name.originalName),path:n.basePath!=null?{pathParameters:n.pathParameters.map(f=>({description:f.docs??void 0,key:DD.FernRegistry.PropertyKey(f.name.originalName),type:Ex(f.valueType),availability:void 0})),parts:[...C8n(n.basePath),...C8n(n.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...n.pathParameters].map(f=>({description:f.docs??void 0,key:DD.FernRegistry.PropertyKey(f.name.originalName),type:Ex(f.valueType),availability:void 0})),parts:[...t.basePath!=null?C8n(t.basePath):[],...C8n(e.basePath),...C8n(n.path)]},queryParameters:n.queryParameters.map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:Ex(f.valueType),availability:$5(f.availability)})),headers:[...e.headers,...n.headers].map(f=>({description:f.docs??void 0,key:f.name.wireValue,type:Ex(f.valueType),availability:$5(f.availability)})),request:n.requestBody!=null?D6w(n.requestBody):void 0,response:n.response!=null?S6w(n.response):void 0,errors:void 0,errorsV2:E6w(n.errors,t),examples:a};r.push(u)}return r}function m6w(e,t){return{auth:e.auth,availability:$5(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?DD.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?P6w({environmentsConfig:t.environments,channel:e}):[],id:DD.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??Ldi(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:DD.FernRegistry.PropertyKey(r.name.originalName),type:Ex(r.valueType),availability:void 0})),parts:C8n(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:Ex(r.valueType),description:r.docs,availability:$5(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:Ex(r.valueType),availability:$5(r.availability)})),messages:e.messages.map(r=>({type:DD.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:M6w(r.body),description:r.docs,availability:$5(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((n,i)=>(n[DD.FernRegistry.PropertyKey(i.name.originalName)]=i.value.jsonExample,n),{}),queryParameters:r.queryParameters.reduce((n,i)=>(n[i.name.wireValue]=i.value.jsonExample,n),{}),headers:r.headers.reduce((n,i)=>(n[i.name.wireValue]=i.value.jsonExample,n),{}),messages:r.messages.map(n=>({type:DD.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}))}}function $5(e){if(e!=null)switch(e.status){case"DEPRECATED":return DD.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return DD.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return DD.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return DD.FernRegistry.Availability.Beta;default:Lc(e.status)}}function O6w({environmentsConfig:e,endpoint:t}){let r=e.environments,n=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:DD.FernRegistry.EnvironmentId(i.id),baseUrl:i.url}));case"multipleBaseUrls":if(n==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(i=>{let a=i.urls[n];if(a==null)throw new Error(`Expected environment ${i.id} to contain url for ${n}`);return{id:DD.FernRegistry.EnvironmentId(i.id),baseUrl:a}});default:Lc(r)}}function P6w({environmentsConfig:e,channel:t}){let r=e.environments;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:DD.FernRegistry.EnvironmentId(n.id),baseUrl:w6w(n.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:Lc(r)}}function w6w(e,t){return e.replace(/^[^:]+/,t)}function j6w(e){return lp.http.HttpMethod._visit(e,{get:()=>DD.FernRegistry.HttpMethod.Get,post:()=>DD.FernRegistry.HttpMethod.Post,put:()=>DD.FernRegistry.HttpMethod.Put,patch:()=>DD.FernRegistry.HttpMethod.Patch,delete:()=>DD.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function C8n(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:DD.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function D6w(e){let t=lp.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??D4.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(n=>DD.FernRegistry.TypeId(n.typeId)),properties:r.properties.map(n=>({description:n.docs??void 0,key:DD.FernRegistry.PropertyKey(n.name.wireValue),valueType:Ex(n.valueType),availability:$5(n.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??D4.APPLICATION_JSON,shape:{type:"reference",value:Ex(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(n=>n._visit({file:i=>{let a=i._visit({file:u=>({type:"file",key:DD.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:DD.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:i=>({type:"bodyProperty",key:DD.FernRegistry.PropertyKey(i.name.wireValue),valueType:Ex(i.valueType),contentType:i.contentType,description:i.docs,availability:$5(i.availability)}),_other:()=>{}})).filter($M)},description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function S6w(e){if(e.body==null)return;let t,r=lp.http.HttpResponseBody._visit(e.body,{fileDownload:n=>(t=n.docs,{type:"fileDownload",contentType:void 0}),json:n=>(t=n.docs,{type:"reference",value:Ex(n.responseBodyType)}),text:()=>{},streamParameter:()=>{},streaming:n=>{if(n.type==="text")return t=n.docs,{type:"streamingText"};if(n.type==="json")return t=n.docs,{type:"stream",shape:{type:"reference",value:Ex(n.payload)},terminator:n.terminator};if(n.type==="sse")return t=n.docs,{type:"stream",shape:{type:"reference",value:Ex(n.payload)},terminator:n.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});if(r!=null)return{type:r,statusCode:e.statusCode,description:t}}function E6w(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let n of e){let i=t.errors[n.error.errorId];i&&r.push({type:i.type==null?void 0:{type:"alias",value:Ex(i.type)},statusCode:i.statusCode,description:i.docs??void 0,name:i.name.name.originalName,availability:void 0,examples:i.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let n of e){let i=t.errors[n.error.errorId];if(i){let a=[{key:DD.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:i.discriminantValue.name.originalName}},description:i.docs,availability:void 0}];i.type!=null&&a.push({key:DD.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:Ex(i.type),description:i.docs,availability:void 0}),r.push({type:i.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:i.statusCode,description:i.docs??void 0,availability:void 0,name:i.name.name.originalName,examples:i.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function Wqu({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:n}){let i=n.headers.map(f=>{let d=f.valueType.type==="container"&&f.valueType.container.type==="literal"?f.valueType.container.literal._visit({boolean:c=>`${c}`,string:c=>c,_other:()=>{}}):void 0;if(d!=null)return{name:f.name,value:{jsonExample:d,shape:lp.ExampleTypeReferenceShape.primitive(lp.ExamplePrimitive.string({original:d}))}}}).filter($M),a=e?.example??t.example,{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((f,d)=>(f[DD.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,f),{}),queryParameters:a.queryParameters.reduce((f,d)=>(f[d.name.wireValue]=d.value.jsonExample,f),{}),headers:[...i,...a.serviceHeaders,...a.endpointHeaders].reduce((f,d)=>(f[d.name.wireValue]=d.value.jsonExample,f),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:f=>{if(a.request==null)return;let d={};if(lS(a.request.jsonExample)){let c=a.request.jsonExample;for(let o of f.properties)o._visit({file:l=>{let g=c[l.key.wireValue];if(l.type==="file")d[l.key.wireValue]={type:"filename",value:typeof g=="string"?g:"<file1>"};else if(l.type==="fileArray"){let O=(Array.isArray(g)?g:[g]).filter(P=>typeof P=="string");d[l.key.wireValue]={type:"filenames",value:O}}},bodyProperty:l=>{d[l.name.wireValue]={type:"json",value:c[l.name.wireValue]}},_other:Gqt})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:lp.http.ExampleResponse._visit(a.response,{ok:f=>f._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+f.type)}}),error:({error:f})=>{let d=n.errors[f.errorId];if(d==null)throw new Error("Cannot find error "+f.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:f=>f._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:f=>f.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:f=>f._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(c=>c.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:c,data:o})=>({event:c,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+f.type)}}),error:f=>f.body!=null?{type:"json",value:f.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(f=>aDe._visit(f,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter($M)}}function A6w(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>DD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:DD.FernRegistry.PropertyKey(t.name.wireValue),valueType:Ex(t.valueType),availability:$5(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:Ex(e.payloadType)},description:e.docs};default:Lc(e)}}function M6w(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>DD.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:DD.FernRegistry.PropertyKey(t.name.wireValue),valueType:Ex(t.valueType),availability:$5(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:Ex(e.bodyType)};default:Lc(e)}}var Qqu=Yo(m6t(),1);function bnd(e,t,r){let n=e.schemes[0];if(e.schemes.length===1&&n!=null)switch(n.type){case"basic":return{type:"basicAuth",passwordName:n.password.originalName,usernameName:n.username.originalName};case"bearer":return{type:"bearerAuth",tokenName:n.token.originalName};case"header":return{type:"header",headerWireValue:n.name.wireValue,nameOverride:n.name.name.originalName,prefix:n.prefix};case"oauth":{let i=n.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Qqu.FernRegistry.EndpointId(n.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:Qqu.FernRegistry.JqString(i)}}}:{type:"bearerAuth",tokenName:"token"}}default:Lc(n)}}function WDe({ir:e,snippetsConfig:t,playgroundConfig:r}){let n={types:{},subpackages:{},rootPackage:Hqu(e.rootPackage,e),auth:bnd(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(i=>({availability:$5(i.availability),description:i.docs??void 0,key:i.name.wireValue,type:Ex(i.valueType)})),navigation:void 0};for(let[i,a]of Object.entries(e.types))n.types[UTa.FernRegistry.TypeId(i)]={description:a.docs??void 0,name:a.name.name.originalName,shape:vnd(a.shape),availability:$5(a.availability)};for(let[i,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;n.subpackages[UTa.FernRegistry.api.v1.SubpackageId(i)]={subpackageId:UTa.FernRegistry.api.v1.SubpackageId(i),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...Hqu(a,e)}}return n}var Jqu=Yo(m6t(),1);async function Gqu({organization:e,workspace:t,context:r,token:n,audiences:i,snippetsConfig:a,playgroundConfig:u}){let f=await aQ({workspace:t,audiences:i,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:r}),d=Ttn({token:n.value}),c=WDe({ir:f,snippetsConfig:a,playgroundConfig:u});r.logger.debug("Calling registerAPI... ",JSON.stringify(c,void 0,4));let o=await d.api.v1.register.registerApiDefinition({orgId:Jqu.FernRegistry.OrgId(e),apiId:Jqu.FernRegistry.ApiId(f.apiName.originalName),definition:c});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:f};switch(o.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",o.error)}}var x6w=new uan({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function gnd(e,t,r){return fPi(sPi(WDe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),KF.ApiDefinitionId(t),x6w))}function mnd(e){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.js!=null&&e.js.files.forEach(r=>{t.add(r.absolutePath)}),t}function hMr(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}Pnd.default.extend(wnd.default);var T6w=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),Ond=0,C6w=async({ir:e})=>(Ond++,`${e.apiName.snakeCase.unsafeName}-${Ond}`),yMr=class{domain;docsWorkspace;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;constructor(t,r,n,i,a,u=T6w,f=C6w){this.domain=t,this.docsWorkspace=r,this.fernWorkspaces=n,this.taskContext=i,this.editThisPage=a,this.uploadFiles=u,this.registerApi=f}#e=LTa.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;async resolve(){this._parsedDocsConfig=await bTe.parseDocsConfiguration({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.fernWorkspaces.forEach(d=>{d.changelog?.files.forEach(c=>{let o=jq(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[o]=c.contents})}),this.markdownFilesToFullSlugs=this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages);for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=await FTu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(d),context:this.taskContext});for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=await LTu({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMdx:this.resolveFilepath(d),context:this.taskContext});let t=mnd(this.parsedDocsConfig);for(let[d,c]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:o,markdown:l}=iPi(c,{absolutePathToMdx:this.resolveFilepath(d),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Ms.of(d)]=l;for(let g of o)t.add(g)}let r=Array.from(t).map(d=>({absoluteFilePath:d,relativeFilePath:this.toRelativeFilepath(d)}));(await this.uploadFiles(r)).forEach(d=>{this.collectedFileIds.set(d.absoluteFilePath,d.fileId)});let i=this.getDocsBasePath();for(let[d,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ms.of(d)]=RTu(c,this.collectedFileIds,new Map(Array.from(this.markdownFilesToFullSlugs.entries()).map(([o,l])=>[o,k1(i,l)])),{absolutePathToMdx:this.resolveFilepath(d),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let a={};Object.entries(this.parsedDocsConfig.pages).forEach(([d,c])=>{let o=q6w(this.editThisPage,d);a[VIt.PageId(d)]={markdown:c,editThisPageUrl:o?VIt.Url(o):void 0}});let u=await this.convertDocsConfiguration(),f={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let d=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let o=rT(this.docsWorkspace.absoluteFilePath,c);(await(0,VTa.stat)(o)).isDirectory()?(await eTe(o,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{d.add(O)}):o.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&d.add(o)})),f=Object.fromEntries(await Promise.all([...d].map(async c=>{let o=this.toRelativeFilepath(c),l=(await(0,VTa.readFile)(c)).toString();return[o,l]})))}return{config:u,pages:a,jsFiles:f}}resolveFilepath(t){if(t!=null)return rT(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return jq(this.docsWorkspace.absoluteFilePath,t)}getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[n,i]of Object.entries(t)){let u=(0,jnd.default)(i).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(n),u.trim())}return r}getDocsBasePath(){return new URL(hMr(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?VIt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(n=>({...n,url:VIt.Url(n.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(n=>({...n,value:VIt.Url(n.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:void 0,ga4:void 0,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},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,playground:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.fernWorkspaces.length===1&&this.fernWorkspaces[0]!=null)return this.fernWorkspaces[0];if(t.apiName!=null){let r=this.fernWorkspaces.find(n=>n.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}async toRootNode(){let t=Yc.V1.SlugGenerator.init(Yc.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),n=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:n,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0}}async toRootChild(t){return QTn(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t)})}toLandingPageNode(t,r){let n=Yc.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({urlSlug:t.slug??nH(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(n),title:t.title,slug:i.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:void 0}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:n}){let i=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,n):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(i,r.items,n):await this.toSidebarRootNode(i,r.items,n);return{type:"unversioned",id:i,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((i,a)=>this.toVersionNode(i,r,a===0)))}}async toVersionNode(t,r,n){let i=this.#e.get(t.version),a=r.setVersionSlug(t.version),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(i,t.navigation.items,a):await this.toSidebarRootNode(i,t.navigation.items,a);return{type:"version",id:i,versionId:Yc.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:n,availability:t.availability!=null?I6w(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,r):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0}}async toSidebarRootNode(t,r,n){let i=this.#e.get(`${t}/root`),a=await Promise.all(r.map(f=>this.toNavigationChild(i,f,n))),u=[];return a.forEach(f=>{switch(f.type){case"apiReference":case"section":u.push(f);return;case"changelog":case"link":case"page":{let d=u[u.length-1];d?.type!=="sidebarGroup"&&(d={id:this.#e.get(`${i}/group`),type:"sidebarGroup",children:[]},u.push(d)),d.children.push(f);return}default:Lc(f)}}),{type:"sidebarRoot",id:i,children:u}}async toNavigationChild(t,r,n){return QTn(r)._visit({page:async i=>this.toPageNode(i,n),apiSection:async i=>this.toApiSectionNode(i,n),section:async i=>this.toSectionNode(t,i,n),link:async i=>this.toLinkNode(i),changelog:async i=>this.toChangelogNode(i,n)})}async toApiSectionNode(t,r){let n=this.getFernWorkspaceForApiSection(t),i=ynd(t.snippetsConfiguration),a=await aQ({workspace:n,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:this.taskContext}),u=await this.registerApi({ir:a,snippetsConfig:i,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),f=gnd(a,u,{oauth:t.playground?.oauth});return new FTa(t,f,r,n,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}async toChangelogNode(t,r){return new gan(this.markdownFilesToFullSlugs,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Yc.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let n=Yc.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({urlSlug:t.slug??nH(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:i.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:void 0}}async toSectionNode(t,r,n){let i=this.toRelativeFilepath(r.overviewAbsolutePath),a=i?Yc.PageId(i):void 0,u=this.#e.get(a??`${t}/section`),f=n.apply({urlSlug:r.slug??nH(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug});return{id:u,type:"section",overviewPageId:a,slug:f.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:r.hidden,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(d=>this.toNavigationChild(u,d,f))),authed:void 0,pointsTo:void 0,noindex:void 0}}async convertTabbedNavigation(t,r,n){let i=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:i,children:await Promise.all(r.map(a=>this.toTabChild(i,a,n)))}}async toTabChild(t,r,n){return QTn(r.child)._visit({link:({href:i})=>this.toTabLinkNode(r,i),layout:({layout:i})=>this.toTabNode(t,r,i,n),changelog:({changelog:i})=>this.toTabChangelogNode(r,i,n)})}async toTabChangelogNode(t,r,n){return new gan(this.markdownFilesToFullSlugs,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:n,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:Yc.V1.Url(r),icon:t.icon}}async toTabNode(t,r,n,i){let a=this.#e.get(`${t}/tab`),u=i.apply({urlSlug:r.slug??nH(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,n,u)}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):VIt.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:n}=this.parsedDocsConfig,i=r?.[t],a=n?.[t];return{logo:this.getFileId(i),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let n=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${n}`,variants:t.variants.map(i=>({fontFile:this.getFileId(i.absolutePath),weight:i.weight,style:i.style!=null?[i.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter($M),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:VIt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":n,...i}=this.parsedDocsConfig.metadata;return{...i,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(n)}}convertFileIdOrUrl(t){if(t!=null)return QTn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:VIt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function q6w(e,t){if(e?.github==null)return;let{owner:r,repo:n,branch:i="main",host:a="https://github.com"}=e.github;return`${hMr(a)}/${r}/${n}/blob/${i}/fern/${t}`}function I6w(e){switch(e){case"beta":return Yc.V1.NavigationV1Availability.Beta;case"deprecated":return Yc.V1.NavigationV1Availability.Deprecated;case"ga":return Yc.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Yc.V1.NavigationV1Availability.Stable;default:Lc(e)}}var M0d=Yo(xnd(),1),v3u=Yo(Q6u(),1),x0d=Yo(require("http"),1),Gqa=Yo(require("path"),1);var tsd=require("events"),wCa=Yo(require("fs"),1),Aan=Yo(require("path"),1);var zud=Yo(require("os"),1),Rud=300,bRr=20,i1i=1e7,Fud=zud.default.platform();var v8w=Fud==="darwin",J6u=Fud==="win32",gRr=v8w||J6u,Lud=3e3,Uud=2e4,G6u=1250;var pLt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(pLt||(pLt={}));var Ean;(function(e){e.CHANGE="change",e.RENAME="rename"})(Ean||(Ean={}));var a1i;(function(e){e.CHANGE="change",e.ERROR="error"})(a1i||(a1i={}));var Lm;(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"})(Lm||(Lm={}));var xk;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(xk||(xk={}));var b8w=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,f,d=0,c=0,o=()=>{let C=Date.now(),F=C-d,K=C-c,ee=F>=t||K>=a;return[C,ee]},l=C=>{if(c=C,!u)return;let F=u;u=void 0,e.apply(void 0,F)},g=()=>{B(0)},O=()=>{f&&(g(),l(Date.now()))},P=C=>{if(c=C,n)return l(C)},j=C=>{if(i&&u)return l(C);u=void 0},M=()=>{f=void 0;let[C,F]=o();return F?j(C):q(C)},q=C=>{let F=C-d,K=C-c,ee=t-F,J=a-K,G=Math.min(ee,J);return B(G)},B=C=>{f&&clearTimeout(f),!(C<=0)&&(f=setTimeout(M,C))},I=(...C)=>{let[F,K]=o(),ee=!!f;if(u=C,d=F,(K||!f)&&B(t),K)return ee?l(F):P(F)};return I.cancel=g,I.flush=O,I},gCa=b8w;var Z6u=Yo(require("fs"),1),OCa=Yo(require("path"),1);var Ax=Yo(require("fs"),1),oQ=require("util");var vMr=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},_Lt=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var $6u=Yo(require("process"),1),Vud=$6u.default.getuid?!$6u.default.getuid():!1,Wud=1e4,Aae=()=>{};var o1i={isChangeErrorOk:e=>{if(!o1i.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Vud&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!o1i.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(!o1i.isNodeError(e))throw e;if(!o1i.isChangeErrorOk(e))throw e}},Zz=o1i;var K6u=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Wud,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()}}}}},Hud=new K6u;var bMr=(e,t)=>function(n){return function i(...a){return Hud.schedule().then(u=>{let f=c=>(u(),c),d=c=>{if(u(),Date.now()>=n)throw c;if(t(c)){let o=Math.round(100*Math.random());return new Promise(g=>setTimeout(g,o)).then(()=>i.apply(void 0,a))}throw c};return e.apply(void 0,a).then(f,d)})}},gMr=(e,t)=>function(n){return function i(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>n)throw u;if(t(u))return i.apply(void 0,a);throw u}}};var g8w={attempt:{chmod:vMr((0,oQ.promisify)(Ax.default.chmod),Zz.onChangeError),chown:vMr((0,oQ.promisify)(Ax.default.chown),Zz.onChangeError),close:vMr((0,oQ.promisify)(Ax.default.close),Aae),fsync:vMr((0,oQ.promisify)(Ax.default.fsync),Aae),mkdir:vMr((0,oQ.promisify)(Ax.default.mkdir),Aae),realpath:vMr((0,oQ.promisify)(Ax.default.realpath),Aae),stat:vMr((0,oQ.promisify)(Ax.default.stat),Aae),unlink:vMr((0,oQ.promisify)(Ax.default.unlink),Aae),chmodSync:_Lt(Ax.default.chmodSync,Zz.onChangeError),chownSync:_Lt(Ax.default.chownSync,Zz.onChangeError),closeSync:_Lt(Ax.default.closeSync,Aae),existsSync:_Lt(Ax.default.existsSync,Aae),fsyncSync:_Lt(Ax.default.fsync,Aae),mkdirSync:_Lt(Ax.default.mkdirSync,Aae),realpathSync:_Lt(Ax.default.realpathSync,Aae),statSync:_Lt(Ax.default.statSync,Aae),unlinkSync:_Lt(Ax.default.unlinkSync,Aae)},retry:{close:bMr((0,oQ.promisify)(Ax.default.close),Zz.isRetriableError),fsync:bMr((0,oQ.promisify)(Ax.default.fsync),Zz.isRetriableError),open:bMr((0,oQ.promisify)(Ax.default.open),Zz.isRetriableError),readFile:bMr((0,oQ.promisify)(Ax.default.readFile),Zz.isRetriableError),rename:bMr((0,oQ.promisify)(Ax.default.rename),Zz.isRetriableError),stat:bMr((0,oQ.promisify)(Ax.default.stat),Zz.isRetriableError),write:bMr((0,oQ.promisify)(Ax.default.write),Zz.isRetriableError),writeFile:bMr((0,oQ.promisify)(Ax.default.writeFile),Zz.isRetriableError),closeSync:gMr(Ax.default.closeSync,Zz.isRetriableError),fsyncSync:gMr(Ax.default.fsyncSync,Zz.isRetriableError),openSync:gMr(Ax.default.openSync,Zz.isRetriableError),readFileSync:gMr(Ax.default.readFileSync,Zz.isRetriableError),renameSync:gMr(Ax.default.renameSync,Zz.isRetriableError),statSync:gMr(Ax.default.statSync,Zz.isRetriableError),writeSync:gMr(Ax.default.writeSync,Zz.isRetriableError),writeFileSync:gMr(Ax.default.writeFileSync,Zz.isRetriableError)}},Qud=g8w;var mCa=Yo(require("fs"),1),u1i=Yo(require("path"),1);var Jud={then:e=>{e()}};var Y6u=()=>{};var X6u=()=>{let e=Y6u,t=Y6u,r=!1,n=!1;return{promise:new Promise((d,c)=>{e=o=>(r=!0,d(o)),t=o=>(n=!0,c(o))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}};X6u.wrap=async e=>{let t=X6u();return await e(t),t.promise};var Gud=X6u;var $ud=e=>Array.isArray(e)?e:[e],Kud=e=>typeof e=="function",Yud=()=>{let{promise:e,resolve:t}=Gud(),r=0,n=()=>{r+=1},i=()=>{r-=1,!r&&t()};return(()=>{n(),queueMicrotask(i)})(),{promise:e,increment:n,decrement:i}};var m8w=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,a=t?.ignore??[],u=$ud(a).map(It=>Kud(It)?It:cr=>It.test(cr)),f=It=>u.some(cr=>cr(It)),d=t?.signal??{aborted:!1},c=t?.onDirents||(()=>{}),o=[],l=new Set,g={},O=[],P=new Set,j={},M=[],q=new Set,B={},I={},C=new Set,F={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},K={directories:o,directoriesNames:l,directoriesNamesToPaths:g,files:O,filesNames:P,filesNamesToPaths:j,symlinks:M,symlinksNames:q,symlinksNamesToPaths:B,map:I},{promise:ee,increment:J,decrement:G}=Yud(),te=0,Xe=(It,cr,Hr,Gt)=>{C.has(cr)||te>=i||(te+=1,It.directories.push(cr),It.directoriesNames.add(Hr),o.push(cr),l.add(Hr),g.propertyIsEnumerable(Hr)||(g[Hr]=[]),g[Hr].push(cr),C.add(cr),!(Gt>=n)&&(te>=i||or(cr,Gt+1)))},Re=(It,cr,Hr)=>{C.has(cr)||te>=i||(te+=1,It.files.push(cr),It.filesNames.add(Hr),O.push(cr),P.add(Hr),j.propertyIsEnumerable(Hr)||(j[Hr]=[]),j[Hr].push(cr),C.add(cr))},Pt=(It,cr,Hr,Gt)=>{C.has(cr)||te>=i||(te+=1,It.symlinks.push(cr),It.symlinksNames.add(Hr),M.push(cr),q.add(Hr),B.propertyIsEnumerable(Hr)||(B[Hr]=[]),B[Hr].push(cr),C.add(cr),r&&(Gt>=n||te>=i||jr(cr,Gt+1)))},Ct=(It,cr,Hr,Gt,wn)=>{d.aborted||f(cr)||(Gt.isDirectory()?Xe(It,cr,Hr,wn):Gt.isFile()?Re(It,cr,Hr):Gt.isSymbolicLink()&&Pt(It,cr,Hr,wn))},Wt=(It,cr,Hr,Gt)=>{if(d.aborted)return;let wn=cr===u1i.default.sep?"":u1i.default.sep,An=Hr.name,Ht=`${cr}${wn}${An}`;f(Ht)||(Hr.isDirectory()?Xe(It,Ht,An,Gt):Hr.isFile()?Re(It,Ht,An):Hr.isSymbolicLink()&&Pt(It,Ht,An,Gt))},Bt=(It,cr,Hr,Gt)=>{for(let wn=0,An=Hr.length;wn<An;wn++)Wt(It,cr,Hr[wn],Gt)},or=(It,cr)=>{d.aborted||cr>n||te>=i||(J(),mCa.default.readdir(It,{withFileTypes:!0},(Hr,Gt)=>{if(Hr||d.aborted||!Gt.length)return G();(c(Gt)||Jud).then(()=>{let An=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Bt(An,It,Gt,cr),G()})}))},jr=async(It,cr)=>{J(),mCa.default.realpath(It,(Hr,Gt)=>{if(Hr||d.aborted)return G();mCa.default.stat(Gt,async(wn,An)=>{if(wn||d.aborted)return G();let Ht=u1i.default.basename(Gt),er=I[It]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Ct(er,Gt,Ht,An,cr),G()})})};return(async(It,cr=1)=>(It=u1i.default.normalize(It),C.add(It),or(It,cr),await ee,d.aborted?F:K))(e)},Xud=m8w;var hLt={lang:{debounce:gCa,attempt:e=>{try{return e()}catch(t){return hLt.lang.castError(t)}},castArray:e=>hLt.lang.isArray(e)?e:[e],castError:e=>hLt.lang.isError(e)?e:hLt.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(hLt.lang.isNaN(e))return hLt.lang.isNaN(t);if(hLt.lang.isPrimitive(e)||hLt.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(OCa.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Z6u.default.realpathSync.native(e):Z6u.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===OCa.default.sep&&t.length-e.length>OCa.default.sep.length,poll:(e,t=Uud)=>Qud.retry.stat(t)(e,{bigint:!0}).catch(hLt.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await Xud(e,{depth:r,limit:n,ignore:t,signal:i});return[u.directories,u.files]}}}},yw=hLt;var PCa=Yo(require("path"),1);var k6u=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||yw.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=Rud){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,a=async(f,d)=>{let c=this.options.ignoreInitial?[]:f,o=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...c,...o]);this.onTargetEvents(l)},u=yw.lang.debounce(()=>{this.watcher.isClosed()||(r=a(n,i),n=[],i=new Set)},t);return async(f,d="",c=!1)=>{c?await this.eventsPopulate([d],n,!0):i.add(d),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[a,u]=i,f=r[u];return a===f||a===Lm.CHANGE&&f===Lm.ADD||(r[u]=a,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let a=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,i]),u===Lm.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):u===Lm.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let a=this.options.recursive?this.options.depth??bRr:Math.min(1,this.options.depth??bRr),u=this.options.limit??i1i,[f,d]=await yw.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),c=[...f,...d];return await Promise.all(c.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let a of this.watcher._poller.stats.keys())yw.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Lm.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!gRr&&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(Lm.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Lm.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(PCa.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Lm.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(PCa.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(Lm.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===Lm.ADD?this.onTargetAdd(n):r===Lm.ADD_DIR?this.onTargetAddDir(n):r===Lm.CHANGE?this.onTargetChange(n):r===Lm.UNLINK?this.onTargetUnlink(n):r===Lm.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=Ean.CHANGE,r){if(this.watcher.isClosed())return;let n=PCa.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){J6u&&t.code==="EPERM"?this.onWatcherChange(Ean.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(a1i.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(a1i.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Ean.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&gRr&&this.options.native!==!1?this.options.depth??bRr:Math.min(1,this.options.depth??bRr),n=this.options.limit??i1i,[i,a]=await yw.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...i,...a];await Promise.all(u.map(f=>{if(!this.watcher._poller.stats.has(f)&&!this.watcher.isIgnored(f,this.options.ignore))return this.onWatcherEvent(Ean.CHANGE,f,t)}))}}},Zud=k6u;var Tk={interval:100,intervalId:void 0,fns:new Map,init:()=>{Tk.intervalId||(Tk.intervalId=setInterval(Tk.resolve,Tk.interval))},reset:()=>{Tk.intervalId&&(clearInterval(Tk.intervalId),delete Tk.intervalId)},add:(e,t)=>{Tk.fns.set(e,Date.now()+t),Tk.init()},remove:e=>{Tk.fns.delete(e)},resolve:()=>{if(!Tk.fns.size)return Tk.reset();let e=Date.now();for(let[t,r]of Tk.fns)r>=e||(Tk.remove(t),t())}},s1i=Tk;var c1i=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=G6u){let{ino:n,targetPath:i,events:a,locks:u}=t,f=()=>{let l=this._watcher._poller.paths.find(n||-1,g=>g!==i);if(l&&l!==i){if(yw.fs.getRealPath(i,!0)===l)return;this._watcher.event(a.rename,l,i)}else this._watcher.event(a.add,i)};if(!n)return f();let d=()=>{u.add.delete(n),s1i.remove(c)},c=()=>{d(),f()};s1i.add(c,r);let o=()=>{let l=u.unlink.get(n);if(!l)return;d();let g=l();i===g?a.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(a.change,i):this._watcher.event(a.rename,g,i)};u.add.set(n,o),o()}getLockUnlink(t,r=G6u){let{ino:n,targetPath:i,events:a,locks:u}=t,f=()=>{this._watcher.event(a.unlink,i)};if(!n)return f();let d=()=>{u.unlink.delete(n),s1i.remove(c)},c=()=>{d(),f()};s1i.add(c,r);let o=()=>(d(),i);u.unlink.set(n,o),u.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,Lm.ADD,pLt.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,Lm.ADD_DIR,pLt.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,Lm.UNLINK,pLt.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,Lm.UNLINK_DIR,pLt.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}}};c1i.DIR_EVENTS={add:Lm.ADD_DIR,rename:Lm.RENAME_DIR,unlink:Lm.UNLINK_DIR};c1i.FILE_EVENTS={add:Lm.ADD,change:Lm.CHANGE,rename:Lm.RENAME,unlink:Lm.UNLINK};var kud=c1i;var eIu=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(yw.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(yw.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(yw.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(yw.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return yw.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);yw.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},tIu=eIu;var rIu=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}},esd=rIu;var nIu=class{constructor(){this.inos={},this.paths=new tIu,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let a=i[t];if(a&&!(n&&a[1]!==n))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await yw.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new esd(n)}reset(){this.inos={},this.paths=new tIu,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,Lm.ADD,i),[Lm.ADD];if(i.isDirectory())return this.updateIno(t,Lm.ADD_DIR,i),[Lm.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,Lm.UNLINK,n),[Lm.UNLINK];if(n.isDirectory())return this.updateIno(t,Lm.UNLINK_DIR,n),[Lm.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,Lm.CHANGE,i),[Lm.CHANGE]);if(i.isDirectory())return this.updateIno(t,Lm.UNLINK,n),this.updateIno(t,Lm.ADD_DIR,i),[Lm.UNLINK,Lm.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,Lm.UNLINK_DIR,n),this.updateIno(t,Lm.ADD,i),[Lm.UNLINK_DIR,Lm.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,Lm.UNLINK_DIR,n),this.updateIno(t,Lm.ADD_DIR,i),[Lm.UNLINK_DIR,Lm.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=n.isFile()?pLt.FILE:pLt.DIR;i[t]=[n.ino,a]}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)}}},iIu=nIu;var aIu=class e extends tsd.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(xk.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(xk.CLOSE,i)),this._readyWait=new Promise(i=>this.on(xk.READY,i)),this._locker=new kud(this),this._roots=new Set,this._poller=new iIu,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&&(yw.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(xk.CLOSE))}error(t){if(this.isClosed())return!1;let r=yw.lang.castError(t);return this.emit(xk.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(xk.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(xk.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&yw.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&yw.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 a of[...i])r&&a.filePath!==r||this.watcherClose(a);if(n)for(let a in this._watchers)yw.fs.isSubPath(t,a)&&this.watchersClose(a,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 a=new Zud(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=yw.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(f=>f.handler===n&&(!f.filePath||f.filePath===i)&&f.options.ignore===r.ignore&&!!f.options.native==!!r.native&&(!r.recursive||f.options.recursive)))return!0;let u=Aan.default.dirname(t);for(let f=1;f<1/0;f++){if(this._watchers[u]?.find(o=>(f===1||o.options.recursive&&f<=(o.options.depth??bRr))&&o.handler===n&&(!o.filePath||o.filePath===i)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&gRr&&o.options.native!==!1)))return!0;if(!gRr)break;let c=Aan.default.dirname(t);if(u===c)break;u=c}return!1}async watchDirectories(t,r,n,i,a){if(this.isClosed())return;t=yw.lang.uniq(t).sort();let u;for(let f of t)if(!this.isIgnored(f,r.ignore)&&!this.watcherExists(f,r,n,i))try{let d=!r.recursive||gRr&&r.native!==!1?r:{...r,recursive:!1},o={watcher:wCa.default.watch(f,d),handler:n,options:r,folderPath:f,filePath:i},l=u=await this.watcherAdd(o,a);if(this._roots.has(i||f)){let O={...r,ignoreInitial:!0,recursive:!1},P=Aan.default.dirname(f),j=f;await this.watchDirectories([P],O,n,j,l)}}catch(d){this.error(d)}return u}async watchDirectory(t,r,n,i,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||gRr&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,a));{r={...r,recursive:!0};let u=r.depth??bRr,f=r.limit??i1i,[d]=await yw.fs.readdir(t,r.ignore,u,f,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let c=await this.watchDirectories([t],r,n,i,a);if(d.length){let o=yw.fs.getDepth(t);for(let l of d){let g=yw.fs.getDepth(l),O=Math.max(0,u-(g-o)),P={...r,depth:O};await this.watchDirectories([l],P,n,i,a||c)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},a=(c,o)=>{o===t&&(d(),n())},u=new e(a),f=()=>{this._subwatchers.add(i),this.on(xk.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(i),this.removeListener(xk.CLOSE,d),u.close()};return f()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=Aan.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,a=new iIu,u=await this.watchPolling(t,r,async()=>{i||!(await a.update(t,r.pollingTimeout)).length||i||(i=!0,u(),n())})}async watchPolling(t,r,n){if(this.isClosed())return yw.lang.noop;if(this.pollerExists(t,r))return yw.lang.noop;let i={...r,interval:r.pollingInterval??Lud},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(xk.CLOSE,f),wCa.default.watchFile(t,i,n)},f=()=>{this._pollers.delete(a),this.removeListener(xk.CLOSE,f),wCa.default.unwatchFile(t,n)};return yw.lang.attempt(u),()=>yw.lang.attempt(f)}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=yw.lang.uniq(t).sort(),t.every((a,u)=>t.every((f,d)=>d===u||!yw.fs.isSubPath(a,f))))await Promise.all(t.map(a=>this.watchPath(a,r,n)));else for(let a of t)await this.watchPath(a,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=Aan.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await yw.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 a=Aan.default.dirname(t);return(await yw.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=yw.lang.noop){if(yw.lang.isFunction(t))return this.watch([],{},t);if(yw.lang.isUndefined(t))return this.watch([],r,n);if(yw.lang.isFunction(r))return this.watch(t,{},r);if(yw.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=yw.lang.castArray(t);i.forEach(a=>this._roots.add(a)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==yw.lang.noop&&this.on(xk.ALL,n),r.readdirMap=void 0,this.ready())}},rsd=aIu;var x5w=Yo(osd(),1),T5w=Yo(yIu(),1),C5w=Yo(bIu(),1),q5w=Yo(DIu(),1),EIu=Yo(ncd(),1);var j0d=Yo(g2a(),1),CLt=require("fs/promises"),Qqa=require("os"),d3u=Yo(require("path"),1),D0d=Yo(Nne(),1),S0d=Yo(Mpd(),1),p3u=Yo(f3u(),1),DJw="etag",_3u="preview",SJw="bundle",h3u=".fern";function EJw(){return yf(v_.of((0,Qqa.homedir)()),Ms.of(h3u),Ms.of(_3u))}function Jqa(){return yf(v_.of((0,Qqa.homedir)()),Ms.of(h3u),Ms.of(_3u),Ms.of(SJw))}function AJw(){return yf(v_.of((0,Qqa.homedir)()),Ms.of(h3u),Ms.of(_3u),Ms.of(DJw))}async function E0d({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let n=await(0,p3u.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!n.ok)return{type:"failure"};let i=n.body,u=await new S0d.default.Parser().parseStringPromise(i),f=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],d=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=AJw();if(r){let B=await Wh(c),I;if(B&&(t.debug("Reading existing ETag"),I=(await(0,CLt.readFile)(c)).toString()),I!=null&&I===f)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle")}t.debug("Creating tmp directory to download docs preview bundle");let o=await D0d.default.dir({prefix:"fern"}),l=v_.of(o.path);t.debug(`Downloading docs preview bundle from ${d3u.default.join(e,d)}`);let g=await(0,p3u.fetcher)({url:`${d3u.default.join(e,d)}`,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!g.ok)return t.error("Failed to download docs preview bundle."),{type:"failure"};let O=yf(l,Ms.of("output.zip")),P=g.body;if(P==null)return{type:"failure"};let j=Buffer.from(P);await(0,CLt.writeFile)(O,j),t.debug(`Wrote output.zip to ${O}`);let M=EJw();await Wh(M)&&await(0,CLt.rm)(M,{recursive:!0}),await(0,CLt.mkdir)(M,{recursive:!0}),t.debug(`rm -rf ${M}`);let q=Jqa();return await(0,CLt.mkdir)(q,{recursive:!0}),await(0,j0d.default)(O,q),await(0,CLt.writeFile)(c,f),t.debug(`Downloaded bundle to ${q}`),{type:"success"}}async function A0d({domain:e,project:t,context:r}){let n=t.docsWorkspaces,i=t.apiWorkspaces;if(n==null)throw new Error("No docs workspace found in project");let a=await Promise.all(i.map(async g=>await g.toFernWorkspace({context:r},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),u=new y3u(r),f={},c=await new yMr(e,n,a,r,void 0,async g=>g.map(O=>{let P=a8r();return f[P]={type:"url",url:Yc.Url(`/_local${bXo(O.absoluteFilePath)}`)},{absoluteFilePath:O.absoluteFilePath,relativeFilePath:O.relativeFilePath,fileId:P}}),async g=>u.addReferencedAPI(g)).resolve(),o=W2u({writeShape:c,files:{}}),l=Q2u({dbShape:o.config});return{apis:u.getAPIsForDefinition(),config:l,files:{},filesV2:f,pages:o.pages,search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0}}var y3u=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:n}){try{let i=a8r(),a=sPi(WDe({ir:t,snippetsConfig:r,playgroundConfig:n}),MU.ApiDefinitionId(i),new uan({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=fPi(a);return this.apis[i]=u,i}catch(i){let a=i;throw this.context.logger.error(`Failed to read referenced API: ${a?.message} ${a?.stack}`),a.stack!=null&&this.context.logger.error(a?.stack),i}}getAPIsForDefinition(){return this.apis}};var MJw={pages:{},apis:{},files:{},filesV2:{},config:{navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0,playground:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function b3u({initialProject:e,reloadProject:t,validateProject:r,context:n,port:i,bundlePath:a}){if(a!=null)n.logger.info(`Using bundle from path: ${a}`);else try{let I="https://prod-local-preview-bundle2.s3.amazonaws.com/";if(I==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await E0d({bucketUrl:I,logger:n.logger,preferCached:!0})}catch(I){let C=Jqa();if(I instanceof Error&&n.logger.debug(`Failed to download latest docs bundle: ${I.message}`),await Wh(C))n.logger.warn("Falling back to cached bundle...");else{n.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=cb(e.config._absolutePath),f=(0,v3u.default)(),d=x0d.default.createServer(f),c=new EIu.default({server:d}),o=new Set;function l(I){for(let C of o)C.send(JSON.stringify(I))}c.on("connection",function(C){o.add(C),C.on("close",function(){o.delete(C)})}),f.use((0,M0d.default)());let g=new URL(hMr(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${i}`)),O=e,P,j=async()=>{n.logger.info("Reloading docs...");let I=Date.now();try{O=await t(),n.logger.info("Validating docs..."),await r(O);let C=await A0d({domain:`${g.host}${g.pathname}`,project:O,context:n});return n.logger.info(`Reload completed in ${Date.now()-I}ms`),C}catch(C){return P==null?n.logger.error("Failed to read docs configuration. Rendering blank page."):n.logger.error("Failed to read docs configuration. Rendering last successful configuration."),C instanceof Error&&C instanceof Error&&C.stack&&n.logger.debug(`${C.message}
1991
1991
  ${C.stack}`),P}};P=await j();let M=O.apiWorkspaces.flatMap(I=>I.getAbsoluteFilePaths()),q=a?v_.of(Gqa.default.resolve(a)):Jqa();new rsd([u,...M],{recursive:!0,ignoreInitial:!0,debounce:1e3,renameDetection:!0}).on("all",async(I,C,F)=>{n.logger.info(nl.dim(`[${I}] ${C}`)),l({version:1,type:"startReload"});let K=await j();K!=null&&(P=K),l({version:1,type:"finishReload"})}),f.post("/v2/registry/docs/load-with-url",async(I,C)=>{try{let F=P??MJw,K={baseUrl:{domain:g.host,basePath:g.pathname},definition:F,lightModeEnabled:F.config.colorsV3?.type!=="dark"};C.send(K)}catch(F){n.logger.error("Error loading docs",F.message),C.status(500).send()}}),f.get(/^\/_local\/(.*)/,(I,C)=>C.sendFile(`/${I.params[0]}`)),f.get("/",(I,C,F)=>I.headers.upgrade==="websocket"?c.handleUpgrade(I,I.socket,Buffer.alloc(0),K=>{c.emit("connection",K,I)}):F()),f.use("/_next",v3u.default.static(Gqa.default.join(q,"/_next"))),f.use("*",async(I,C)=>C.sendFile(Gqa.default.join(q,"/[[...slug]].html"))),f.listen(i),n.logger.info(`Running server on http://localhost:${i}`),await new Promise(()=>{})}var fQ={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function k2(e,t){return async r=>{r!=null&&await e.docs?.(r,[...t,"docs"])}}async function Q2e({example:e,visitor:t,nodePath:r}){if(typeof e=="string")e.startsWith(uFt)&&await t.exampleTypeReference?.(e,r);else if(lS(e))for(let n of Object.values(e))await Q2e({example:n,visitor:t,nodePath:r});else if(Array.isArray(e))for(let n of e)await Q2e({example:n,visitor:t,nodePath:r})}function rBt(e){return async(t,r,{_default:n,validation:i,location:a}={})=>{await e.typeReference?.({typeReference:t,_default:n,validation:i,location:a,nodePath:r},r)}}async function T0d({service:e,visitor:t,nodePath:r}){await t.httpService?.(e,r),await VP(e,{url:async n=>{await t.serviceBaseUrl?.(n,[...r,"url"])},"base-path":cl,"display-name":cl,availability:cl,headers:async n=>{await C0d({headers:n,visitor:t,nodePath:[...r,"headers"]})},audiences:cl,auth:cl,"path-parameters":async n=>{await $qa({pathParameters:n,visitor:t,nodePath:[...r,"path-parameters"]})},endpoints:async n=>{for(let[i,a]of Object.entries(n)){let u=[...r,"endpoints",i];await xJw({endpointId:i,endpoint:a,service:e,visitor:t,nodePathForEndpoint:u})}},idempotent:cl,transport:cl,source:cl})}async function xJw({endpointId:e,endpoint:t,service:r,visitor:n,nodePathForEndpoint:i}){let a=rBt(n);await n.httpEndpoint?.({endpointId:e,endpoint:t,service:r},i),await VP(t,{docs:k2(n,i),"display-name":cl,availability:cl,"base-path":cl,path:cl,idempotent:cl,url:async u=>{await n.endpointBaseUrl?.({baseUrl:u,service:r},[...i,"url"])},"path-parameters":async u=>{await $qa({pathParameters:u,visitor:n,nodePath:[...i,"path-parameters"]})},request:async u=>{if(u==null)return;let f=[...i,"request"];if(typeof u=="string"){await a(u,f,{location:"requestReference"});return}await VP(u,{name:cl,docs:k2(n,f),"query-parameters":async d=>{if(d!=null)for(let[c,o]of Object.entries(d)){let l=[...f,"query-parameters",c];await n.queryParameter?.({queryParameterKey:c,queryParameter:o},l),typeof o=="string"?await a(o,l):await VP(o,{name:cl,docs:k2(n,l),availability:cl,type:async g=>{await a(g,[...l,"type"],{_default:o.default,validation:o.validation})},"allow-multiple":cl,audiences:cl,encoding:cl,default:cl,validation:cl})}},"content-type":cl,headers:async d=>{await C0d({headers:d,visitor:n,nodePath:[...f,"headers"]})},body:async d=>{if(d==null)return;let c=[...f,"body"];typeof d=="string"?await a(d,c,{location:"requestReference"}):v6(d)?(await n.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:d},c),await VP(d,{extends:async o=>{if(o==null)return;let l=typeof o=="string"?[o]:o;for(let g of l){let O=[...c,"extends",g];await n.extension?.(g,O),await a(g,O)}},properties:async o=>{if(o!=null)for(let[l,g]of Object.entries(o)){let O=[...c,"properties",l];typeof g=="string"?await a(g,O,{location:fQ.InlinedRequestProperty}):await VP(g,{name:cl,docs:k2(n,O),availability:cl,type:async P=>{await a(P,[...O,"type"],{location:fQ.InlinedRequestProperty,_default:g.default,validation:g.validation})},"content-type":cl,audiences:cl,encoding:cl,default:cl,validation:cl})}},"extra-properties":cl})):(await k2(n,c)(d.docs),await a(d.type,c))}})},audiences:cl,method:cl,auth:cl,"stream-condition":async u=>{await n.streamCondition?.({streamCondition:u,endpoint:t},[...i,"stream-condition"])},"response-stream":async u=>{u!=null&&(typeof u=="string"?await a(u,[...i,"response-stream"],{location:fQ.StreamingResponse}):await a(u.type,[...i,"response-stream"],{location:fQ.StreamingResponse}))},response:async u=>{if(u==null)return;let f=[...i,"response"];typeof u=="string"?await a(u,f,{location:fQ.Response}):await VP(u,{docs:k2(n,f),type:async d=>{await a(d,[...f,"type"],{location:fQ.Response})},property:cl,"status-code":cl})},errors:async u=>{if(u!=null)for(let f of u){let d=[...i,"errors",typeof f=="string"?f:f.error];typeof f=="string"?await n.errorReference?.(f,d):await VP(f,{docs:k2(n,d),error:async c=>{await n.errorReference?.(c,[...d,"error"])}})}},examples:async u=>{if(u!=null)for(let[f,d]of u.entries())await TJw({nodePathForExample:[...i,{key:"examples",arrayIndex:f}],visitor:n,service:r,endpoint:t,example:d})},pagination:cl})}async function TJw({nodePathForExample:e,visitor:t,service:r,endpoint:n,example:i}){if(i.headers==null&&i["path-parameters"]==null&&i["query-parameters"]==null&&i.request==null&&i.response==null&&i["code-samples"]!=null)return;await t.exampleHttpEndpointCall?.({service:r,endpoint:n,example:i},e);let a=[...e,"headers"];if(await t.exampleHeaders?.({service:r,endpoint:n,examples:i.headers},a),i.headers!=null)for(let o of Object.values(i.headers))await Q2e({example:o,visitor:t,nodePath:a});let u=[...e,"path-parameters"];if(await t.examplePathParameters?.({service:r,endpoint:n,examples:i["path-parameters"]},u),i["path-parameters"]!=null)for(let o of Object.values(i["path-parameters"]))await Q2e({example:o,visitor:t,nodePath:u});let f=[...e,"query-parameters"];if(await t.exampleQueryParameters?.({service:r,endpoint:n,examples:i["query-parameters"]},f),i["query-parameters"]!=null)for(let o of Object.values(i["query-parameters"]))await Q2e({example:o,visitor:t,nodePath:f});let d=[...e,"request"];await t.exampleRequest?.({service:r,endpoint:n,example:i.request},d),i.request!=null&&await Q2e({example:i.request,visitor:t,nodePath:d});let c=[...e,"response"];if(await t.exampleResponse?.({service:r,endpoint:n,example:i.response},c),i.response!=null&&await Etn(n,i.response,{body:async o=>{o.body!=null&&await Q2e({example:o.body,visitor:t,nodePath:c}),o.error!=null&&await t.errorReference?.(o.error,[...c,"error"])},stream:async o=>{for(let l of o.stream)await Q2e({example:l,visitor:t,nodePath:c})},events:async o=>{for(let{data:l}of o.stream)await Q2e({example:l,visitor:t,nodePath:c})}}),i["code-samples"]!=null)for(let[o,l]of i["code-samples"].entries())await t.exampleCodeSample?.({service:r,endpoint:n,example:i,sample:l},[...e,{key:"code-samples",arrayIndex:o}])}async function $qa({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let n=rBt(t);for(let[i,a]of Object.entries(e)){let u=[...r,i];await t.pathParameter?.({pathParameterKey:i,pathParameter:a},u),bIn(a)?typeof a=="string"?await t.variableReference?.(a,u):await VP(a,{docs:k2(t,u),variable:async f=>await t.variableReference?.(f,[...u,"variable"]),availability:cl}):typeof a=="string"?await n(a,u):await VP(a,{docs:k2(t,u),type:async f=>{await n(f,[...u,"type"],{_default:a.default,validation:a.validation})},availability:cl,encoding:cl,default:cl,validation:cl,name:cl,audiences:cl})}}async function C0d({headers:e,visitor:t,nodePath:r}){if(e==null)return;let n=rBt(t);for(let[i,a]of Object.entries(e)){let u=[...r,i];await t.header?.({headerKey:i,header:a},u),typeof a=="string"?await n(a,u):await VP(a,{name:cl,availability:cl,type:async f=>{await n(f,u,{_default:a.default,validation:a.validation})},docs:k2(t,u),audiences:cl,encoding:cl,env:cl,default:cl,validation:cl})}}async function q0d({typeDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e)){let a=[...r,n];await t.typeName?.(n,a),await g3u({typeName:n,declaration:i,visitor:t,nodePathForType:a})}}async function g3u({typeName:e,declaration:t,visitor:r,nodePathForType:n}){let i=rBt(r);await r.typeDeclaration?.({typeName:{isInlined:!1,name:e},declaration:t,nodePath:n},n);let a=async u=>{if(u!=null)for(let[f,d]of u.entries()){let c=[...n,{key:"examples",arrayIndex:f}];await r.exampleType?.({typeName:e,typeDeclaration:t,example:d},c),await Q2e({example:d.value,nodePath:c,visitor:r})}};await zz(t,{alias:async u=>{typeof u=="string"?await i(u,n):await VP(u,{type:async f=>{await i(f,[...n,"type"])},docs:k2(r,n),availability:cl,audiences:cl,examples:a,validation:cl,encoding:cl,source:cl})},object:async u=>{await VP(u,{docs:k2(r,n),extends:async f=>{if(f==null)return;let d=typeof f=="string"?[f]:f;for(let c of d){let o=[...n,"extends",c];await r.extension?.(c,o),await i(c,o)}},properties:async f=>{if(f!=null)for(let[d,c]of Object.entries(f)){let o=[...n,"properties",d];typeof c=="string"?await i(c,o):await VP(c,{name:cl,docs:k2(r,o),availability:cl,type:async l=>{await i(l,[...o,"type"],{_default:c.default,validation:c.validation})},audiences:cl,encoding:cl,default:cl,validation:cl})}},"extra-properties":cl,availability:cl,audiences:cl,encoding:cl,source:cl,examples:a})},discriminatedUnion:async u=>{await VP(u,{docs:k2(r,n),discriminant:cl,extends:async f=>{if(f==null)return;let d=typeof f=="string"?[f]:f;for(let c of d){let o=[...n,"extends",c];await r.extension?.(c,o),await i(c,o)}},union:async f=>{for(let[d,c]of Object.entries(f)){let o=[...n,"union",d];typeof c=="string"?await i(c,o):await VP(c,{docs:k2(r,o),name:cl,key:cl,type:async l=>{typeof l=="string"&&await i(l,[...n,"type"])},"display-name":cl,availability:cl})}},"base-properties":cl,availability:cl,audiences:cl,encoding:cl,source:cl,examples:a})},undiscriminatedUnion:async u=>{await VP(u,{docs:k2(r,n),discriminated:cl,union:async f=>{for(let[d,c]of f.entries()){let o=[...n,`union[${d}]`];typeof c!="string"&&await VP(c,{docs:k2(r,o),type:async l=>{await i(l,[...n,"type"])},"display-name":cl})}},availability:cl,audiences:cl,encoding:cl,source:cl,examples:a})},enum:async u=>{await VP(u,{docs:k2(r,n),enum:async f=>{for(let d of f){let c=[...n,typeof d=="string"?d:d.name??d.value];typeof d!="string"&&await VP(d,{docs:k2(r,c),name:cl,value:cl,casing:cl})}},availability:cl,audiences:cl,default:cl,encoding:cl,source:cl,examples:a})}})}async function I0d({errorDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e)){let a=[...r,n];await t.errorDeclaration?.({errorName:n,declaration:i},a),await CJw({errorName:n,declaration:i,visitor:t,nodePathForError:a})}}async function CJw({errorName:e,declaration:t,visitor:r,nodePathForError:n}){let i=rBt(r);typeof t=="string"?await i(t,n):await VP(t,{docs:k2(r,n),"status-code":cl,type:async a=>{if(a==null)return;let u=[...n,"type"];typeof a=="string"?await i(a,u):await g3u({typeName:e,declaration:a,visitor:r,nodePathForType:u})},examples:async a=>{if(a!=null)for(let u of a){let f=[...n,"type"];await r.exampleError?.({errorName:e,declaration:t,example:u},f)}}})}async function B0d({imports:e,visitor:t,nodePath:r}){if(e!=null)for(let[n,i]of Object.entries(e))await t.import?.({importPath:i,importedAs:n},[...r,n])}async function N0d({webhook:e,visitor:t,nodePathForWebhook:r}){let n=rBt(t);await VP(e,{"display-name":cl,method:cl,examples:cl,headers:async i=>{await qJw({headers:i,visitor:t,nodePath:[...r,"headers"]})},payload:async i=>{let a=[...r,"payload"];if(typeof i=="string"){await n(i,a,{location:"requestReference"});return}if(IJw(i)){await n(i.type,[...a,"type"],{location:"requestReference"});return}let u=[...a];await t.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:i},u),await VP(i,{name:cl,extends:async f=>{if(f==null)return;let d=typeof f=="string"?[f]:f;for(let c of d){let o=[...u,"extends",c];await t.extension?.(c,o),await n(c,o)}},properties:async f=>{if(f!=null)for(let[d,c]of Object.entries(f)){let o=[...u,"properties",d];typeof c=="string"?await n(c,o,{location:fQ.InlinedRequestProperty}):await VP(c,{name:cl,docs:k2(t,o),availability:cl,type:async l=>{await n(l,[...o,"type"],{_default:c.default,validation:c.validation,location:fQ.InlinedRequestProperty})},audiences:cl,encoding:cl,default:cl,validation:cl})}}})},audiences:cl,availability:cl,docs:k2(t,r)})}async function qJw({headers:e,visitor:t,nodePath:r}){if(e==null)return;let n=rBt(t);for(let[i,a]of Object.entries(e)){let u=[...r,i];await t.header?.({headerKey:i,header:a},u),typeof a=="string"?await n(a,u):await VP(a,{name:cl,availability:cl,type:async f=>{await n(f,u,{_default:a.default,validation:a.validation})},docs:k2(t,u),audiences:cl,encoding:cl,env:cl,default:cl,validation:cl})}}function IJw(e){return e.type!=null}async function dQ(e,t){await VP(e,{docs:k2(t,[]),imports:async r=>{await B0d({imports:r,visitor:t,nodePath:["imports"]})},types:async r=>{await q0d({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:async r=>{r!=null&&await T0d({service:r,visitor:t,nodePath:["service"]})},webhooks:async r=>{for(let[n,i]of Object.entries(r??{}))await N0d({webhook:i,visitor:t,nodePathForWebhook:["webhooks",n]})},channel:cl,errors:async r=>{await I0d({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}async function m3u(e,t){await VP(e,{docs:cl,imports:cl,types:cl,service:cl,webhooks:cl,errors:cl,channel:cl,export:async r=>{await t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:async r=>{await t.navigation?.(r,["navigation"])}})}async function O3u(e,t){await t.file?.(e,[]),await VP(e,{version:cl,name:cl,"default-url":cl,"display-name":cl,imports:cl,auth:cl,"idempotency-headers":cl,"auth-schemes":async r=>{await Promise.all(Object.entries(r??{}).map(async([n,i])=>{Auu(i)&&await t.oauth?.({name:n,oauth:i},["auth-scheme",n])}))},pagination:cl,"default-environment":async r=>{await t.defaultEnvironment?.(r,["default-environment"])},docs:cl,headers:cl,environments:async r=>{if(r!=null)for(let[n,i]of Object.entries(r))await t.environment?.({environmentId:n,environment:i},["environments",n])},"error-discrimination":async r=>{await t.errorDiscrimination?.(r,["error-discrimination"])},audiences:cl,errors:async r=>{if(r!=null)for(let n of r)await t.errorReference?.(n,["errors",n])},"base-path":cl,"path-parameters":async r=>{await $qa({pathParameters:r,visitor:t,nodePath:["path-parameters"]})},variables:async r=>{if(r!=null)for(let[n,i]of Object.entries(r))await t.variableDeclaration?.({variableId:n,variable:i},["variables",n])}})}var Kqa=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function z0d({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let u=async(f,d)=>{for(let c of r){let o=c.definitionFile?.[a];if(o!=null){let l=await o(f,{relativeFilepath:e,contents:t});n(l.map(g=>({severity:g.severity,relativeFilepath:e,nodePath:d,message:g.message})))}}};return{[a]:u}}return{...i("docs"),...i("import"),...i("typeReference"),...i("typeDeclaration"),...i("typeName"),...i("httpService"),...i("httpEndpoint"),...i("pathParameter"),...i("queryParameter"),...i("streamCondition"),...i("header"),...i("errorDeclaration"),...i("errorReference"),...i("exampleType"),...i("exampleTypeReference"),...i("exampleHttpEndpointCall"),...i("exampleCodeSample"),...i("exampleHeaders"),...i("examplePathParameters"),...i("exampleQueryParameters"),...i("exampleRequest"),...i("exampleResponse"),...i("variableReference"),...i("extension"),...i("serviceBaseUrl"),...i("endpointBaseUrl"),...i("exampleError")}}function R0d({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let u=async(f,d)=>{for(let c of r){let o=c.packageMarker?.[a];if(o!=null){let l=await o(f,{relativeFilepath:e,contents:t});n(l.map(g=>({severity:g.severity,relativeFilepath:e,nodePath:d,message:g.message})))}}};return{[a]:u}}return{...i("export"),...i("navigation")}}function F0d({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:n}){function i(a){let u=async(f,d)=>{for(let c of r){let o=c.rootApiFile?.[a];if(o!=null){let l=await o(f,{relativeFilepath:e,contents:t});n(l.map(g=>({severity:g.severity,relativeFilepath:e,nodePath:d,message:g.message})))}}};return{[a]:u}}return{...i("file"),...i("oauth"),...i("defaultEnvironment"),...i("environment"),...i("errorDiscrimination"),...i("errorReference"),...i("variableDeclaration"),...i("variableReference"),...i("pathParameter")}}function BJw(e,t,r){if(!iae(r,t))return[{severity:"error",message:`The generator ${e} requires CLI version ${t} or later (current version: ${r}). Please run \`fern upgrade\` to upgrade your CLI version and use this generator.`}]}function NJw(e){return Number(e.replace("v",""))}async function zJw(e){let t=Spa({token:void 0}),r=await t.generators.getGeneratorByImage({dockerImage:e.name});if(!r.ok||r.body==null)return;let n=await t.generators.versions.getGeneratorRelease(r.body.id,e.version);if(n.ok)return n.body.irVersion}var P3u={name:"compatible-ir-version",create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e,cliVersion:t})=>{let r=Spa({token:void 0});if(t==null)return[];let n=await r.generators.cli.getCliRelease(t);if(!n.ok)return[];let i=n.body.irVersion,a;if(e["ir-version"]!=null)a=NJw(e["ir-version"]);else{let f=await zJw(e);if(f==null)return[];a=f}if(a<=i)return[];let u=await r.generators.cli.getMinCliForIr(a);return u.ok?BJw(e.name,u.body.version,t)??[]:[]}}})};var w3u={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(NAr(e.definition)),r=new Set;return t.forEach(n=>{let i=yf(e.definition.absoluteFilePath,Ms.of(n));r.add(i)}),{definitionFile:{import:async({importedAs:n,importPath:i},{relativeFilepath:a})=>{let u=[],f=yf(e.definition.absoluteFilePath,cb(a),Ms.of(i));return r.has(f)||u.push({severity:"error",message:`Import ${nl.bold(n)} points to non-existent path ${nl.bold(i)}.`}),u}}}}};function Yqa(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(vIn(r))for(let n of Object.keys(r.urls))t.includes(n)||t.push(n);return t},[])}var j3u={name:"matching-environment-urls",create:({workspace:e})=>{let t=Yqa(e);return t.length===0?{}:{rootApiFile:{environment:({environmentId:r,environment:n})=>{let i=[],a=u=>{i.push({severity:"error",message:`Environment ${r} is missing URL for ${nl.bold(u)}`})};return zEr(n,{singleBaseUrl:()=>{for(let u of t)a(u)},multipleBaseUrls:u=>{for(let f of t)u.urls[f]==null&&a(f)}}),i}}}}};var D3u={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=RJw(e.definition.namedDefinitionFiles);return{definitionFile:{import:async({importPath:r},{relativeFilepath:n})=>{let i=t[n];if(i==null)return[];let a=oRr({referencedIn:n,importPath:Ms.of(r)});return i.filter(({chainWithoutStartingFilepath:f})=>f.length===0||f[0]===a).map(f=>({severity:"error",message:f.chainWithoutStartingFilepath.length===0?"A file cannot import itself":`Circular import detected: ${[f.startingFilepath,...f.chainWithoutStartingFilepath,f.startingFilepath].join(" -> ")}`}))}}}}};function RJw(e){let t={};for(let r of Fzt(e))t[r]=L0d(r,[r],e);return t}function L0d(e,t,r){let n=[],i=r[e];if(i==null)return[];if(i.contents.imports!=null)for(let a of Object.values(i.contents.imports)){let u=oRr({referencedIn:e,importPath:Ms.of(a)});t.includes(u)?t[0]===u&&t[0]===FJw(t)&&n.push({startingFilepath:u,chainWithoutStartingFilepath:t.slice(1)}):n.push(...L0d(u,[...t,u],r))}return n}function FJw(e){return e.reduce((t,r)=>r<t?r:t)}var ex=oLt({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var Xqa=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new eM(t)}isTypeComplex(t,r){let n=qO({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:ex,rootApiFile:this.workspace.definition.rootApiFile.contents}),i=this.typeResolver.resolveType({type:t,file:n});if(i==null)return;let a=new Set;return this.isResolvedReferenceComplex({type:i,file:n,visited:a})}isResolvedReferenceComplex({type:t,file:r,visited:n}){switch(t._type){case"container":return this.isResolvedContainerComplex({type:t.container,file:r,visited:n});case"named":return this.isNamedTypeComplex({type:t,file:r,visited:n});case"primitive":return!1;case"unknown":return!0;default:Lc(t)}}isResolvedContainerComplex({type:t,file:r,visited:n}){switch(t._type){case"literal":return!1;case"map":return(this.isResolvedReferenceComplex({type:t.keyType,file:r,visited:n})||this.isResolvedReferenceComplex({type:t.valueType,file:r,visited:n}))&&!(t.keyType._type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType._type==="unknown");case"optional":case"list":case"set":return this.isResolvedReferenceComplex({type:t.itemType,file:r,visited:n});default:Lc(t)}}isNamedTypeComplex({type:t,file:r,visited:n}){if(n.has(t.rawName))return!1;if(n.add(t.rawName),UNr(t.declaration))return!0;if(V6t(t.declaration))return!1;if(mA(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:n});if(mIn(t.declaration)){for(let i of t.declaration.union){let a=typeof i=="string"?i:i.type,u=this.isTypeComplex(a,{contents:r.definitionFile,relativeFilepath:r.relativeFilepath});if(u!=null&&u)return!0}return!1}Lc(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:n,visited:i}){return QIt({typeName:t,objectDeclaration:r,typeResolver:this.typeResolver,definitionFile:n.definitionFile,workspace:this.workspace,filepathOfDeclaration:n.relativeFilepath,smartCasing:!1}).some(u=>this.isComplex({type:u.resolvedPropertyType,file:n,visited:i}))}isComplex({type:t,file:r,visited:n}){switch(t._type){case"named":return this.isNamedTypeComplex({type:t,file:r,visited:n});case"primitive":case"unknown":return!1;case"container":return this.isComplexContainer({type:t.container,file:r,visited:n});default:Lc(t)}}isComplexContainer({type:t,file:r,visited:n}){switch(t._type){case"literal":return!0;case"map":return this.isComplex({type:t.keyType,file:r,visited:n})||this.isComplex({type:t.valueType,file:r,visited:n});case"optional":case"list":case"set":return this.isComplex({type:t.itemType,file:r,visited:n});default:Lc(t)}}};var S3u={name:"no-complex-query-params",create:({workspace:e})=>{let t=new Xqa(e);return{definitionFile:{queryParameter:({queryParameter:r},n)=>{let i=typeof r=="string"?r:r.type,a=t.isTypeComplex(i,n);return a!=null&&a?[{severity:"error",message:`${i} is not a valid type for a query parameter`}]:[]}}}}};var E3u={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===PTa?[{severity:"error",message:`Path parameter ${nl.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function pwi({service:e,endpoint:t}){return e["base-path"]+t.path}var Zqa=class{root=new A3u;registerEndpoint(t){this.root.insert(this.getPathPartsForEndpoint(t),t)}getConflictingEndpoints(t){return this.root.getMatchingEndpoints(this.getPathPartsForEndpoint(t)).filter(r=>!(r.relativeFilepath===t.relativeFilepath&&r.endpointId===t.endpointId)&&r.endpoint.method===t.endpoint.method)}getPathPartsForEndpoint(t){return pwi({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},A3u=class e{childPaths={};childPathParam;endpointsThatEndWithThisNode=[];insert(t,r){let[n,...i]=t;if(n==null){this.endpointsThatEndWithThisNode.push(r);return}(this.isPathParam(n)?this.childPathParam??=new e:this.childPaths[n]??=new e).insert(i,r)}getMatchingEndpoints(t){let[r,...n]=t;if(r==null)return this.endpointsThatEndWithThisNode;let i=[];if(this.isPathParam(r))i.push(...Object.values(this.childPaths).flatMap(a=>a.getMatchingEndpoints(n)));else{let a=this.childPaths[r];a!=null&&i.push(...a.getMatchingEndpoints(n))}return this.childPathParam!=null&&i.push(...this.childPathParam.getMatchingEndpoints(n)),i}isPathParam(t){return t.startsWith("{")&&t.endsWith("}")}};var M3u={name:"no-conflicting-endpoint-paths",create:async({workspace:e})=>{let t=new Zqa;return await Jz(e,async(r,n)=>{await dQ(n,{httpEndpoint:({service:i,endpointId:a,endpoint:u})=>{t.registerEndpoint({service:i,endpointId:a,endpoint:u,relativeFilepath:r})}})}),{definitionFile:{httpEndpoint:({service:r,endpoint:n,endpointId:i},{relativeFilepath:a})=>{let u=t.getConflictingEndpoints({service:r,endpointId:i,endpoint:n,relativeFilepath:a});return u.length===0?[]:[{severity:"warning",message:[`Endpoint path ${pwi({service:r,endpoint:n})} conflicts with other endpoints:`,...u.map(f=>` - ${f.relativeFilepath} -> ${f.endpointId} ${nl.dim(pwi({service:f.service,endpoint:f.endpoint}))}`)].join(`
1992
1992
  `)}]}}}}};var x3u={name:"no-conflicting-request-wrapper-properties",create:({workspace:e})=>({definitionFile:{httpEndpoint:({endpoint:t,service:r},{contents:n,relativeFilepath:i})=>{let a=LJw({endpoint:t,service:r,relativeFilepath:i,definitionFile:n,workspace:e}),u=[];for(let[f,d]of Object.entries(a))d.length<=1||u.push({severity:"error",message:`Multiple request properties have the name ${nl.bold(f)}. This is not suitable for code generation. Use the "name" property to deconflict.
1993
1993
  `+d.map(c=>` - ${UJw(c)}`).join(`
@@ -2319,7 +2319,7 @@ error-discriminant: error`;await(0,XRo.writeFile)(r,i)}}};var X26={version:"0.0.
2319
2319
  `));if(await r.takeOverTerminal(async()=>{await QB6(n)||r.failAndThrow("Canceled.")}),r.getResult()===E4.Failure)return;let i=n.flatMap(({migrations:a,version:u})=>a.map(f=>({migration:f,context:r.addInteractiveTask({name:`${u} ${f.name}`})})));for(let{migration:a,context:u}of i){let f=u.start();if(await a.run({context:f}),f.finish(),f.getResult()===E4.Failure){r.logger.error("Failed to run migrations. You may need to undo changes to files.");return}}}async function QB6(e){let t="wantsToContinue",r=["Some migrations need to be run:"];for(let{migrations:i}of e)for(let a of i)r.push(SZ({prefix:" \u25E6 ",content:`${a.name}
2320
2320
  ${nl.dim(a.summary)}`}));r.push("Do you wish to continue?");let{[t]:n}=await gma.prompt({name:t,type:"confirm",message:r.join(`
2321
2321
  `)});return n}var NUg=require("fs/promises");function ZJ(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];if(process.env.NODE_ENV!=="production"){var i=kB6[e],a=i?typeof i=="function"?i.apply(null,r):i:"unknown error nr: "+e;throw Error("[Immer] "+a)}throw Error("[Immer] minified error nr: "+e+(r.length?" "+r.map(function(u){return"'"+u+"'"}).join(","):"")+". Find the full error at: https://bit.ly/3cXEKWf")}function pai(e){return!!e&&!!e[kAe]}function KSn(e){return!!e&&(function(t){if(!t||typeof t!="object")return!1;var r=Object.getPrototypeOf(t);if(r===null)return!0;var n=Object.hasOwnProperty.call(r,"constructor")&&r.constructor;return n===Object||typeof n=="function"&&Function.toString.call(n)===e46}(e)||Array.isArray(e)||!!e[xUg]||!!e.constructor[xUg]||gzc(e)||mzc(e))}function WWi(e,t,r){r===void 0&&(r=!1),hai(e)===0?(r?Object.keys:Dzc)(e).forEach(function(n){r&&typeof n=="symbol"||t(n,e[n],e)}):e.forEach(function(n,i){return t(i,n,e)})}function hai(e){var t=e[kAe];return t?t.i>3?t.i-4:t.i:Array.isArray(e)?1:gzc(e)?2:mzc(e)?3:0}function _zc(e,t){return hai(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function JB6(e,t){return hai(e)===2?e.get(t):e[t]}function TUg(e,t,r){var n=hai(e);n===2?e.set(t,r):n===3?(e.delete(t),e.add(r)):e[t]=r}function GB6(e,t){return e===t?e!==0||1/e==1/t:e!=e&&t!=t}function gzc(e){return XB6&&e instanceof Map}function mzc(e){return ZB6&&e instanceof Set}function $Sn(e){return e.o||e.t}function Ozc(e){if(Array.isArray(e))return Array.prototype.slice.call(e);var t=t46(e);delete t[kAe];for(var r=Dzc(t),n=0;n<r.length;n++){var i=r[n],a=t[i];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(t[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(Object.getPrototypeOf(e),t)}function Pzc(e,t){return t===void 0&&(t=!1),wzc(e)||pai(e)||!KSn(e)||(hai(e)>1&&(e.set=e.add=e.clear=e.delete=$B6),Object.freeze(e),t&&WWi(e,function(r,n){return Pzc(n,!0)},!0)),e}function $B6(){ZJ(2)}function wzc(e){return e==null||typeof e!="object"||Object.isFrozen(e)}function Wjr(e){var t=r46[e];return t||ZJ(18,e),t}function wUg(){return process.env.NODE_ENV==="production"||_ai||ZJ(0),_ai}function lzc(e,t){t&&(Wjr("Patches"),e.u=[],e.s=[],e.v=t)}function c9o(e){hzc(e),e.p.forEach(KB6),e.p=null}function hzc(e){e===_ai&&(_ai=e.l)}function jUg(e){return _ai={p:[],l:_ai,h:e,m:!0,_:0}}function KB6(e){var t=e[kAe];t.i===0||t.i===1?t.j():t.O=!0}function fzc(e,t){t._=t.p.length;var r=t.p[0],n=e!==void 0&&e!==r;return t.h.g||Wjr("ES5").S(t,e,n),n?(r[kAe].P&&(c9o(t),ZJ(4)),KSn(e)&&(e=l9o(t,e),t.l||f9o(t,e)),t.u&&Wjr("Patches").M(r[kAe].t,e,t.u,t.s)):e=l9o(t,r,[]),c9o(t),t.u&&t.v(t.u,t.s),e!==CUg?e:void 0}function l9o(e,t,r){if(wzc(t))return t;var n=t[kAe];if(!n)return WWi(t,function(a,u){return DUg(e,n,t,a,u,r)},!0),t;if(n.A!==e)return t;if(!n.P)return f9o(e,n.t,!0),n.t;if(!n.I){n.I=!0,n.A._--;var i=n.i===4||n.i===5?n.o=Ozc(n.k):n.o;WWi(n.i===3?new Set(i):i,function(a,u){return DUg(e,n,i,a,u,r)}),f9o(e,i,!1),r&&e.u&&Wjr("Patches").R(n,r,e.u,e.s)}return n.o}function DUg(e,t,r,n,i,a){if(process.env.NODE_ENV!=="production"&&i===r&&ZJ(5),pai(i)){var u=l9o(e,i,a&&t&&t.i!==3&&!_zc(t.D,n)?a.concat(n):void 0);if(TUg(r,n,u),!pai(u))return;e.m=!1}if(KSn(i)&&!wzc(i)){if(!e.h.F&&e._<1)return;l9o(e,i),t&&t.A.l||f9o(e,i)}}function f9o(e,t,r){r===void 0&&(r=!1),e.h.F&&e.m&&Pzc(t,r)}function dzc(e,t){var r=e[kAe];return(r?$Sn(r):e)[t]}function SUg(e,t){if(t in e)for(var r=Object.getPrototypeOf(e);r;){var n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Object.getPrototypeOf(r)}}function yzc(e){e.P||(e.P=!0,e.l&&yzc(e.l))}function pzc(e){e.o||(e.o=Ozc(e.t))}function vzc(e,t,r){var n=gzc(t)?Wjr("MapSet").N(t,r):mzc(t)?Wjr("MapSet").T(t,r):e.g?function(i,a){var u=Array.isArray(i),f={i:u?1:0,A:a?a.A:wUg(),P:!1,I:!1,D:{},l:a,t:i,k:null,o:null,j:null,C:!1},d=f,c=bzc;u&&(d=[f],c=VWi);var o=Proxy.revocable(d,c),l=o.revoke,g=o.proxy;return f.k=g,f.j=l,g}(t,r):Wjr("ES5").J(t,r);return(r?r.A:wUg()).p.push(n),n}function YB6(e){return pai(e)||ZJ(22,e),function t(r){if(!KSn(r))return r;var n,i=r[kAe],a=hai(r);if(i){if(!i.P&&(i.i<4||!Wjr("ES5").K(i)))return i.t;i.I=!0,n=EUg(r,a),i.I=!1}else n=EUg(r,a);return WWi(n,function(u,f){i&&JB6(i.t,u)===f||TUg(n,u,t(f))}),a===3?new Set(n):n}(e)}function EUg(e,t){switch(t){case 2:return new Map(e);case 3:return Array.from(e)}return Ozc(e)}var AUg,_ai,jzc=typeof Symbol<"u"&&typeof Symbol("x")=="symbol",XB6=typeof Map<"u",ZB6=typeof Set<"u",MUg=typeof Proxy<"u"&&Proxy.revocable!==void 0&&typeof Reflect<"u",CUg=jzc?Symbol.for("immer-nothing"):((AUg={})["immer-nothing"]=!0,AUg),xUg=jzc?Symbol.for("immer-draftable"):"__$immer_draftable",kAe=jzc?Symbol.for("immer-state"):"__$immer_state";var kB6={0:"Illegal state",1:"Immer drafts cannot have computed properties",2:"This object has been frozen and should not be mutated",3:function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},4:"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",5:"Immer forbids circular references",6:"The first or second argument to `produce` must be a function",7:"The third argument to `produce` must be a function or undefined",8:"First argument to `createDraft` must be a plain object, an array, or an immerable object",9:"First argument to `finishDraft` must be a draft returned by `createDraft`",10:"The given draft is already finalized",11:"Object.defineProperty() cannot be used on an Immer draft",12:"Object.setPrototypeOf() cannot be used on an Immer draft",13:"Immer only supports deleting array indices",14:"Immer only supports setting array indices and the 'length' property",15:function(e){return"Cannot apply patch, path doesn't resolve: "+e},16:'Sets cannot have "replace" patches.',17:function(e){return"Unsupported patch operation: "+e},18:function(e){return"The plugin for '"+e+"' has not been loaded into Immer. To enable the plugin, import and call `enable"+e+"()` when initializing your application."},20:"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",21:function(e){return"produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '"+e+"'"},22:function(e){return"'current' expects a draft, got: "+e},23:function(e){return"'original' expects a draft, got: "+e},24:"Patching reserved attributes like __proto__, prototype and constructor is not allowed"},e46=""+Object.prototype.constructor,Dzc=typeof Reflect<"u"&&Reflect.ownKeys?Reflect.ownKeys:Object.getOwnPropertySymbols!==void 0?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames,t46=Object.getOwnPropertyDescriptors||function(e){var t={};return Dzc(e).forEach(function(r){t[r]=Object.getOwnPropertyDescriptor(e,r)}),t},r46={},bzc={get:function(e,t){if(t===kAe)return e;var r=$Sn(e);if(!_zc(r,t))return function(i,a,u){var f,d=SUg(a,u);return d?"value"in d?d.value:(f=d.get)===null||f===void 0?void 0:f.call(i.k):void 0}(e,r,t);var n=r[t];return e.I||!KSn(n)?n:n===dzc(e.t,t)?(pzc(e),e.o[t]=vzc(e.A.h,n,e)):n},has:function(e,t){return t in $Sn(e)},ownKeys:function(e){return Reflect.ownKeys($Sn(e))},set:function(e,t,r){var n=SUg($Sn(e),t);if(n?.set)return n.set.call(e.k,r),!0;if(!e.P){var i=dzc($Sn(e),t),a=i?.[kAe];if(a&&a.t===r)return e.o[t]=r,e.D[t]=!1,!0;if(GB6(r,i)&&(r!==void 0||_zc(e.t,t)))return!0;pzc(e),yzc(e)}return e.o[t]===r&&typeof r!="number"&&(r!==void 0||t in e.o)||(e.o[t]=r,e.D[t]=!0,!0)},deleteProperty:function(e,t){return dzc(e.t,t)!==void 0||t in e.t?(e.D[t]=!1,pzc(e),yzc(e)):delete e.D[t],e.o&&delete e.o[t],!0},getOwnPropertyDescriptor:function(e,t){var r=$Sn(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.i!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty:function(){ZJ(11)},getPrototypeOf:function(e){return Object.getPrototypeOf(e.t)},setPrototypeOf:function(){ZJ(12)}},VWi={};WWi(bzc,function(e,t){VWi[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),VWi.deleteProperty=function(e,t){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(t))&&ZJ(13),VWi.set.call(this,e,t,void 0)},VWi.set=function(e,t,r){return process.env.NODE_ENV!=="production"&&t!=="length"&&isNaN(parseInt(t))&&ZJ(14),bzc.set.call(this,e[0],t,r,e[0])};var n46=function(){function e(r){var n=this;this.g=MUg,this.F=!0,this.produce=function(i,a,u){if(typeof i=="function"&&typeof a!="function"){var f=a;a=i;var d=n;return function(j){var M=this;j===void 0&&(j=f);for(var q=arguments.length,B=Array(q>1?q-1:0),I=1;I<q;I++)B[I-1]=arguments[I];return d.produce(j,function(C){var F;return(F=a).call.apply(F,[M,C].concat(B))})}}var c;if(typeof a!="function"&&ZJ(6),u!==void 0&&typeof u!="function"&&ZJ(7),KSn(i)){var o=jUg(n),l=vzc(n,i,void 0),g=!0;try{c=a(l),g=!1}finally{g?c9o(o):hzc(o)}return typeof Promise<"u"&&c instanceof Promise?c.then(function(j){return lzc(o,u),fzc(j,o)},function(j){throw c9o(o),j}):(lzc(o,u),fzc(c,o))}if(!i||typeof i!="object"){if((c=a(i))===void 0&&(c=i),c===CUg&&(c=void 0),n.F&&Pzc(c,!0),u){var O=[],P=[];Wjr("Patches").M(i,c,O,P),u(O,P)}return c}ZJ(21,i)},this.produceWithPatches=function(i,a){if(typeof i=="function")return function(c){for(var o=arguments.length,l=Array(o>1?o-1:0),g=1;g<o;g++)l[g-1]=arguments[g];return n.produceWithPatches(c,function(O){return i.apply(void 0,[O].concat(l))})};var u,f,d=n.produce(i,a,function(c,o){u=c,f=o});return typeof Promise<"u"&&d instanceof Promise?d.then(function(c){return[c,u,f]}):[d,u,f]},typeof r?.useProxies=="boolean"&&this.setUseProxies(r.useProxies),typeof r?.autoFreeze=="boolean"&&this.setAutoFreeze(r.autoFreeze)}var t=e.prototype;return t.createDraft=function(r){KSn(r)||ZJ(8),pai(r)&&(r=YB6(r));var n=jUg(this),i=vzc(this,r,void 0);return i[kAe].C=!0,hzc(n),i},t.finishDraft=function(r,n){var i=r&&r[kAe];process.env.NODE_ENV!=="production"&&(i&&i.C||ZJ(9),i.I&&ZJ(10));var a=i.A;return lzc(a,n),fzc(void 0,a)},t.setAutoFreeze=function(r){this.F=r},t.setUseProxies=function(r){r&&!MUg&&ZJ(20),this.g=r},t.applyPatches=function(r,n){var i;for(i=n.length-1;i>=0;i--){var a=n[i];if(a.path.length===0&&a.op==="replace"){r=a.value;break}}i>-1&&(n=n.slice(i+1));var u=Wjr("Patches").$;return pai(r)?u(r,n):this.produce(r,function(f){return u(f,n)})},e}(),eMe=new n46,i46=eMe.produce,Lj5=eMe.produceWithPatches.bind(eMe),Uj5=eMe.setAutoFreeze.bind(eMe),Vj5=eMe.setUseProxies.bind(eMe),Wj5=eMe.applyPatches.bind(eMe),Hj5=eMe.createDraft.bind(eMe),Qj5=eMe.finishDraft.bind(eMe),qUg=i46;async function IUg({cliEnvironment:e,version:t}){try{return await Rbi(e.packageName,{version:t}),!0}catch{return!1}}var HWi="FERN_CWD";async function QWi({version:e,cliContext:t,env:r}){t.suppressUpgradeMessage();let n=["--quiet","--yes",`${t.environment.packageName}@${e}`,...process.argv.slice(2)];t.logger.debug([`Re-running CLI at version ${e}.`,`${nl.dim(`+ npx ${n.map(f=>`"${f}"`).join(" ")}`)}`].join(`
2322
- `));let{failed:i,stdout:a,stderr:u}=await PDe(t.logger,"npx",["--quiet",...n],{stdio:"inherit",reject:!1,env:{...r,[HWi]:process.env[HWi]??process.cwd()}});if(a?.includes("code EEXIST")||u?.includes("code EEXIST"))return await QWi({version:e,cliContext:t});i&&t.failWithoutThrowing()}var BUg="FERN_PRE_UPGRADE_VERSION";async function zUg({cliContext:e,includePreReleases:t,targetVersion:r}){r!=null&&(await IUg({cliEnvironment:e.environment,version:r})||e.failAndThrow(`Failed to upgrade to ${r} because it does not exist. See https://www.npmjs.com/package/${e.environment.packageName}?activeTab=versions.`),iae(r,e.environment.packageVersion)||e.failAndThrow(`Cannot upgrade because target version (${r}) is behind existing version ${e.environment.packageVersion}`));let n=r!=null?{latestVersion:r,isUpgradeAvailable:!0}:(await e.isUpgradeAvailable({includePreReleases:t})).cliUpgradeInfo;if(n&&!n.isUpgradeAvailable){let i=process.env[BUg];if(i==null){e.logger.info("No upgrade available.");return}await e.runTask(async a=>{await czc({fromVersion:i,toVersion:n.latestVersion,context:a})}),await e.exitIfFailed()}else if(n!=null){let i=await VNr();if(i==null)return e.failAndThrow(`Directory "${e6t}" not found.`);let a=await e.runTask(f=>p8t.loadProjectConfig({directory:i,context:f})),u=qUg(a.rawConfig,f=>{f.version=n.latestVersion});await(0,NUg.writeFile)(a._absolutePath,JSON.stringify(u,void 0,2)),e.logger.info(`Upgrading from ${nl.dim(e.environment.packageVersion)} \u2192 ${nl.green(n.latestVersion)}`),await PDe(e.logger,"npm",["install","-g",`${e.environment.packageName}@${n.latestVersion}`]),await QWi({version:n.latestVersion,cliContext:e,env:{[BUg]:e.environment.packageVersion}})}}async function RUg({project:e,cliContext:t,logWarnings:r}){let n=e.docsWorkspaces;n!=null&&await t.runTaskForWorkspace(n,async i=>{await sBa({workspace:n,context:i,logWarnings:r,loadAPIWorkspace:e.loadAPIWorkspace})}),await Promise.all(e.apiWorkspaces.map(async i=>{await t.runTaskForWorkspace(i,async a=>{let u=await i.toFernWorkspace({context:a});await ILt({workspace:u,context:a,logWarnings:r})})}))}var Hjr=require("fs/promises");var Szc=Yo(require("path"),1);async function FUg({project:e,cliContext:t,sdkLanguage:r}){await Promise.all(e.apiWorkspaces.map(async n=>{await t.runTaskForWorkspace(n,async i=>{n instanceof DIt?await a46({workspace:n,context:i}):await o46({workspace:await n.toFernWorkspace({context:i}),context:i})})}))}async function a46({workspace:e,context:t}){for(let[r,n]of Object.entries(e.definition.importedDefinitions)){let i=yf(e.absoluteFilePath,Ms.of(QL),Ms.of(r),Ms.of(`.${QL}`));await LUg({definition:n.definition,absolutePathToOutputDirectory:i}),t.logger.info(nl.green(`Wrote imported definition at ${Szc.default.relative(process.cwd(),i)}`))}}async function o46({workspace:e,context:t}){let r=yf(e.absoluteFilePath,Ms.of(`.${QL}`));await LUg({definition:e.definition,absolutePathToOutputDirectory:r}),t.logger.info(nl.green(`Wrote definition to ${Szc.default.relative(process.cwd(),r)}`))}async function LUg({definition:e,absolutePathToOutputDirectory:t}){let r=(n,i)=>{let a={imports:0,types:1,services:2},u=n in a?a[n]:Object.keys(a).length,f=i in a?a[i]:Object.keys(a).length;return u==null?-1:f==null?1:u!==f?u-f:n.localeCompare(i)};await Wh(t)&&await(0,Hjr.rmdir)(t,{recursive:!0}),await(0,Hjr.mkdir)(t,{recursive:!0}),await(0,Hjr.writeFile)(yf(t,Ms.of(w5)),d0.dump(e.rootApiFile.contents,{sortKeys:r}));for(let[n,i]of Object.entries(e.packageMarkers)){let a=yf(t,Ms.of(n));await(0,Hjr.mkdir)(cb(a),{recursive:!0}),await(0,Hjr.writeFile)(a,d0.dump(i.contents,{sortKeys:r}))}for(let[n,i]of Object.entries(e.namedDefinitionFiles)){let a=yf(t,Ms.of(n));await(0,Hjr.mkdir)(cb(a),{recursive:!0}),await(0,Hjr.writeFile)(a,d0.dump(i.contents,{sortKeys:r}))}}function UUg(e){try{return new URL(e),!0}catch{return!1}}var d9o=class{context;ir;buildingTypeIds=new Set;definitions={};constructor(t,r){this.context=t,this.ir=r}getTypeDeclarationForId({typeName:t,typeId:r}){let n=this.ir.types[r];return n??(t!=null&&this.context.logger.error(`Type ${t} not found`),this.context.failAndThrow())}isOptional(t){if(t.type==="container"&&t.container.type==="optional")return!0;if(t.type==="named"){let r=this.getTypeDeclarationForId({typeId:t.typeId});if(r.shape.type==="alias")return this.isOptional(r.shape.aliasOf)}return!1}registerDefinition(t,r){let n=this.getTypeDeclarationForId({typeId:t});this.definitions[this.getDefinitionKey(n)]=r}getDefinitions(){return this.definitions}hasDefinition(t){let r=this.getTypeDeclarationForId({typeId:t});return this.getDefinitionKey(r)in this.definitions}getDefinitionKey(t){return[...t.name.fernFilepath.allParts.map(r=>r.originalName),t.name.name.originalName].join(".")}buildingTypeDeclaration(t){this.buildingTypeIds.add(t)}finishedBuildingTypeDeclaration(t){this.buildingTypeIds.delete(t)}isBuildingTypeDeclaration(t){return this.buildingTypeIds.has(t)}};function VUg({container:e,context:t}){switch(e.type){case"list":return{type:"array",items:tMe({typeReference:e.list,context:t})};case"map":return{type:"object",additionalProperties:tMe({typeReference:e.valueType,context:t})};case"optional":return{oneOf:[tMe({typeReference:e.optional,context:t}),{type:"null"}]};case"set":return{type:"array",items:tMe({typeReference:e.set,context:t}),uniqueItems:!0};case"literal":switch(e.literal.type){case"string":return{const:e.literal.string};case"boolean":return{const:e.literal.boolean};default:Lc(e.literal)}default:Lc(e)}}function tMe({typeReference:e,context:t}){switch(e.type){case"named":{let r=t.getTypeDeclarationForId({typeId:e.typeId});if(!t.hasDefinition(e.typeId)&&!t.isBuildingTypeDeclaration(e.typeId)){t.buildingTypeDeclaration(e.typeId);let n=yai({typeDeclaration:r,context:t});t.registerDefinition(e.typeId,n),t.finishedBuildingTypeDeclaration(e.typeId)}return{$ref:`#/definitions/${t.getDefinitionKey(r)}`}}case"container":return VUg({container:e.container,context:t});case"primitive":return u46(e.primitive.v1);case"unknown":return{type:["string","number","boolean","object","array","null"]};default:Lc(e)}}function u46(e){switch(e){case vP.String:return{type:"string"};case vP.Integer:return{type:"integer"};case vP.Long:return{type:"integer"};case vP.Uint:return{type:"integer",minimum:0};case vP.Uint64:return{type:"integer",minimum:0};case vP.Float:return{type:"number"};case vP.Double:return{type:"number"};case vP.Boolean:return{type:"boolean"};case vP.Date:return{type:"string",format:"date"};case vP.DateTime:return{type:"string",format:"date-time"};case vP.Uuid:return{type:"string",format:"uuid"};case vP.Base64:return{type:"string",contentEncoding:"base64"};case vP.BigInteger:return{type:"string",pattern:"^-?[0-9]+$"};default:Lc(e)}}function WUg({object:e,context:t}){let r={type:"object"},n=[...e.extendedProperties??[],...e.properties],i=n.map(u=>{let f=u.name.wireValue,d=tMe({typeReference:u.valueType,context:t});return[f,d]}),a=n.filter(u=>!t.isOptional(u.valueType)).map(u=>u.name.wireValue);return i.length>0&&(r.properties=Object.fromEntries(i)),a.length>0&&(r.required=a),r.additionalProperties=e.extraProperties,r}function HUg({enum:e,context:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue)}}function QUg({union:e,context:t}){let r=e.discriminant.wireValue;return{type:"object",properties:{[r]:{type:"string",enum:e.types.map(n=>n.discriminantValue.wireValue)}},required:[r],oneOf:e.types.map(n=>{let i={},a=[];switch(n.shape.propertiesType){case"samePropertiesAsObject":{let u=t.getTypeDeclarationForId({typeId:n.shape.typeId}),f=yai({typeDeclaration:u,context:t});i=f.properties??{},a=Array.isArray(f.required)?f.required:[];break}case"singleProperty":i.value=tMe({typeReference:n.shape.type,context:t});break;case"noProperties":break;default:Lc(n.shape)}return{properties:{[r]:{const:n.discriminantValue.wireValue},...i},required:[r,...a]}})}}function JUg({undiscriminatedUnion:e,context:t}){return{anyOf:e.members.map(r=>{let n=tMe({typeReference:r.type,context:t});return r.docs&&(n.description=r.docs),n})}}function yai({typeDeclaration:e,context:t}){switch(e.shape.type){case"object":return WUg({object:e.shape,context:t});case"alias":return tMe({typeReference:e.shape.aliasOf,context:t});case"enum":return HUg({enum:e.shape,context:t});case"union":return QUg({union:e.shape,context:t});case"undiscriminatedUnion":return JUg({undiscriminatedUnion:e.shape,context:t});default:Lc(e.shape)}}function Ezc(e){let t=new d9o(e.context,e.ir),r=t.getTypeDeclarationForId({typeId:e.typeId,typeName:e.typeName});return{...yai({typeDeclaration:r,context:t}),definitions:t.getDefinitions()}}var p9o=require("fs/promises");async function GUg({typeLocator:e,project:t,jsonschemaFilepath:r,cliContext:n}){await Promise.all(t.apiWorkspaces.map(async i=>{await n.runTaskForWorkspace(i,async a=>{let u=await i.toFernWorkspace({context:a}),f=await aQ({workspace:u,context:a,generationLanguage:void 0,audiences:{type:"all"},keywords:void 0,smartCasing:!1,disableExamples:!0,version:void 0,packageName:void 0,readme:void 0}),d=e.split("."),c=oLt({generationLanguage:void 0,keywords:void 0,smartCasing:!1}),o=d[d.length-1]??e,l=d.length>1?`${d.slice(0,-1).join("/")}.yml`:$A,g=s1.generateTypeId({fernFilepath:jae({relativeFilepath:Ms.of(`${d.slice(0,-1).join("/")}.yml`),casingsGenerator:c}),name:c.generateName(o)}),O=Ezc({ir:f,typeName:o,typeId:g,context:a});await Wh(cb(r))||await(0,p9o.mkdir)(cb(r),{recursive:!0}),await(0,p9o.writeFile)(r,JSON.stringify(O,null,2)),a.logger.info(nl.green(`Wrote JSON Schema to ${r}`))})}))}var KUg=Yo(require("path"),1);var $Ug="1.0.0";var _9o=class{ir;auth;constructor(t){this.ir=t,this.auth=this.convertAuth(t.auth)}convert(){return{version:$Ug,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints()}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints(){let t=this.getAllHttpEndpoints();return Object.fromEntries(t.map(r=>[r.id,this.convertEndpoint(r)]))}convertEndpoint(t){return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:this.convertEndpointLocation({endpoint:t}),request:this.convertRequest({endpoint:t}),response:op.Response.json()}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:t.allPathParameters});if(t.sdkRequest==null&&t.requestBody==null)return op.Request.body({pathParameters:r,body:void 0});if(t.sdkRequest==null)throw new Error(`Internal error; endpoint "${t.id}" has a request body but no SDK request`);switch(t.sdkRequest.shape.type){case"justRequestBody":return op.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertWireValueParameters({wireValueParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:t.headers}),body:t.requestBody});default:Lc(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return op.ReferencedRequestBodyType.bytes();case"typeReference":return op.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:Lc(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:n,queryParameters:i,headers:a,body:u}){return op.Request.inlined({declaration:this.convertDeclaration({name:r.wrapperName,fernFilepath:t}),pathParameters:n,queryParameters:i,headers:a,body:u!=null?this.convertInlinedRequestBody({wrapper:r,body:u}):void 0})}convertInlinedRequestBody({wrapper:t,body:r}){switch(r.type){case"inlinedRequestBody":{let n=[...r.extendedProperties??[],...r.properties];return op.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:n}))}case"reference":return op.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:op.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return op.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:op.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:Lc(r)}}convertFileUploadRequestBody({properties:t}){return op.InlinedRequestBody.fileUpload({properties:this.convertFileUploadRequestBodyProperties({properties:t})})}convertFileUploadRequestBodyProperties({properties:t}){return t.map(r=>{switch(r.type){case"file":return this.convertFileUploadRequestBodyFileProperty({fileProperty:r.value});case"bodyProperty":return op.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:Lc(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return op.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return op.FileUploadRequestBodyProperty.fileArray(t.key);default:Lc(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:Lc(t)}}convertContainerType(t){switch(t.type){case"list":return op.TypeReference.list(this.convertTypeReference(t.list));case"map":return op.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return op.TypeReference.optional(this.convertTypeReference(t.optional));case"set":return op.TypeReference.set(this.convertTypeReference(t.set));case"literal":return op.TypeReference.literal(this.convertLiteral(t.literal));default:Lc(t)}}convertNamedType(t){return op.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:Lc(t.shape)}}convertAlias({declaration:t,alias:r}){return op.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return op.NamedType.enum({declaration:t,values:r.values.map(n=>n.name)})}convertObject({declaration:t,object:r}){let n=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:n})}convertObjectProperties({declaration:t,properties:r}){return op.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r})})}convertDiscriminatedUnion({declaration:t,union:r}){let n=[...this.resolveProperties(r.extends),...r.baseProperties];return op.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(i=>[i.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:n,discriminantValue:i.discriminantValue,singleUnionTypeProperties:i.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:n}){switch(n.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:n});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:n});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:Lc(n)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:n}){let i=[...t,...this.resolveProperties([n])];return op.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:n.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:i})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:n}){return op.SingleDiscriminatedUnionType.singleProperty({typeReference:this.convertTypeReference(n.type),discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r}){return op.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return op.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(n=>this.convertTypeReference(n.type))})}convertLiteral(t){switch(t.type){case"boolean":return op.LiteralType.boolean(t.boolean);case"string":return op.LiteralType.string(t.string);default:Lc(t)}}convertPrimitiveType(t){return op.TypeReference.primitive(t.v1)}convertUnknownType(){return op.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return op.Auth.basic(r);case"bearer":return op.Auth.bearer(r);case"header":return op.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return;default:Lc(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let n of t){let i=this.resolveObjectTypeOrThrow(n.typeId);r.push(...this.resolveProperties(i.extends)),r.push(...i.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=k1(r,t.fullPath.head));for(let n of t.fullPath.parts)r=k1(r,"{"+n.pathParameter+"}"),n.tail.length>0&&(r=k1(r,n.tail));return r.startsWith("/")?r:`/${r}`}};async function Azc(e){return new _9o(e).convert()}async function YUg({project:e,irFilepath:t,cliContext:r,generationLanguage:n,audiences:i,version:a,keywords:u,smartCasing:f}){await Promise.all(e.apiWorkspaces.map(async d=>{await r.runTaskForWorkspace(d,async c=>{r.logger.info(`Generating IR for workspace ${d.workspaceName??"api"}`);let o=await d.toFernWorkspace({context:c}),l=await iRn({workspace:o,context:c,generationLanguage:n,keywords:u,smartCasing:f,disableExamples:!1,audiences:i,readme:void 0}),g=await Azc(l),O=KUg.default.resolve(t);await HSr(v_.of(O),g),c.logger.info(`Wrote IR to ${O}`)})}))}var XUg=require("fs/promises");async function ZUg({project:e,outputPath:t,cliContext:r}){let n=e.docsWorkspaces;n!=null&&await r.runTaskForWorkspace(n,async i=>{let a=await Promise.all(e.apiWorkspaces.map(async d=>d.toFernWorkspace({context:i},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),f=await new yMr(`https://${n.config.instances[0]?.url??"https://localhost:8080"}`,n,a,i).resolve();await(0,XUg.writeFile)(v_.of(t),JSON.stringify(f,null,2)),i.logger.info(nl.green(`Docs definition written to ${t}`))})}var cUo=Yo(f3u(),1);bW6();var vW6="The Fern CLI requires Node 18+ or above.";async function bW6(){let e=new bPa(process.stdout),t=async()=>{await e.exit()};if(cUo.RUNTIME.type==="node"&&cUo.RUNTIME.parsedVersion!=null&&cUo.RUNTIME.parsedVersion>=18){let{setGlobalDispatcher:r,Agent:n}=await Promise.resolve().then(()=>Yo(NKg(),1));r(new n({connect:{timeout:5e3}}))}process.on("SIGINT",async()=>{e.suppressUpgradeMessage(),await t()});try{let r=process.env[HWi];r!=null&&process.chdir(r);let n=await mW6(e);e.environment.packageVersion===n?await gW6(e):await QWi({version:n,cliContext:e})}catch(r){await e.instrumentPostHogEvent({command:process.argv.join(" "),properties:{failed:!0,error:r}}),r?.message.includes("globalThis")?(e.logger.error(vW6),e.failWithoutThrowing()):r instanceof rTe?e.failWithoutThrowing():r instanceof GSr?e.logger.error(`Failed. ${r.log}`):e.failWithoutThrowing("Failed.",r)}await t()}async function gW6(e){let t=wMf(pgu(process.argv)).scriptName(e.environment.cliName).version(!1).fail((r,n,i)=>{n==null&&(i.showHelp(),e.logger.error(r))}).strict().exitProcess(!1).command("$0",!1,r=>r.option("version",{describe:"Print current version",alias:"v"}).version(!1),r=>{r.version!=null?e.logger.info(e.environment.packageVersion):(t.showHelp(),e.failAndThrow())}).option("log-level",{default:KA.Info,choices:T3r}).demandCommand().recommendCommands();OW6(t,e),PW6(t,e),wW6(t,e),jW6(t,e),DW6(t,e),AW6(t,e),SW6(t,e),EW6(t,e),TW6(t,e),MW6(t,e),xW6(t,e),IW6(t,e),BW6(t,e),FW6(t,e),LW6(t,e),zW6(t,e),RW6(t,e),NW6(t,e),qW6(t,e),CW6({cli:t,cliContext:e,onRun:()=>{e.suppressUpgradeMessage()}}),UW6(t,e),VW6(t,e),n$f(t,e),i$f(t,e),t.middleware(async r=>{e.setLogLevel(r["log-level"]),e.logDebugInfo()}),await t.parse()}async function mW6(e){if(process.env.FERN_NO_VERSION_REDIRECTION==="true")return e.environment.packageVersion;let t=await VNr();if(t!=null){let r=await e.runTask(n=>p8t.loadProjectConfig({directory:t,context:n}));return r.version==="*"?e.environment.packageVersion:r.version}return Q3n({cliEnvironment:e.environment})}function OW6(e,t){e.command("init","Initialize a Fern API",r=>r.option("api",{boolean:!0,description:"Initialize an api."}).option("docs",{boolean:!0,description:"Initialize a docs website."}).option("organization",{alias:"org",type:"string",description:"Organization name"}).option("openapi",{type:"string",description:"Filepath or url to an existing OpenAPI spec"}),async r=>{if(r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.");if(r.docs!=null)await t.runTask(async n=>{await dgu({organization:r.organization,versionOfCli:await Q3n({cliEnvironment:t.environment}),taskContext:n})});else{let n;if(r.openapi!=null){if(UUg(r.openapi)){let a=await EMf({url:r.openapi,logger:t.logger});a.status==="failure"&&t.failAndThrow(a.errorMessage);let u=a.filePath;n=v_.of(u)}else n=v_.of(rT(t6t(),r.openapi));await Wh(n)||t.failAndThrow(`${n} does not exist`)}await t.runTask(async i=>{await fgu({organization:r.organization,versionOfCli:await Q3n({cliEnvironment:t.environment}),context:i,openApiPath:n})})}})}function PW6(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async n=>{await f5g({orgId:r.organization??(await Tq(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:n})})})}function wW6(e,t){e.command("add <generator>",`Add a code generator to ${mz}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{await o$f({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:r.generator,groupName:r.group,cliContext:t})})}function jW6(e,t){e.command(["generate"],"Generate all generators in the specified group",r=>r.option("api",{string:!0,description:"If multiple APIs, specify the name with --api <name>. Otherwise, just --api."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("group",{type:"string",description:"The group to generate"}).option("mode",{choices:Object.values($8g),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally, using Docker"}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}),async r=>r.api!=null&&r.docs!=null?t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one."):r.local&&r.preview?t.failWithoutThrowing("The --local flag is incompatible with --preview."):r.api!=null?await cNc({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode}):r.docs!=null?(r.group!=null&&t.logger.warn("--group is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await K8g({project:await Tq(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview})):await cNc({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode}))}function DW6(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(nP.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the IR for certain audiences"}),async r=>{await _Tg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:rT(t6t(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:!1,readme:void 0})})}function SW6(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(nP.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await vTg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:rT(t6t(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function EW6(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(nP.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the IR for certain audiences"}),async r=>{await YUg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:rT(t6t(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:!1})})}function AW6(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the FDR API definition for certain audiences"}),async r=>{await Ljd({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:rT(t6t(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function MW6(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let n=await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),i=await t.runTask(a=>kCe(a));await u5g({project:n,cliContext:t,token:i,version:r.version})})}function xW6(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let n=await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),i=await t.runTask(a=>kCe(a));await s5g({project:n,cliContext:t,token:i})})}function TW6(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}),async r=>{await RUg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,logWarnings:r.warnings})})}function CW6({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades version in ${Xzt}. Also upgrades generators in ${mz} to their minimum-compatible versions.`,n=>n.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}),async n=>{await zUg({cliContext:t,includePreReleases:n.rc,targetVersion:n.version}),r()})}function qW6(e,t){e.command("api update",`Pulls the latest OpenAPI spec from the specified origin in ${mz} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}),async r=>{await t.instrumentPostHogEvent({command:"fern api update"}),await h5g({cliContext:t,project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0})})})}function IW6(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}),async r=>{await t.runTask(async n=>{await t.instrumentPostHogEvent({command:"fern login"}),await Hvi(n,{useDeviceCodeFlow:r.deviceCode})})})}function BW6(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern format"}),await zjd({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function NW6(e,t){e.command("test","Runs tests specified in --command, this spins up a mock server in the background that is terminated upon completion of the tests.",r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(nP.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{await t.instrumentPostHogEvent({command:"fern test"}),await c5g({cliContext:t,project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function zW6(e,t){e.command("mock","Starts a mock server for an API.",r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{await t.instrumentPostHogEvent({command:"fern mock"}),await t5g({cliContext:t,project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function RW6(e,t){e.command("write-overrides","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{await t.instrumentPostHogEvent({command:"fern generate-overrides"}),await gTg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function FW6(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(nP.GenerationLanguage),description:"Write the definition for a particular SDK language"}),async r=>{await t.instrumentPostHogEvent({command:"fern write-definition"}),await FUg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language}),cliContext:t,sdkLanguage:r.language})})}function LW6(e,t){e.command("docs dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}),async r=>{let n;r.port!=null?n=r.port:n=await nbi({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]});let i=r.bundlePath;await Njd({loadProject:()=>Tq(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:n,bundlePath:i})})}function UW6(e,t){e.command("jsonschema <path-to-output>","Generate JSON Schema for a specific type",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).positional("path-to-output",{type:"string",description:"Path to write JSON Schema",demandOption:!0}).option("type",{string:!0,demandOption:!0,description:"The type to generate JSON Schema for (e.g. 'MySchema' or 'mypackage.MySchema')"}),async r=>{await t.instrumentPostHogEvent({command:"fern jsonschema",properties:{output:r.output}}),await GUg({typeLocator:r.type,project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),jsonschemaFilepath:rT(t6t(),r.pathToOutput),cliContext:t})})}function VW6(e,t){e.command("write-docs-definition <output-path>",!1,r=>r.positional("output-path",{type:"string",description:"Path to write the docs definition",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern write-docs-definition",properties:{outputPath:r.outputPath}}),await ZUg({project:await Tq(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),outputPath:rT(t6t(),r.outputPath),cliContext:t})})}
2322
+ `));let{failed:i,stdout:a,stderr:u}=await PDe(t.logger,"npx",["--quiet",...n],{stdio:"inherit",reject:!1,env:{...r,[HWi]:process.env[HWi]??process.cwd()}});if(a?.includes("code EEXIST")||u?.includes("code EEXIST"))return await QWi({version:e,cliContext:t});i&&t.failWithoutThrowing()}var BUg="FERN_PRE_UPGRADE_VERSION";async function zUg({cliContext:e,includePreReleases:t,targetVersion:r}){r!=null&&(await IUg({cliEnvironment:e.environment,version:r})||e.failAndThrow(`Failed to upgrade to ${r} because it does not exist. See https://www.npmjs.com/package/${e.environment.packageName}?activeTab=versions.`),iae(r,e.environment.packageVersion)||e.failAndThrow(`Cannot upgrade because target version (${r}) is behind existing version ${e.environment.packageVersion}`));let n=r!=null?{latestVersion:r,isUpgradeAvailable:!0}:(await e.isUpgradeAvailable({includePreReleases:t})).cliUpgradeInfo;if(n&&!n.isUpgradeAvailable){let i=process.env[BUg];if(i==null){e.logger.info("No upgrade available.");return}await e.runTask(async a=>{await czc({fromVersion:i,toVersion:n.latestVersion,context:a})}),await e.exitIfFailed()}else if(n!=null){let i=await VNr();if(i==null)return e.failAndThrow(`Directory "${e6t}" not found.`);let a=await e.runTask(f=>p8t.loadProjectConfig({directory:i,context:f})),u=qUg(a.rawConfig,f=>{f.version=n.latestVersion});await(0,NUg.writeFile)(a._absolutePath,JSON.stringify(u,void 0,2)),e.logger.info(`Upgrading from ${nl.dim(e.environment.packageVersion)} \u2192 ${nl.green(n.latestVersion)}`),await PDe(e.logger,"npm",["install","-g",`${e.environment.packageName}@${n.latestVersion}`]),await QWi({version:n.latestVersion,cliContext:e,env:{[BUg]:e.environment.packageVersion}})}}async function RUg({project:e,cliContext:t,logWarnings:r}){let n=e.docsWorkspaces;n!=null&&await t.runTaskForWorkspace(n,async i=>{await sBa({workspace:n,context:i,logWarnings:r,loadAPIWorkspace:e.loadAPIWorkspace})}),await Promise.all(e.apiWorkspaces.map(async i=>{await t.runTaskForWorkspace(i,async a=>{let u=await i.toFernWorkspace({context:a});await ILt({workspace:u,context:a,logWarnings:r})})}))}var Hjr=require("fs/promises");var Szc=Yo(require("path"),1);async function FUg({project:e,cliContext:t,sdkLanguage:r}){await Promise.all(e.apiWorkspaces.map(async n=>{await t.runTaskForWorkspace(n,async i=>{n instanceof DIt?await a46({workspace:n,context:i}):await o46({workspace:await n.toFernWorkspace({context:i}),context:i})})}))}async function a46({workspace:e,context:t}){for(let[r,n]of Object.entries(e.definition.importedDefinitions)){let i=yf(e.absoluteFilePath,Ms.of(QL),Ms.of(r),Ms.of(`.${QL}`));await LUg({definition:n.definition,absolutePathToOutputDirectory:i}),t.logger.info(nl.green(`Wrote imported definition at ${Szc.default.relative(process.cwd(),i)}`))}}async function o46({workspace:e,context:t}){let r=yf(e.absoluteFilePath,Ms.of(`.${QL}`));await LUg({definition:e.definition,absolutePathToOutputDirectory:r}),t.logger.info(nl.green(`Wrote definition to ${Szc.default.relative(process.cwd(),r)}`))}async function LUg({definition:e,absolutePathToOutputDirectory:t}){let r=(n,i)=>{let a={imports:0,types:1,services:2},u=n in a?a[n]:Object.keys(a).length,f=i in a?a[i]:Object.keys(a).length;return u==null?-1:f==null?1:u!==f?u-f:n.localeCompare(i)};await Wh(t)&&await(0,Hjr.rmdir)(t,{recursive:!0}),await(0,Hjr.mkdir)(t,{recursive:!0}),await(0,Hjr.writeFile)(yf(t,Ms.of(w5)),d0.dump(e.rootApiFile.contents,{sortKeys:r}));for(let[n,i]of Object.entries(e.packageMarkers)){let a=yf(t,Ms.of(n));await(0,Hjr.mkdir)(cb(a),{recursive:!0}),await(0,Hjr.writeFile)(a,d0.dump(i.contents,{sortKeys:r}))}for(let[n,i]of Object.entries(e.namedDefinitionFiles)){let a=yf(t,Ms.of(n));await(0,Hjr.mkdir)(cb(a),{recursive:!0}),await(0,Hjr.writeFile)(a,d0.dump(i.contents,{sortKeys:r}))}}function UUg(e){try{return new URL(e),!0}catch{return!1}}var d9o=class{context;ir;buildingTypeIds=new Set;definitions={};constructor(t,r){this.context=t,this.ir=r}getTypeDeclarationForId({typeName:t,typeId:r}){let n=this.ir.types[r];return n??(t!=null&&this.context.logger.error(`Type ${t} not found`),this.context.failAndThrow())}isOptional(t){if(t.type==="container"&&t.container.type==="optional")return!0;if(t.type==="named"){let r=this.getTypeDeclarationForId({typeId:t.typeId});if(r.shape.type==="alias")return this.isOptional(r.shape.aliasOf)}return!1}registerDefinition(t,r){let n=this.getTypeDeclarationForId({typeId:t});this.definitions[this.getDefinitionKey(n)]=r}getDefinitions(){return this.definitions}hasDefinition(t){let r=this.getTypeDeclarationForId({typeId:t});return this.getDefinitionKey(r)in this.definitions}getDefinitionKey(t){return[...t.name.fernFilepath.allParts.map(r=>r.originalName),t.name.name.originalName].join(".")}buildingTypeDeclaration(t){this.buildingTypeIds.add(t)}finishedBuildingTypeDeclaration(t){this.buildingTypeIds.delete(t)}isBuildingTypeDeclaration(t){return this.buildingTypeIds.has(t)}};function VUg({container:e,context:t}){switch(e.type){case"list":return{type:"array",items:tMe({typeReference:e.list,context:t})};case"map":return{type:"object",additionalProperties:tMe({typeReference:e.valueType,context:t})};case"optional":return{oneOf:[tMe({typeReference:e.optional,context:t}),{type:"null"}]};case"set":return{type:"array",items:tMe({typeReference:e.set,context:t}),uniqueItems:!0};case"literal":switch(e.literal.type){case"string":return{const:e.literal.string};case"boolean":return{const:e.literal.boolean};default:Lc(e.literal)}default:Lc(e)}}function tMe({typeReference:e,context:t}){switch(e.type){case"named":{let r=t.getTypeDeclarationForId({typeId:e.typeId});if(!t.hasDefinition(e.typeId)&&!t.isBuildingTypeDeclaration(e.typeId)){t.buildingTypeDeclaration(e.typeId);let n=yai({typeDeclaration:r,context:t});t.registerDefinition(e.typeId,n),t.finishedBuildingTypeDeclaration(e.typeId)}return{$ref:`#/definitions/${t.getDefinitionKey(r)}`}}case"container":return VUg({container:e.container,context:t});case"primitive":return u46(e.primitive.v1);case"unknown":return{type:["string","number","boolean","object","array","null"]};default:Lc(e)}}function u46(e){switch(e){case vP.String:return{type:"string"};case vP.Integer:return{type:"integer"};case vP.Long:return{type:"integer"};case vP.Uint:return{type:"integer",minimum:0};case vP.Uint64:return{type:"integer",minimum:0};case vP.Float:return{type:"number"};case vP.Double:return{type:"number"};case vP.Boolean:return{type:"boolean"};case vP.Date:return{type:"string",format:"date"};case vP.DateTime:return{type:"string",format:"date-time"};case vP.Uuid:return{type:"string",format:"uuid"};case vP.Base64:return{type:"string",contentEncoding:"base64"};case vP.BigInteger:return{type:"string",pattern:"^-?[0-9]+$"};default:Lc(e)}}function WUg({object:e,context:t}){let r={type:"object"},n=[...e.extendedProperties??[],...e.properties],i=n.map(u=>{let f=u.name.wireValue,d=tMe({typeReference:u.valueType,context:t});return[f,d]}),a=n.filter(u=>!t.isOptional(u.valueType)).map(u=>u.name.wireValue);return i.length>0&&(r.properties=Object.fromEntries(i)),a.length>0&&(r.required=a),r.additionalProperties=e.extraProperties,r}function HUg({enum:e,context:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue)}}function QUg({union:e,context:t}){let r=e.discriminant.wireValue;return{type:"object",properties:{[r]:{type:"string",enum:e.types.map(n=>n.discriminantValue.wireValue)}},required:[r],oneOf:e.types.map(n=>{let i={},a=[];switch(n.shape.propertiesType){case"samePropertiesAsObject":{let u=t.getTypeDeclarationForId({typeId:n.shape.typeId}),f=yai({typeDeclaration:u,context:t});i=f.properties??{},a=Array.isArray(f.required)?f.required:[];break}case"singleProperty":i.value=tMe({typeReference:n.shape.type,context:t});break;case"noProperties":break;default:Lc(n.shape)}return{properties:{[r]:{const:n.discriminantValue.wireValue},...i},required:[r,...a]}})}}function JUg({undiscriminatedUnion:e,context:t}){return{anyOf:e.members.map(r=>{let n=tMe({typeReference:r.type,context:t});return r.docs&&(n.description=r.docs),n})}}function yai({typeDeclaration:e,context:t}){switch(e.shape.type){case"object":return WUg({object:e.shape,context:t});case"alias":return tMe({typeReference:e.shape.aliasOf,context:t});case"enum":return HUg({enum:e.shape,context:t});case"union":return QUg({union:e.shape,context:t});case"undiscriminatedUnion":return JUg({undiscriminatedUnion:e.shape,context:t});default:Lc(e.shape)}}function Ezc(e){let t=new d9o(e.context,e.ir),r=t.getTypeDeclarationForId({typeId:e.typeId,typeName:e.typeName});return{...yai({typeDeclaration:r,context:t}),definitions:t.getDefinitions()}}var p9o=require("fs/promises");async function GUg({typeLocator:e,project:t,jsonschemaFilepath:r,cliContext:n}){await Promise.all(t.apiWorkspaces.map(async i=>{await n.runTaskForWorkspace(i,async a=>{let u=await i.toFernWorkspace({context:a}),f=await aQ({workspace:u,context:a,generationLanguage:void 0,audiences:{type:"all"},keywords:void 0,smartCasing:!1,disableExamples:!0,version:void 0,packageName:void 0,readme:void 0}),d=e.split("."),c=oLt({generationLanguage:void 0,keywords:void 0,smartCasing:!1}),o=d[d.length-1]??e,l=d.length>1?`${d.slice(0,-1).join("/")}.yml`:$A,g=s1.generateTypeId({fernFilepath:jae({relativeFilepath:Ms.of(`${d.slice(0,-1).join("/")}.yml`),casingsGenerator:c}),name:c.generateName(o)}),O=Ezc({ir:f,typeName:o,typeId:g,context:a});await Wh(cb(r))||await(0,p9o.mkdir)(cb(r),{recursive:!0}),await(0,p9o.writeFile)(r,JSON.stringify(O,null,2)),a.logger.info(nl.green(`Wrote JSON Schema to ${r}`))})}))}var KUg=Yo(require("path"),1);var $Ug="1.0.0";var _9o=class{ir;auth;constructor(t){this.ir=t,this.auth=this.convertAuth(t.auth)}convert(){return{version:$Ug,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints()}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints(){let t=this.getAllHttpEndpoints();return Object.fromEntries(t.map(r=>[r.id,this.convertEndpoint(r)]))}convertEndpoint(t){return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:this.convertEndpointLocation({endpoint:t}),request:this.convertRequest({endpoint:t}),response:op.Response.json()}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:t.allPathParameters});if(t.sdkRequest==null&&t.requestBody==null)return op.Request.body({pathParameters:r,body:void 0});if(t.sdkRequest==null)throw new Error(`Internal error; endpoint "${t.id}" has a request body but no SDK request`);switch(t.sdkRequest.shape.type){case"justRequestBody":return op.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertWireValueParameters({wireValueParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:t.headers}),body:t.requestBody});default:Lc(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return op.ReferencedRequestBodyType.bytes();case"typeReference":return op.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:Lc(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:n,queryParameters:i,headers:a,body:u}){return op.Request.inlined({declaration:this.convertDeclaration({name:r.wrapperName,fernFilepath:t}),pathParameters:n,queryParameters:i,headers:a,body:u!=null?this.convertInlinedRequestBody({wrapper:r,body:u}):void 0})}convertInlinedRequestBody({wrapper:t,body:r}){switch(r.type){case"inlinedRequestBody":{let n=[...r.extendedProperties??[],...r.properties];return op.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:n}))}case"reference":return op.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:op.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return op.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:op.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:Lc(r)}}convertFileUploadRequestBody({properties:t}){return op.InlinedRequestBody.fileUpload({properties:this.convertFileUploadRequestBodyProperties({properties:t})})}convertFileUploadRequestBodyProperties({properties:t}){return t.map(r=>{switch(r.type){case"file":return this.convertFileUploadRequestBodyFileProperty({fileProperty:r.value});case"bodyProperty":return op.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:Lc(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return op.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return op.FileUploadRequestBodyProperty.fileArray(t.key);default:Lc(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:Lc(t)}}convertContainerType(t){switch(t.type){case"list":return op.TypeReference.list(this.convertTypeReference(t.list));case"map":return op.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return op.TypeReference.optional(this.convertTypeReference(t.optional));case"set":return op.TypeReference.set(this.convertTypeReference(t.set));case"literal":return op.TypeReference.literal(this.convertLiteral(t.literal));default:Lc(t)}}convertNamedType(t){return op.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:Lc(t.shape)}}convertAlias({declaration:t,alias:r}){return op.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return op.NamedType.enum({declaration:t,values:r.values.map(n=>n.name)})}convertObject({declaration:t,object:r}){let n=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:n})}convertObjectProperties({declaration:t,properties:r}){return op.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r})})}convertDiscriminatedUnion({declaration:t,union:r}){let n=[...this.resolveProperties(r.extends),...r.baseProperties];return op.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(i=>[i.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:n,discriminantValue:i.discriminantValue,singleUnionTypeProperties:i.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:n}){switch(n.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:n});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:n});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:Lc(n)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:n}){let i=[...t,...this.resolveProperties([n])];return op.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:n.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:i})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:n}){return op.SingleDiscriminatedUnionType.singleProperty({typeReference:this.convertTypeReference(n.type),discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r}){return op.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return op.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(n=>this.convertTypeReference(n.type))})}convertLiteral(t){switch(t.type){case"boolean":return op.LiteralType.boolean(t.boolean);case"string":return op.LiteralType.string(t.string);default:Lc(t)}}convertPrimitiveType(t){return op.TypeReference.primitive(t.v1)}convertUnknownType(){return op.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return op.Auth.basic(r);case"bearer":return op.Auth.bearer(r);case"header":return op.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return;default:Lc(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let n of t){let i=this.resolveObjectTypeOrThrow(n.typeId);r.push(...this.resolveProperties(i.extends)),r.push(...i.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=k1(r,t.fullPath.head));for(let n of t.fullPath.parts)r=k1(r,"{"+n.pathParameter+"}"),n.tail.length>0&&(r=k1(r,n.tail));return r.startsWith("/")?r:`/${r}`}};async function Azc(e){return new _9o(e).convert()}async function YUg({project:e,irFilepath:t,cliContext:r,generationLanguage:n,audiences:i,version:a,keywords:u,smartCasing:f}){await Promise.all(e.apiWorkspaces.map(async d=>{await r.runTaskForWorkspace(d,async c=>{r.logger.info(`Generating IR for workspace ${d.workspaceName??"api"}`);let o=await d.toFernWorkspace({context:c}),l=await iRn({workspace:o,context:c,generationLanguage:n,keywords:u,smartCasing:f,disableExamples:!1,audiences:i,readme:void 0}),g=await Azc(l),O=KUg.default.resolve(t);await HSr(v_.of(O),g),c.logger.info(`Wrote IR to ${O}`)})}))}var XUg=require("fs/promises");async function ZUg({project:e,outputPath:t,cliContext:r}){let n=e.docsWorkspaces;n!=null&&await r.runTaskForWorkspace(n,async i=>{let a=await Promise.all(e.apiWorkspaces.map(async d=>d.toFernWorkspace({context:i},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),f=await new yMr(n.config.instances[0]?.url??"http://localhost:8080",n,a,i).resolve();await(0,XUg.writeFile)(v_.of(t),JSON.stringify(f,null,2)),i.logger.info(nl.green(`Docs definition written to ${t}`))})}var cUo=Yo(f3u(),1);bW6();var vW6="The Fern CLI requires Node 18+ or above.";async function bW6(){let e=new bPa(process.stdout),t=async()=>{await e.exit()};if(cUo.RUNTIME.type==="node"&&cUo.RUNTIME.parsedVersion!=null&&cUo.RUNTIME.parsedVersion>=18){let{setGlobalDispatcher:r,Agent:n}=await Promise.resolve().then(()=>Yo(NKg(),1));r(new n({connect:{timeout:5e3}}))}process.on("SIGINT",async()=>{e.suppressUpgradeMessage(),await t()});try{let r=process.env[HWi];r!=null&&process.chdir(r);let n=await mW6(e);e.environment.packageVersion===n?await gW6(e):await QWi({version:n,cliContext:e})}catch(r){await e.instrumentPostHogEvent({command:process.argv.join(" "),properties:{failed:!0,error:r}}),r?.message.includes("globalThis")?(e.logger.error(vW6),e.failWithoutThrowing()):r instanceof rTe?e.failWithoutThrowing():r instanceof GSr?e.logger.error(`Failed. ${r.log}`):e.failWithoutThrowing("Failed.",r)}await t()}async function gW6(e){let t=wMf(pgu(process.argv)).scriptName(e.environment.cliName).version(!1).fail((r,n,i)=>{n==null&&(i.showHelp(),e.logger.error(r))}).strict().exitProcess(!1).command("$0",!1,r=>r.option("version",{describe:"Print current version",alias:"v"}).version(!1),r=>{r.version!=null?e.logger.info(e.environment.packageVersion):(t.showHelp(),e.failAndThrow())}).option("log-level",{default:KA.Info,choices:T3r}).demandCommand().recommendCommands();OW6(t,e),PW6(t,e),wW6(t,e),jW6(t,e),DW6(t,e),AW6(t,e),SW6(t,e),EW6(t,e),TW6(t,e),MW6(t,e),xW6(t,e),IW6(t,e),BW6(t,e),FW6(t,e),LW6(t,e),zW6(t,e),RW6(t,e),NW6(t,e),qW6(t,e),CW6({cli:t,cliContext:e,onRun:()=>{e.suppressUpgradeMessage()}}),UW6(t,e),VW6(t,e),n$f(t,e),i$f(t,e),t.middleware(async r=>{e.setLogLevel(r["log-level"]),e.logDebugInfo()}),await t.parse()}async function mW6(e){if(process.env.FERN_NO_VERSION_REDIRECTION==="true")return e.environment.packageVersion;let t=await VNr();if(t!=null){let r=await e.runTask(n=>p8t.loadProjectConfig({directory:t,context:n}));return r.version==="*"?e.environment.packageVersion:r.version}return Q3n({cliEnvironment:e.environment})}function OW6(e,t){e.command("init","Initialize a Fern API",r=>r.option("api",{boolean:!0,description:"Initialize an api."}).option("docs",{boolean:!0,description:"Initialize a docs website."}).option("organization",{alias:"org",type:"string",description:"Organization name"}).option("openapi",{type:"string",description:"Filepath or url to an existing OpenAPI spec"}),async r=>{if(r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.");if(r.docs!=null)await t.runTask(async n=>{await dgu({organization:r.organization,versionOfCli:await Q3n({cliEnvironment:t.environment}),taskContext:n})});else{let n;if(r.openapi!=null){if(UUg(r.openapi)){let a=await EMf({url:r.openapi,logger:t.logger});a.status==="failure"&&t.failAndThrow(a.errorMessage);let u=a.filePath;n=v_.of(u)}else n=v_.of(rT(t6t(),r.openapi));await Wh(n)||t.failAndThrow(`${n} does not exist`)}await t.runTask(async i=>{await fgu({organization:r.organization,versionOfCli:await Q3n({cliEnvironment:t.environment}),context:i,openApiPath:n})})}})}function PW6(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async n=>{await f5g({orgId:r.organization??(await Tq(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:n})})})}function wW6(e,t){e.command("add <generator>",`Add a code generator to ${mz}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{await o$f({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:r.generator,groupName:r.group,cliContext:t})})}function jW6(e,t){e.command(["generate"],"Generate all generators in the specified group",r=>r.option("api",{string:!0,description:"If multiple APIs, specify the name with --api <name>. Otherwise, just --api."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("group",{type:"string",description:"The group to generate"}).option("mode",{choices:Object.values($8g),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally, using Docker"}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}),async r=>r.api!=null&&r.docs!=null?t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one."):r.local&&r.preview?t.failWithoutThrowing("The --local flag is incompatible with --preview."):r.api!=null?await cNc({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode}):r.docs!=null?(r.group!=null&&t.logger.warn("--group is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await K8g({project:await Tq(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview})):await cNc({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode}))}function DW6(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(nP.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the IR for certain audiences"}),async r=>{await _Tg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:rT(t6t(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:!1,readme:void 0})})}function SW6(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(nP.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await vTg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:rT(t6t(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function EW6(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(nP.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the IR for certain audiences"}),async r=>{await YUg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:rT(t6t(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:!1})})}function AW6(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the FDR API definition for certain audiences"}),async r=>{await Ljd({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:rT(t6t(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function MW6(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let n=await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),i=await t.runTask(a=>kCe(a));await u5g({project:n,cliContext:t,token:i,version:r.version})})}function xW6(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let n=await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),i=await t.runTask(a=>kCe(a));await s5g({project:n,cliContext:t,token:i})})}function TW6(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}),async r=>{await RUg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,logWarnings:r.warnings})})}function CW6({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades version in ${Xzt}. Also upgrades generators in ${mz} to their minimum-compatible versions.`,n=>n.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}),async n=>{await zUg({cliContext:t,includePreReleases:n.rc,targetVersion:n.version}),r()})}function qW6(e,t){e.command("api update",`Pulls the latest OpenAPI spec from the specified origin in ${mz} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}),async r=>{await t.instrumentPostHogEvent({command:"fern api update"}),await h5g({cliContext:t,project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0})})})}function IW6(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}),async r=>{await t.runTask(async n=>{await t.instrumentPostHogEvent({command:"fern login"}),await Hvi(n,{useDeviceCodeFlow:r.deviceCode})})})}function BW6(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern format"}),await zjd({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function NW6(e,t){e.command("test","Runs tests specified in --command, this spins up a mock server in the background that is terminated upon completion of the tests.",r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(nP.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{await t.instrumentPostHogEvent({command:"fern test"}),await c5g({cliContext:t,project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function zW6(e,t){e.command("mock","Starts a mock server for an API.",r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{await t.instrumentPostHogEvent({command:"fern mock"}),await t5g({cliContext:t,project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function RW6(e,t){e.command("write-overrides","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{await t.instrumentPostHogEvent({command:"fern generate-overrides"}),await gTg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function FW6(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(nP.GenerationLanguage),description:"Write the definition for a particular SDK language"}),async r=>{await t.instrumentPostHogEvent({command:"fern write-definition"}),await FUg({project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language}),cliContext:t,sdkLanguage:r.language})})}function LW6(e,t){e.command("docs dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}),async r=>{let n;r.port!=null?n=r.port:n=await nbi({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]});let i=r.bundlePath;await Njd({loadProject:()=>Tq(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:n,bundlePath:i})})}function UW6(e,t){e.command("jsonschema <path-to-output>","Generate JSON Schema for a specific type",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).positional("path-to-output",{type:"string",description:"Path to write JSON Schema",demandOption:!0}).option("type",{string:!0,demandOption:!0,description:"The type to generate JSON Schema for (e.g. 'MySchema' or 'mypackage.MySchema')"}),async r=>{await t.instrumentPostHogEvent({command:"fern jsonschema",properties:{output:r.output}}),await GUg({typeLocator:r.type,project:await Tq(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),jsonschemaFilepath:rT(t6t(),r.pathToOutput),cliContext:t})})}function VW6(e,t){e.command("write-docs-definition <output-path>",!1,r=>r.positional("output-path",{type:"string",description:"Path to write the docs definition",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern write-docs-definition",properties:{outputPath:r.outputPath}}),await ZUg({project:await Tq(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),outputPath:rT(t6t(),r.outputPath),cliContext:t})})}
2323
2323
  /*! Bundled license information:
2324
2324
 
2325
2325
  tmp/lib/tmp.js: