fern-api 0.65.33 → 0.65.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +3 -3
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1712,7 +1712,7 @@ ${GAp.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&cJs(th
1712
1712
  `+NHi.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?NHi.default.cyan(tqp(t,this.opt.mask)):NHi.default.italic(NHi.default.dim("[hidden]")):this.opt.mask?tqp(t,this.opt.mask):NHi.default.italic(NHi.default.dim("[input is hidden] "))}getSpinningValue(t){return this.getMaskedValue(t)}filterInput(t){return t||(this.opt.default==null?"":this.opt.default)}onEnd(t){this.status="answered",this.answer=t.value,this.render(),this.screen.done(),this.done(t.value)}onError(t){this.render(t.isValid)}onKeypress(){this.opt.default&&=void 0,this.render()}};var e3o=ui(F2(),1),DTp=ui(tKs(),1),ETp=ui(VEe(),1);var nEa=class extends L2{_run(t){this.done=t,this.editorResult=new ETp.Subject;let r=EW(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?e3o.default.dim("Received"):e3o.default.dim("Press <enter> to launch your preferred editor."),t&&(r=e3o.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,DTp.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 CTp=require("stream");var qTp=ui(require("readline"),1),TTp=ui(ATp(),1),GHi=class{constructor(t){this.rl||=qTp.default.createInterface(S_D(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 S_D(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new TTp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var aEa=class extends GHi{constructor(t={}){super(t),this.log=new CTp.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return LDa(this.rl,this.bottomBar.split(`
1713
1713
  `).length),this}updateBottomBar(t){return LDa(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+`
1714
1714
  `}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&&MFo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var UE=ui(VEe(),1),zTp=ui(sDa(),1);var t3o=ui(VEe(),1),BTp=ui(sDa(),1),r3o=function(e,t,r){return typeof e[t]!="function"?(0,t3o.of)(e):(0,t3o.from)((0,BTp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var ITp={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,u)=>{n==="__proto__"||n==="constructor"||(a===u.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((u,l)=>u!=null?u[l]:u,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},yFn=class extends GHi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let i;return Array.isArray(t)?i=(0,UE.from)(t):(0,UE.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,UE.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,UE.from)([t]),this.process=i.pipe((0,UE.concatMap)(this.processQuestion.bind(this)),(0,UE.publish)()),this.process.connect(),this.process.pipe((0,UE.reduce)((n,a)=>(ITp.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,UE.defer)(()=>(0,UE.of)(t).pipe((0,UE.concatMap)(this.setDefaultType.bind(this)),(0,UE.concatMap)(this.filterIfRunnable.bind(this)),(0,UE.concatMap)(()=>r3o(t,"message",this.answers)),(0,UE.concatMap)(()=>r3o(t,"default",this.answers)),(0,UE.concatMap)(()=>r3o(t,"choices",this.answers)),(0,UE.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,UE.defer)(()=>(0,UE.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,UE.defer)(()=>(0,UE.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&ITp.get(this.answers,t.name)!==void 0)return UE.EMPTY;if(t.when===!1)return UE.EMPTY;if(typeof t.when!="function")return(0,UE.of)(t);let{answers:r}=this;return(0,UE.defer)(()=>(0,UE.from)((0,zTp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,UE.filter)(i=>i!=null)))}};function xTp(e){let t=function(r,i){let n;try{n=new yFn(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",VDa),this.registerPrompt("input",RHi),this.registerPrompt("number",WDa),this.registerPrompt("confirm",HDa),this.registerPrompt("rawlist",$Da),this.registerPrompt("expand",GDa),this.registerPrompt("checkbox",QDa),this.registerPrompt("password",JDa),this.registerPrompt("editor",nEa)},t.restoreDefaultPrompts(),t}var iKs=xTp();function E_D(e,t){iKs.registerPrompt(e,t)}function M_D(){iKs.restoreDefaultPrompts()}var A_D={prompt:iKs,ui:{BottomBar:aEa,Prompt:yFn},createPromptModule:xTp,registerPrompt:E_D,restoreDefaultPrompts:M_D,Separator:cae},i3o=A_D;var MFn=require("path"),yBp=require("fs"),vBp=require("readline"),UCp="posthog-node";function lvD(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"]}={}){return a=>{if(!(n==="*"||n.includes(a.level)))return a;a.tags||(a.tags={});let l=a.tags[S3o.POSTHOG_ID_TAG];if(l===void 0)return a;let d=e.options.host??"https://us.i.posthog.com",s=new URL(`/project/${e.apiKey}/person/${l}`,d).toString();a.tags["PostHog Person URL"]=s;let o=a.exception?.values||[],c=o.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(O=>({...O,platform:"node:javascript"}))}:void 0})),b={$exception_message:o[0]?.value||a.message,$exception_type:o[0]?.type,$exception_personURL:s,$exception_level:a.level,$exception_list:c,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:o[0]?.value||a.message,$sentry_exception_type:o[0]?.type,$sentry_tags:a.tags};return t&&r&&(b.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:l,properties:b}),a}}var S3o=class{constructor(t,r,i,n){this.name=UCp,this.name=UCp,this.setupOnce=function(a,u){let l=u()?.getClient()?.getDsn()?.projectId;a(lvD(t,{organization:r,projectId:l,prefix:i,severityAllowList:n}))}}};S3o.POSTHOG_ID_TAG="posthog_distinct_id";var O3o="0123456789abcdef",D3o=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O3o.charAt(this.bytes[r]>>>4),t+=O3o.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O3o.charAt(this.bytes[r]>>>4),t+=O3o.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},GKs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??fvD()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return D3o.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,D3o.ofInner(t)}},fvD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),VCp,QKs=()=>dvD().toString(),dvD=()=>(VCp||(VCp=new GKs)).generate();function pvD(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(u=>u.name!=="domainUncaughtExceptionClear"&&u._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t())},{_posthogErrorHandler:!0})}function _vD(e,t){global.process.on("uncaughtException",pvD(e,t))}function hvD(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var m3o,WCp,P3o;function yvD(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return P3o&&r.length===WCp||(WCp=r.length,P3o=r.reduce((i,n)=>{m3o||(m3o={});let a=m3o[n];if(a)i[a[0]]=a[1];else{let u=e(n);for(let l=u.length-1;l>=0;l--){let s=u[l]?.filename,o=t[n];if(s&&o){i[s]=o,m3o[n]=[s,o];break}}}return i},{})),P3o}function vvD(e){return typeof Event<"u"&&bBp(e,Event)}function bvD(e){return gBp(e,"Object")}function tYs(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return bBp(e,Error)}}function bBp(e,t){try{return e instanceof t}catch{return!1}}function gvD(e){return gBp(e,"ErrorEvent")}function gBp(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function OvD(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},u=OBp(a,r,i);return{$exception_list:await Promise.all(u.map(async s=>{let o=await EvD(e,t,s);return o.value=o.value||"",o.type=o.type||"Error",o.mechanism=a,o}))}}function OBp(e,t,r){let i=mvD(e,t,r);return i.cause?[i,...OBp(e,i.cause,r)]:[i]}function mvD(e,t,r){if(tYs(t))return t;if(e.synthetic=!0,bvD(t)){let n=PvD(t);if(n)return n;let a=jvD(t),u=r?.syntheticException||new Error(a);return u.message=a,u}let i=r?.syntheticException||new Error(t);return i.message=`${t}`,i}function PvD(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(tYs(r))return r}}function jvD(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(i+=` with message '${e.message}'`),i}else if("message"in e&&typeof e.message=="string")return e.message;let t=SvD(e);if(gvD(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=wvD(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function wvD(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function SvD(e,t=40){let r=Object.keys(DvD(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return HCp(i,t);for(let n=r.length;n>0;n--){let a=r.slice(0,n).join(", ");if(!(a.length>t))return n===r.length?a:HCp(a,t)}return""}function HCp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function DvD(e){return tYs(e)?{message:e.message,name:e.name,stack:e.stack,...$Cp(e)}:vvD(e)?{type:e.type,target:GCp(e.target),currentTarget:GCp(e.currentTarget),...$Cp(e)}:e}function $Cp(e){if(typeof e=="object"&&e!==null){let t={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}else return{}}function GCp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function EvD(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=MvD(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function MvD(e,t){return AvD(e(t.stack||"",1),e)}function AvD(e,t){let r=yvD(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var qvD=2e3,SFn=class e{static async captureException(t,r,i,n,a){let u={...a};n||(u.$process_person_profile=!1);let l=await OvD(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||QKs(),properties:{...l,...u}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(_vD(this.onException.bind(this),this.onFatalError.bind(this)),hvD(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(qvD)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function TvD(e=process.argv[1]?(0,MFn.dirname)(process.argv[1]):process.cwd(),t=MFn.sep==="\\"){let r=t?QCp(e):e;return i=>{if(!i)return;let n=t?QCp(i):i,{dir:a,base:u,ext:l}=MFn.posix.parse(n);(l===".js"||l===".mjs"||l===".cjs")&&(u=u.slice(0,l.length*-1));let d=decodeURIComponent(u);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let o=a.slice(r.length+1).replace(/\//g,".");return o?`${o}:${d}`:d}return d}}function QCp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var E3o=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}},w3o=new E3o(25),mBp=new E3o(20),rYs=7,CvD=1e3,BvD=1e4;async function IvD(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],u=a?.filename;if(!a||typeof u!="string"||typeof a.lineno!="number"||NvD(u)||FvD(a))continue;t[u]||(t[u]=[]),t[u].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(mBp.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let u=UvD(a);if(u.every(d=>LvD(n,d)))continue;let l=VvD(w3o,n,{});i.push(zvD(n,u,l))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&xvD(e,w3o),w3o.reduce(),e}function zvD(e,t,r){return new Promise(i=>{let n=(0,yBp.createReadStream)(e),a=(0,vBp.createInterface)({input:n});function u(){n.destroy(),i()}let l=0,d=0,s=t[d];if(s===void 0){u();return}let o=s[0],c=s[1];function b(){mBp.set(e,1),a.close(),a.removeAllListeners(),u()}n.on("error",b),a.on("error",b),a.on("close",u),a.on("line",g=>{if(l++,!(l<o)&&(r[l]=WvD(g,0),l>=c)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let O=t[d];if(O===void 0){a.close(),a.removeAllListeners();return}o=O[0],c=O[1]}})})}function xvD(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;RvD(r.lineno,r,i)}}function RvD(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=PBp(e);n<e;n++){let a=r[n];if(a===void 0){JCp(t);return}t.pre_context.push(a)}if(r[e]===void 0){JCp(t);return}t.context_line=r[e];let i=jBp(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function JCp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function NvD(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function FvD(e){return e.lineno!==void 0&&e.lineno>BvD||e.colno!==void 0&&e.colno>CvD}function LvD(e,t){let r=w3o.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function UvD(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=KCp(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+rYs:(n.push(i),i=KCp(a)),t++}return n}function KCp(e){return[PBp(e),jBp(e)]}function PBp(e){return Math.max(1,e-rYs)}function jBp(e){return e+rYs}function VvD(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function WvD(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}var HvD="4.18.0",hae;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.DecideEndpointWasHit="decide_endpoint_was_hit",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config"})(hae||(hae={}));var YCp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(YCp||(YCp={}));var XCp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(XCp||(XCp={}));var ZCp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(ZCp||(ZCp={}));var kCp;(function(e){e.Html="html",e.Text="text"})(kCp||(kCp={}));var eBp;(function(e){e.Number="number",e.Emoji="emoji"})(eBp||(eBp={}));var tBp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(tBp||(tBp={}));var rBp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(rBp||(rBp={}));var iBp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(iBp||(iBp={}));var nBp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(nBp||(nBp={}));var $vD=e=>{if("flags"in e){let t=QvD(e.flags),r=JvD(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,wBp(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,GvD(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function GvD(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var QvD=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,iYs(r)]).filter(([,t])=>t!==void 0)),JvD=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map(r=>{let i=t[r].metadata?.payload;return[r,i?wBp(i):void 0]}))},iYs=e=>e===void 0?void 0:e.variant??e.enabled,wBp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},KvD=1,YvD=new Set(["61be3dd8","96f6df5f","8cfdba9b","bf027177","e59430a8","7fa5500b","569798e9","04809ff7","0ebc61a5","32de7f98","3beeb69a","12d34ad9","733853ec","0645bb64","5dcbee21","b1f95fa3","2189e408","82b460c2","3a8cc979","29ef8843","2cdbf767","38084b54","50f9f8de","41d0df91","5c236689","c11aedd3","ada46672","f4331ee1","42fed62a","c957462c","d62f705a","e0162666","01b3e5cf","441cef7f","bb9cafee","8f348eb0","b2553f3a","97469d7d","39f21a76","03706dcc","27d50569","307584a7","6433e92e","150c7fbb","49f57f22","3772f65b","01eb8256","3c9e9234","f853c7f7","c0ac4b67","cd609d40","10ca9b1a","8a87f11b","8e8e5216","1f6b63b3","db7943dd","79b7164c","07f78e33","2d21b6fd","952db5ee","a7d3b43f","1924dd9c","84e1b8f6","dff631b6","c5aa8a79","fa133a95","498a4508","24748755","98f3d658","21bbda67","7dbfed69","be3ec24c","fc80b8e2","75cc0998"]),XvD="utf8";function ZvD(e,t){if(!e||typeof e!="string"||kvD(e))throw new Error(t)}function kvD(e){return e.trim().length===0}function ebD(e){return e?.replace(/\/+$/,"")}async function tbD(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function aBp(){return new Date().getTime()}function HKs(){return new Date().toISOString()}function M3o(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function rbD(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function ibD(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return(t>>>0).toString(16).padStart(8,"0")}function nbD(e,t=0,r){let i=ibD(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function oBp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var hEa=String.fromCharCode,uBp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",j3o={};function abD(e,t){if(!j3o[e]){j3o[e]={};for(let r=0;r<e.length;r++)j3o[e][e.charAt(r)]=r}return j3o[e][t]}var jFn={compressToBase64:function(e){if(e==null)return"";let t=jFn._compress(e,6,function(r){return uBp.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:jFn._decompress(e.length,32,function(t){return abD(uBp,e.charAt(t))})},compress:function(e){return jFn._compress(e,16,function(t){return hEa(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,w;for(w=0;w<e.length;w+=1)if(d=e.charAt(w),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:jFn._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,l=4,d=3,s="",o,c,b,g,O,m,w;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=hEa(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=hEa(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(w=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=hEa(b),w=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=hEa(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[w])s=i[w];else if(w===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},JKs=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}},DFn=class extends Error{constructor(t,r){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},yEa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function sBp(e){if(e instanceof DFn){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function $Ks(e){return typeof e=="object"&&(e instanceof DFn||e instanceof yEa)}function cBp(e){return typeof e=="object"&&e instanceof DFn&&e.status===413}var KKs;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(KKs||(KKs={}));var YKs=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new JKs,this._isInitialized=!1,ZvD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=ebD(r?.host||"https://us.i.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r?.maxQueueSize??1e3),this.flushInterval=r?.flushInterval??1e4,this.captureMode=r?.captureMode||"json",this.preloadFeatureFlags=r?.preloadFeatureFlags??!0,this.defaultOptIn=r?.defaultOptIn??!0,this.disableSurveys=r?.disableSurveys??!1,this._retryOptions={retryCount:r?.fetchRetryCount??3,retryDelay:r?.fetchRetryDelay??3e3,retryCheck:$Ks},this.requestTimeout=r?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r?.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r?.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r?.disableGeoip??!0,this.disabled=r?.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(hae.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(hae.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(hae.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=QKs();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(t,r,i){let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",n,i)}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}async captureStatelessImmediate(t,r,i,n){let a=this.buildPayload({distinct_id:t,event:r,properties:i});await this.sendImmediate("capture",a,n)}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}async aliasStatelessImmediate(t,r,i,n){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,n)}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,n)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this.logMsgIfDebug(()=>console.error("Remote config could not be loaded",n)),this._events.emit("error",n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let l=nbD(this.apiKey,KvD,YvD)?`${this.host}/flags/?v=2`:`${this.host}/decide/?v=4`,d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Decide URL",l)),this.fetchWithRetry(l,d,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>$vD(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagDetailStateless(t,r,i,n,a,u);if(l===void 0)return{response:void 0,requestId:void 0};let d=iYs(l.response);return d===void 0&&(d=!1),{response:d,requestId:l.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagDetailsStateless(r,i,n,a,u,[t]);return l===void 0?void 0:{response:l.flags[t],requestId:l.requestId}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u,[t]);if(!l)return;let d=l[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,u){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,u)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,u){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,u)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,u){await this._initPromise;let l=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,u);return l?{flags:l.featureFlags,payloads:l.featureFlagPayloads,requestId:l.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,u){await this._initPromise;let l={};(a??this.disableGeoip)&&(l.geoip_disable=!0),u&&(l.flag_keys_to_evaluate=u);let d=await this.getDecide(t,r,i,n,l);if(d!==void 0)return d.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),d.quotaLimited?.includes(KKs.FeatureFlags)?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:d?.requestId}):d}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this.logMsgIfDebug(()=>console.log("PostHog Debug","Loading surveys is disabled.")),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},n=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let u=`Surveys API could not be loaded: ${a.status}`,l=new Error(u);this.logMsgIfDebug(()=>console.error(l)),this._events.emit("error",new Error(u));return}return a.json()}).catch(a=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",a)),this._events.emit("error",a)}))?.surveys;return n&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(n))),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(hae.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(hae.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(hae.Props,this.props)})}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n=this.prepareMessage(t,r,i),a=this.getPersistedProperty(hae.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),a.push({message:n}),this.setPersistedProperty(hae.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=M3o(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized||await this._initPromise,this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:HKs()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),u=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${aBp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,l=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(jFn.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(u,l)}catch(d){this._events.emit("error",d)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:HKs(),uuid:i?.uuid?i.uuid:QKs()};return(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await sBp(t)})}async flush(){let t=oBp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),oBp([t]).then(()=>{this.flushPromise===t&&(this.flushPromise=null)}),t}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(hae.Queue)||[];if(!t.length)return;let r=[],i=t.length;for(;t.length>0&&r.length<i;){let n=t.slice(0,this.maxBatchSize),a=n.map(b=>b.message),u=()=>{let g=(this.getPersistedProperty(hae.Queue)||[]).slice(n.length);this.setPersistedProperty(hae.Queue,g),t=g},l={api_key:this.apiKey,batch:a,sent_at:HKs()};this.historicalMigration&&(l.historical_migration=!0);let d=JSON.stringify(l),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${aBp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,o=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(jFn.compressToBase64(d))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:d},c={retryCheck:b=>cBp(b)?!1:$Ks(b)};try{await this.fetchWithRetry(s,o,c)}catch(b){if(cBp(b)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`));continue}throw b instanceof yEa||u(),this._events.emit("error",b),b}u(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){var a;(a=AbortSignal).timeout??(a.timeout=function(s){let o=new AbortController;return setTimeout(()=>o.abort(),s),o.signal});let u=r.body?r.body:"",l=-1;try{l=Buffer.byteLength(u,XvD)}catch{l=new TextEncoder().encode(u).length}return await tbD(async()=>{let d=null;try{d=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(o){throw new yEa(o)}if(!(r.mode==="no-cors")&&(d.status<200||d.status>=400))throw new DFn(d,l);return d},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await Promise.all(Object.values(this.pendingPromises));!((this.getPersistedProperty(hae.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!$Ks(n))throw n;await sBp(n)}};return Promise.race([new Promise((n,a)=>{M3o(()=>{this.logMsgIfDebug(()=>console.error("Timed out while shutting down PostHog")),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),i()])}async shutdown(t=3e4){return this.shutdownPromise?this.logMsgIfDebug(()=>console.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup")):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}},XKs=rbD();if(!XKs){let e=LCp();XKs=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var SBp=XKs,A3o=class{constructor(t){this.factory=t}async getValue(){return this.value!==void 0?this.value:(this.initializationPromise===void 0&&(this.initializationPromise=(async()=>{try{let t=await this.factory();return this.value=t,t}finally{this.initializationPromise=void 0}})()),this.initializationPromise)}isInitialized(){return this.value!==void 0}async waitForInitialization(){this.isInitialized()||await this.getValue()}},DBp=new A3o(async()=>{try{return await import("crypto")}catch{return}});async function obD(){return await DBp.getValue()}var ubD=new A3o(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await DBp.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function sbD(){return await ubD.getValue()}async function cbD(e){let t=await obD();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await sbD();if(r){let i=await r.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}throw new Error("No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API")}var lbD=60*1e3,fbD=1152921504606847e3,dbD=["is_not"],wFn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},U2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},ZKs=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=l.fetch||SBp,this.onError=l.onError,this.customHeaders=u,this.onLoad=l.onLoad,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=await this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof U2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return await Promise.all(this.featureFlags.map(async d=>{try{let s=await this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof U2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}})),{response:a,payloads:u,fallbackToDecide:l}}async computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new U2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new U2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return await this.matchFeatureFlagProperties(t,i[d],s)}else return await this.matchFeatureFlagProperties(t,r,n)}async matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(await this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=await this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof U2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new U2("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=MBp(l,n,this.cohorts,this.debugMode):s=EBp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&await lBp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await lBp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(lbD,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.getPollingInterval());try{let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new wFn(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new wFn(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new wFn(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r)){this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));return}this.featureFlags=r.flags??[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||{},this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof wFn&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET"){return{method:t,headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions(),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=M3o(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}_requestRemoteConfigPayload(t){let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config/`,i=this.getPersonalApiKeyRequestOptions(),n=null;if(this.timeout&&typeof this.timeout=="number"){let a=new AbortController;n=M3o(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function lBp(e,t,r=""){let i=await cbD(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/fbD}function EBp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new U2("Operator is_not_set is not supported")}else throw new U2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!dbD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return fBp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return fBp(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=pbD(String(n));if(s==null&&(s=dBp(n)),s==null)throw new U2(`Invalid date: ${n}`);let o=dBp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new U2(`Unknown operator: ${a}`)}}function MBp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new U2("can't match cohort without a given cohort property value");let a=r[n];return ABp(a,t,r,i)}function ABp(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let l of a)try{let d=ABp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof U2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new U2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=MBp(l,t,r,i):d=EBp(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof U2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new U2("can't match cohort without a given cohort property value");return n==="AND"}}function fBp(e){try{return new RegExp(e),!0}catch{return!1}}function dBp(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new U2(`${e} is in an invalid date format`)}else throw new U2(`The date provided ${e} must be a string, number, or date object`)}function pbD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var kKs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},_bD=100,pBp=30*1e3,hbD=50*1e3,eYs=class extends YKs{constructor(t,r={}){if(super(t,r),this._memoryStorage=new kKs,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,_bD):pBp,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');this.featureFlagsPoller=new ZKs({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders()})}this.errorTracking=new SFn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||hbD}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):SBp(t,r)}getLibraryVersion(){return HvD}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:u,timestamp:l,disableGeoip:d,uuid:s}=t,o=g=>{super.captureStateless(r,i,g,{timestamp:l,disableGeoip:d,uuid:s})},c=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags,b=Promise.resolve().then(async()=>{if(u)return await c(r,a,d);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[O,m]of Object.entries(a||{}))g[O]=String(m);return await this.getAllFlags(r,{groups:g,disableGeoip:d,onlyEvaluateLocally:!0})}return{}}).then(g=>{let O={};if(g)for(let[w,E]of Object.entries(g))O[`$feature/${w}`]=E;let m=Object.keys(g||{}).filter(w=>g?.[w]!==!1).sort();return m.length>0&&(O.$active_feature_flags=m),O}).catch(()=>({})).then(g=>{o({...g,...n,$groups:a})});this.addPendingPromise(b)}async captureImmediate(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:u,timestamp:l,disableGeoip:d,uuid:s}=t,o=g=>super.captureStatelessImmediate(r,i,g,{timestamp:l,disableGeoip:d,uuid:s}),c=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags;await Promise.resolve().then(async()=>{if(u)return await c(r,a,d);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[O,m]of Object.entries(a||{}))g[O]=String(m);return await this.getAllFlags(r,{groups:g,disableGeoip:d,onlyEvaluateLocally:!0})}return{}}).then(g=>{let O={};if(g)for(let[w,E]of Object.entries(g))O[`$feature/${w}`]=E;let m=Object.keys(g||{}).filter(w=>g?.[w]!==!1).sort();return m.length>0&&(O.$active_feature_flags=m),O}).catch(()=>({})).then(g=>{o({...g,...n,$groups:a})})}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;super.identifyStateless(t,{$set:a,$set_once:n},{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;await super.identifyStatelessImmediate(t,{$set:a,$set_once:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=pBp){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0,g,O;if(!b&&!u){let w=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(w===void 0)return;O=w.response,c=iYs(O),g=w?.requestId}let m=`${t}_${c}`;return l&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(m))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(m):this.distinctIdHasSentFlagCalls[r]=[m],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:c,$feature_flag_id:O?.metadata?.id,$feature_flag_version:O?.metadata?.version,$feature_flag_reason:O?.reason?.description??O?.reason?.code,locally_evaluated:b,[`$feature/${t}`]:c,$feature_flag_request_id:g},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.allGroupProperties;let b;return this.featureFlagsPoller!==void 0&&(i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i))),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async getRemoteConfigPayload(t){return(await this.featureFlagsPoller?._requestRemoteConfigPayload(t))?.json()}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(),super._shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}captureException(t,r,i){let n=new Error("PostHog syntheticException");SFn.captureException(this,t,{syntheticException:n},r,i)}},_Bp=/\(error: (.*)\)/,qBp=50,TBp="?";function ybD(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return i=>{let n=i.match(r);if(n){let a,u,l,d,s;if(n[1]){l=n[1];let b=l.lastIndexOf(".");if(l[b-1]==="."&&b--,b>0){a=l.slice(0,b),u=l.slice(b+1);let g=a.indexOf(".Module");g>0&&(l=l.slice(g+1),a=a.slice(0,g))}d=void 0}u&&(d=a,s=u),u==="<anonymous>"&&(s=void 0,l=void 0),l===void 0&&(s=s||TBp,l=d?`${d}.${s}`:s);let o=n[2]?.startsWith("file://")?n[2].slice(7):n[2],c=n[5]==="native";return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),!o&&n[5]&&!c&&(o=n[5]),{filename:o?decodeURI(o):void 0,module:e?e(o):void 0,function:l,lineno:hBp(n[3]),colno:hBp(n[4]),in_app:vbD(o||"",c),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function vbD(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function hBp(e){return parseInt(e||"",10)||void 0}function bbD(e){return[90,ybD(e)]}function gbD(e){let r=[bbD(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],u=i.split(`
1715
- `);for(let l=n;l<u.length;l++){let d=u[l];if(d.length>1024)continue;let s=_Bp.test(d)?d.replace(_Bp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let c=o(s);if(c){a.push(c);break}}if(a.length>=qBp)break}}return ObD(a)}}function ObD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,qBp).map(r=>({...r,filename:r.filename||mbD(t).filename,function:r.function||TBp}))}function mbD(e){return e[e.length-1]||{}}SFn.stackParser=gbD(TvD());SFn.frameModifiers=[IvD];var EFn=class extends eYs{getLibraryId(){return"posthog-node"}};var q3o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new EFn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.65.33",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var vEa=class{async sendEvent(){}async identify(){}async flush(){}};var AFn=require("fs/promises"),zBp=require("os"),xBp=require("path");var CBp=ui(require("crypto")),C3o=new Uint8Array(256),T3o=C3o.length;function nYs(){return T3o>C3o.length-16&&(CBp.default.randomFillSync(C3o),T3o=0),C3o.slice(T3o,T3o+=16)}var qW=[];for(let e=0;e<256;++e)qW.push((e+256).toString(16).slice(1));function BBp(e,t=0){return qW[e[t+0]]+qW[e[t+1]]+qW[e[t+2]]+qW[e[t+3]]+"-"+qW[e[t+4]]+qW[e[t+5]]+"-"+qW[e[t+6]]+qW[e[t+7]]+"-"+qW[e[t+8]]+qW[e[t+9]]+"-"+qW[e[t+10]]+qW[e[t+11]]+qW[e[t+12]]+qW[e[t+13]]+qW[e[t+14]]+qW[e[t+15]]}var IBp=ui(require("crypto")),aYs={randomUUID:IBp.default.randomUUID};function PbD(e,t,r){if(aYs.randomUUID&&!t&&!e)return aYs.randomUUID();e=e||{};let i=e.random||(e.rng||nYs)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return BBp(i)}var yae=PbD;var jbD="id",wbD=".fern",bEa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new EFn(r),this.userId=t==null?void 0:KVs(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.65.33",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Tu(pl.of((0,zBp.homedir)()),Ra.of(wbD),Ra.of(jbD));await yf(t)||(await(0,AFn.mkdir)((0,xBp.dirname)(t),{recursive:!0}),await(0,AFn.writeFile)(t,yae())),this.persistedDistinctId=(await(0,AFn.readFile)(t)).toString()}return this.persistedDistinctId}};var oYs;async function qFn(){return oYs==null&&(oYs=await SbD()),oYs}async function SbD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new vEa;let r=await XBo();return r!=null?new bEa({token:r,posthogApiKey:e}):await ARn()!=null?new q3o({posthogApiKey:e}):new bEa({token:void 0,posthogApiKey:e})}catch{return new vEa}}function gEa(e,t){return function(){return e.apply(t,arguments)}}var{toString:DbD}=Object.prototype,{getPrototypeOf:sYs}=Object,{iterator:I3o,toStringTag:NBp}=Symbol,z3o=(e=>t=>{let r=DbD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),cWt=e=>(e=e.toLowerCase(),t=>z3o(t)===e),x3o=e=>t=>typeof t===e,{isArray:TFn}=Array,OEa=x3o("undefined");function EbD(e){return e!==null&&!OEa(e)&&e.constructor!==null&&!OEa(e.constructor)&&vae(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var FBp=cWt("ArrayBuffer");function MbD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&FBp(e.buffer),t}var AbD=x3o("string"),vae=x3o("function"),LBp=x3o("number"),R3o=e=>e!==null&&typeof e=="object",qbD=e=>e===!0||e===!1,B3o=e=>{if(z3o(e)!=="object")return!1;let t=sYs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(NBp in e)&&!(I3o in e)},TbD=cWt("Date"),CbD=cWt("File"),BbD=cWt("Blob"),IbD=cWt("FileList"),zbD=e=>R3o(e)&&vae(e.pipe),xbD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||vae(e.append)&&((t=z3o(e))==="formdata"||t==="object"&&vae(e.toString)&&e.toString()==="[object FormData]"))},RbD=cWt("URLSearchParams"),[NbD,FbD,LbD,UbD]=["ReadableStream","Request","Response","Headers"].map(cWt),VbD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function mEa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),TFn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function UBp(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var ZHi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,VBp=e=>!OEa(e)&&e!==ZHi;function uYs(){let{caseless:e}=VBp(this)&&this||{},t={},r=(i,n)=>{let a=e&&UBp(t,n)||n;B3o(t[a])&&B3o(i)?t[a]=uYs(t[a],i):B3o(i)?t[a]=uYs({},i):TFn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&mEa(arguments[i],r);return t}var WbD=(e,t,r,{allOwnKeys:i}={})=>(mEa(t,(n,a)=>{r&&vae(n)?e[a]=gEa(n,r):e[a]=n},{allOwnKeys:i}),e),HbD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),$bD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},GbD=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&sYs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},QbD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},JbD=e=>{if(!e)return null;if(TFn(e))return e;let t=e.length;if(!LBp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},KbD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&sYs(Uint8Array)),YbD=(e,t)=>{let i=(e&&e[I3o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},XbD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},ZbD=cWt("HTMLFormElement"),kbD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),RBp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),e0D=cWt("RegExp"),WBp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};mEa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},t0D=e=>{WBp(e,(t,r)=>{if(vae(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(vae(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},r0D=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return TFn(e)?i(e):i(String(e).split(t)),r},i0D=()=>{},n0D=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function a0D(e){return!!(e&&vae(e.append)&&e[NBp]==="FormData"&&e[I3o])}var o0D=e=>{let t=new Array(10),r=(i,n)=>{if(R3o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=TFn(i)?[]:{};return mEa(i,(u,l)=>{let d=r(u,n+1);!OEa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},u0D=cWt("AsyncFunction"),s0D=e=>e&&(R3o(e)||vae(e))&&vae(e.then)&&vae(e.catch),HBp=((e,t)=>e?setImmediate:t?((r,i)=>(ZHi.addEventListener("message",({source:n,data:a})=>{n===ZHi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),ZHi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",vae(ZHi.postMessage)),c0D=typeof queueMicrotask<"u"?queueMicrotask.bind(ZHi):typeof process<"u"&&process.nextTick||HBp,l0D=e=>e!=null&&vae(e[I3o]),os={isArray:TFn,isArrayBuffer:FBp,isBuffer:EbD,isFormData:xbD,isArrayBufferView:MbD,isString:AbD,isNumber:LBp,isBoolean:qbD,isObject:R3o,isPlainObject:B3o,isReadableStream:NbD,isRequest:FbD,isResponse:LbD,isHeaders:UbD,isUndefined:OEa,isDate:TbD,isFile:CbD,isBlob:BbD,isRegExp:e0D,isFunction:vae,isStream:zbD,isURLSearchParams:RbD,isTypedArray:KbD,isFileList:IbD,forEach:mEa,merge:uYs,extend:WbD,trim:VbD,stripBOM:HbD,inherits:$bD,toFlatObject:GbD,kindOf:z3o,kindOfTest:cWt,endsWith:QbD,toArray:JbD,forEachEntry:YbD,matchAll:XbD,isHTMLForm:ZbD,hasOwnProperty:RBp,hasOwnProp:RBp,reduceDescriptors:WBp,freezeMethods:t0D,toObjectSet:r0D,toCamelCase:kbD,noop:i0D,toFiniteNumber:n0D,findKey:UBp,global:ZHi,isContextDefined:VBp,isSpecCompliantForm:a0D,toJSONObject:o0D,isAsyncFn:u0D,isThenable:s0D,setImmediate:HBp,asap:c0D,isIterable:l0D};function CFn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}os.inherits(CFn,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:os.toJSONObject(this.config),code:this.code,status:this.status}}});var $Bp=CFn.prototype,GBp={};["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=>{GBp[e]={value:e}});Object.defineProperties(CFn,GBp);Object.defineProperty($Bp,"isAxiosError",{value:!0});CFn.from=(e,t,r,i,n,a)=>{let u=Object.create($Bp);return os.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),CFn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Fp=CFn;var QBp=ui(n3o(),1),N3o=QBp.default;function cYs(e){return os.isPlainObject(e)||os.isArray(e)}function KBp(e){return os.endsWith(e,"[]")?e.slice(0,-2):e}function JBp(e,t,r){return e?e.concat(t).map(function(n,a){return n=KBp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function f0D(e){return os.isArray(e)&&!e.some(cYs)}var d0D=os.toFlatObject(os,{},null,function(t){return/^is[A-Z]/.test(t)});function p0D(e,t,r){if(!os.isObject(e))throw new TypeError("target must be an object");t=t||new(N3o||FormData),r=os.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!os.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&os.isSpecCompliantForm(t);if(!os.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(os.isDate(O))return O.toISOString();if(os.isBoolean(O))return O.toString();if(!d&&os.isBlob(O))throw new Fp("Blob is not supported. Use a Buffer instead.");return os.isArrayBuffer(O)||os.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let E=O;if(O&&!w&&typeof O=="object"){if(os.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(os.isArray(O)&&f0D(O)||(os.isFileList(O)||os.endsWith(m,"[]"))&&(E=os.toArray(O)))return m=KBp(m),E.forEach(function(M,D){!(os.isUndefined(M)||M===null)&&t.append(u===!0?JBp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return cYs(O)?!0:(t.append(JBp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(d0D,{defaultVisitor:o,convertValue:s,isVisitable:cYs});function g(O,m){if(!os.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),os.forEach(O,function(E,q){(!(os.isUndefined(E)||E===null)&&n.call(t,E,os.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!os.isObject(e))throw new TypeError("data must be an object");return g(e),t}var kSi=p0D;function YBp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function XBp(e,t){this._pairs=[],e&&kSi(e,this,t)}var ZBp=XBp.prototype;ZBp.append=function(t,r){this._pairs.push([t,r])};ZBp.toString=function(t){let r=t?function(i){return t.call(this,i,YBp)}:YBp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var kBp=XBp;function _0D(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function kHi(e,t,r){if(!t)return e;let i=r&&r.encode||_0D;os.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=os.isURLSearchParams(t)?t.toString():new kBp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var lYs=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){os.forEach(this.handlers,function(i){i!==null&&t(i)})}},fYs=lYs;var BFn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var iIp=ui(require("crypto"),1);var eIp=ui(require("url"),1),tIp=eIp.default.URLSearchParams;var dYs="abcdefghijklmnopqrstuvwxyz",rIp="0123456789",nIp={DIGIT:rIp,ALPHA:dYs,ALPHA_DIGIT:dYs+dYs.toUpperCase()+rIp},h0D=(e=16,t=nIp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);iIp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},aIp={isNode:!0,classes:{URLSearchParams:tIp,FormData:N3o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:nIp,generateString:h0D,protocols:["http","https","file","data"]};var hYs={};Po(hYs,{hasBrowserEnv:()=>_Ys,hasStandardBrowserEnv:()=>y0D,hasStandardBrowserWebWorkerEnv:()=>v0D,navigator:()=>pYs,origin:()=>b0D});var _Ys=typeof window<"u"&&typeof document<"u",pYs=typeof navigator=="object"&&navigator||void 0,y0D=_Ys&&(!pYs||["ReactNative","NativeScript","NS"].indexOf(pYs.product)<0),v0D=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",b0D=_Ys&&window.location.href||"http://localhost";var oA={...hYs,...aIp};function yYs(e,t){return kSi(e,new oA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return oA.isNode&&os.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function g0D(e){return os.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function O0D(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function m0D(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&os.isArray(n)?n.length:u,d?(os.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!os.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&os.isArray(n[u])&&(n[u]=O0D(n[u])),!l)}if(os.isFormData(e)&&os.isFunction(e.entries)){let r={};return os.forEachEntry(e,(i,n)=>{t(g0D(i),n,r,0)}),r}return null}var F3o=m0D;function P0D(e,t,r){if(os.isString(e))try{return(t||JSON.parse)(e),os.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var vYs={transitional:BFn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=os.isObject(t);if(a&&os.isHTMLForm(t)&&(t=new FormData(t)),os.isFormData(t))return n?JSON.stringify(F3o(t)):t;if(os.isArrayBuffer(t)||os.isBuffer(t)||os.isStream(t)||os.isFile(t)||os.isBlob(t)||os.isReadableStream(t))return t;if(os.isArrayBufferView(t))return t.buffer;if(os.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return yYs(t,this.formSerializer).toString();if((l=os.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return kSi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),P0D(t)):t}],transformResponse:[function(t){let r=this.transitional||vYs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(os.isResponse(t)||os.isReadableStream(t))return t;if(t&&os.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Fp.from(l,Fp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:oA.classes.FormData,Blob:oA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};os.forEach(["delete","get","head","post","put","patch"],e=>{vYs.headers[e]={}});var IFn=vYs;var j0D=os.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"]),oIp=e=>{let t={},r,i,n;return e&&e.split(`
1715
+ `);for(let l=n;l<u.length;l++){let d=u[l];if(d.length>1024)continue;let s=_Bp.test(d)?d.replace(_Bp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let c=o(s);if(c){a.push(c);break}}if(a.length>=qBp)break}}return ObD(a)}}function ObD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,qBp).map(r=>({...r,filename:r.filename||mbD(t).filename,function:r.function||TBp}))}function mbD(e){return e[e.length-1]||{}}SFn.stackParser=gbD(TvD());SFn.frameModifiers=[IvD];var EFn=class extends eYs{getLibraryId(){return"posthog-node"}};var q3o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new EFn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.65.34",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var vEa=class{async sendEvent(){}async identify(){}async flush(){}};var AFn=require("fs/promises"),zBp=require("os"),xBp=require("path");var CBp=ui(require("crypto")),C3o=new Uint8Array(256),T3o=C3o.length;function nYs(){return T3o>C3o.length-16&&(CBp.default.randomFillSync(C3o),T3o=0),C3o.slice(T3o,T3o+=16)}var qW=[];for(let e=0;e<256;++e)qW.push((e+256).toString(16).slice(1));function BBp(e,t=0){return qW[e[t+0]]+qW[e[t+1]]+qW[e[t+2]]+qW[e[t+3]]+"-"+qW[e[t+4]]+qW[e[t+5]]+"-"+qW[e[t+6]]+qW[e[t+7]]+"-"+qW[e[t+8]]+qW[e[t+9]]+"-"+qW[e[t+10]]+qW[e[t+11]]+qW[e[t+12]]+qW[e[t+13]]+qW[e[t+14]]+qW[e[t+15]]}var IBp=ui(require("crypto")),aYs={randomUUID:IBp.default.randomUUID};function PbD(e,t,r){if(aYs.randomUUID&&!t&&!e)return aYs.randomUUID();e=e||{};let i=e.random||(e.rng||nYs)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return BBp(i)}var yae=PbD;var jbD="id",wbD=".fern",bEa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new EFn(r),this.userId=t==null?void 0:KVs(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.65.34",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Tu(pl.of((0,zBp.homedir)()),Ra.of(wbD),Ra.of(jbD));await yf(t)||(await(0,AFn.mkdir)((0,xBp.dirname)(t),{recursive:!0}),await(0,AFn.writeFile)(t,yae())),this.persistedDistinctId=(await(0,AFn.readFile)(t)).toString()}return this.persistedDistinctId}};var oYs;async function qFn(){return oYs==null&&(oYs=await SbD()),oYs}async function SbD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new vEa;let r=await XBo();return r!=null?new bEa({token:r,posthogApiKey:e}):await ARn()!=null?new q3o({posthogApiKey:e}):new bEa({token:void 0,posthogApiKey:e})}catch{return new vEa}}function gEa(e,t){return function(){return e.apply(t,arguments)}}var{toString:DbD}=Object.prototype,{getPrototypeOf:sYs}=Object,{iterator:I3o,toStringTag:NBp}=Symbol,z3o=(e=>t=>{let r=DbD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),cWt=e=>(e=e.toLowerCase(),t=>z3o(t)===e),x3o=e=>t=>typeof t===e,{isArray:TFn}=Array,OEa=x3o("undefined");function EbD(e){return e!==null&&!OEa(e)&&e.constructor!==null&&!OEa(e.constructor)&&vae(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var FBp=cWt("ArrayBuffer");function MbD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&FBp(e.buffer),t}var AbD=x3o("string"),vae=x3o("function"),LBp=x3o("number"),R3o=e=>e!==null&&typeof e=="object",qbD=e=>e===!0||e===!1,B3o=e=>{if(z3o(e)!=="object")return!1;let t=sYs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(NBp in e)&&!(I3o in e)},TbD=cWt("Date"),CbD=cWt("File"),BbD=cWt("Blob"),IbD=cWt("FileList"),zbD=e=>R3o(e)&&vae(e.pipe),xbD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||vae(e.append)&&((t=z3o(e))==="formdata"||t==="object"&&vae(e.toString)&&e.toString()==="[object FormData]"))},RbD=cWt("URLSearchParams"),[NbD,FbD,LbD,UbD]=["ReadableStream","Request","Response","Headers"].map(cWt),VbD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function mEa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),TFn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function UBp(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var ZHi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,VBp=e=>!OEa(e)&&e!==ZHi;function uYs(){let{caseless:e}=VBp(this)&&this||{},t={},r=(i,n)=>{let a=e&&UBp(t,n)||n;B3o(t[a])&&B3o(i)?t[a]=uYs(t[a],i):B3o(i)?t[a]=uYs({},i):TFn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&mEa(arguments[i],r);return t}var WbD=(e,t,r,{allOwnKeys:i}={})=>(mEa(t,(n,a)=>{r&&vae(n)?e[a]=gEa(n,r):e[a]=n},{allOwnKeys:i}),e),HbD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),$bD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},GbD=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&sYs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},QbD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},JbD=e=>{if(!e)return null;if(TFn(e))return e;let t=e.length;if(!LBp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},KbD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&sYs(Uint8Array)),YbD=(e,t)=>{let i=(e&&e[I3o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},XbD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},ZbD=cWt("HTMLFormElement"),kbD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),RBp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),e0D=cWt("RegExp"),WBp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};mEa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},t0D=e=>{WBp(e,(t,r)=>{if(vae(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(vae(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},r0D=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return TFn(e)?i(e):i(String(e).split(t)),r},i0D=()=>{},n0D=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function a0D(e){return!!(e&&vae(e.append)&&e[NBp]==="FormData"&&e[I3o])}var o0D=e=>{let t=new Array(10),r=(i,n)=>{if(R3o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=TFn(i)?[]:{};return mEa(i,(u,l)=>{let d=r(u,n+1);!OEa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},u0D=cWt("AsyncFunction"),s0D=e=>e&&(R3o(e)||vae(e))&&vae(e.then)&&vae(e.catch),HBp=((e,t)=>e?setImmediate:t?((r,i)=>(ZHi.addEventListener("message",({source:n,data:a})=>{n===ZHi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),ZHi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",vae(ZHi.postMessage)),c0D=typeof queueMicrotask<"u"?queueMicrotask.bind(ZHi):typeof process<"u"&&process.nextTick||HBp,l0D=e=>e!=null&&vae(e[I3o]),os={isArray:TFn,isArrayBuffer:FBp,isBuffer:EbD,isFormData:xbD,isArrayBufferView:MbD,isString:AbD,isNumber:LBp,isBoolean:qbD,isObject:R3o,isPlainObject:B3o,isReadableStream:NbD,isRequest:FbD,isResponse:LbD,isHeaders:UbD,isUndefined:OEa,isDate:TbD,isFile:CbD,isBlob:BbD,isRegExp:e0D,isFunction:vae,isStream:zbD,isURLSearchParams:RbD,isTypedArray:KbD,isFileList:IbD,forEach:mEa,merge:uYs,extend:WbD,trim:VbD,stripBOM:HbD,inherits:$bD,toFlatObject:GbD,kindOf:z3o,kindOfTest:cWt,endsWith:QbD,toArray:JbD,forEachEntry:YbD,matchAll:XbD,isHTMLForm:ZbD,hasOwnProperty:RBp,hasOwnProp:RBp,reduceDescriptors:WBp,freezeMethods:t0D,toObjectSet:r0D,toCamelCase:kbD,noop:i0D,toFiniteNumber:n0D,findKey:UBp,global:ZHi,isContextDefined:VBp,isSpecCompliantForm:a0D,toJSONObject:o0D,isAsyncFn:u0D,isThenable:s0D,setImmediate:HBp,asap:c0D,isIterable:l0D};function CFn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}os.inherits(CFn,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:os.toJSONObject(this.config),code:this.code,status:this.status}}});var $Bp=CFn.prototype,GBp={};["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=>{GBp[e]={value:e}});Object.defineProperties(CFn,GBp);Object.defineProperty($Bp,"isAxiosError",{value:!0});CFn.from=(e,t,r,i,n,a)=>{let u=Object.create($Bp);return os.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),CFn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Fp=CFn;var QBp=ui(n3o(),1),N3o=QBp.default;function cYs(e){return os.isPlainObject(e)||os.isArray(e)}function KBp(e){return os.endsWith(e,"[]")?e.slice(0,-2):e}function JBp(e,t,r){return e?e.concat(t).map(function(n,a){return n=KBp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function f0D(e){return os.isArray(e)&&!e.some(cYs)}var d0D=os.toFlatObject(os,{},null,function(t){return/^is[A-Z]/.test(t)});function p0D(e,t,r){if(!os.isObject(e))throw new TypeError("target must be an object");t=t||new(N3o||FormData),r=os.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!os.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&os.isSpecCompliantForm(t);if(!os.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(os.isDate(O))return O.toISOString();if(os.isBoolean(O))return O.toString();if(!d&&os.isBlob(O))throw new Fp("Blob is not supported. Use a Buffer instead.");return os.isArrayBuffer(O)||os.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let E=O;if(O&&!w&&typeof O=="object"){if(os.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(os.isArray(O)&&f0D(O)||(os.isFileList(O)||os.endsWith(m,"[]"))&&(E=os.toArray(O)))return m=KBp(m),E.forEach(function(M,D){!(os.isUndefined(M)||M===null)&&t.append(u===!0?JBp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return cYs(O)?!0:(t.append(JBp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(d0D,{defaultVisitor:o,convertValue:s,isVisitable:cYs});function g(O,m){if(!os.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),os.forEach(O,function(E,q){(!(os.isUndefined(E)||E===null)&&n.call(t,E,os.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!os.isObject(e))throw new TypeError("data must be an object");return g(e),t}var kSi=p0D;function YBp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function XBp(e,t){this._pairs=[],e&&kSi(e,this,t)}var ZBp=XBp.prototype;ZBp.append=function(t,r){this._pairs.push([t,r])};ZBp.toString=function(t){let r=t?function(i){return t.call(this,i,YBp)}:YBp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var kBp=XBp;function _0D(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function kHi(e,t,r){if(!t)return e;let i=r&&r.encode||_0D;os.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=os.isURLSearchParams(t)?t.toString():new kBp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var lYs=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){os.forEach(this.handlers,function(i){i!==null&&t(i)})}},fYs=lYs;var BFn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var iIp=ui(require("crypto"),1);var eIp=ui(require("url"),1),tIp=eIp.default.URLSearchParams;var dYs="abcdefghijklmnopqrstuvwxyz",rIp="0123456789",nIp={DIGIT:rIp,ALPHA:dYs,ALPHA_DIGIT:dYs+dYs.toUpperCase()+rIp},h0D=(e=16,t=nIp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);iIp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},aIp={isNode:!0,classes:{URLSearchParams:tIp,FormData:N3o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:nIp,generateString:h0D,protocols:["http","https","file","data"]};var hYs={};Po(hYs,{hasBrowserEnv:()=>_Ys,hasStandardBrowserEnv:()=>y0D,hasStandardBrowserWebWorkerEnv:()=>v0D,navigator:()=>pYs,origin:()=>b0D});var _Ys=typeof window<"u"&&typeof document<"u",pYs=typeof navigator=="object"&&navigator||void 0,y0D=_Ys&&(!pYs||["ReactNative","NativeScript","NS"].indexOf(pYs.product)<0),v0D=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",b0D=_Ys&&window.location.href||"http://localhost";var oA={...hYs,...aIp};function yYs(e,t){return kSi(e,new oA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return oA.isNode&&os.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function g0D(e){return os.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function O0D(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function m0D(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&os.isArray(n)?n.length:u,d?(os.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!os.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&os.isArray(n[u])&&(n[u]=O0D(n[u])),!l)}if(os.isFormData(e)&&os.isFunction(e.entries)){let r={};return os.forEachEntry(e,(i,n)=>{t(g0D(i),n,r,0)}),r}return null}var F3o=m0D;function P0D(e,t,r){if(os.isString(e))try{return(t||JSON.parse)(e),os.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var vYs={transitional:BFn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=os.isObject(t);if(a&&os.isHTMLForm(t)&&(t=new FormData(t)),os.isFormData(t))return n?JSON.stringify(F3o(t)):t;if(os.isArrayBuffer(t)||os.isBuffer(t)||os.isStream(t)||os.isFile(t)||os.isBlob(t)||os.isReadableStream(t))return t;if(os.isArrayBufferView(t))return t.buffer;if(os.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return yYs(t,this.formSerializer).toString();if((l=os.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return kSi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),P0D(t)):t}],transformResponse:[function(t){let r=this.transitional||vYs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(os.isResponse(t)||os.isReadableStream(t))return t;if(t&&os.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Fp.from(l,Fp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:oA.classes.FormData,Blob:oA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};os.forEach(["delete","get","head","post","put","patch"],e=>{vYs.headers[e]={}});var IFn=vYs;var j0D=os.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"]),oIp=e=>{let t={},r,i,n;return e&&e.split(`
1716
1716
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&j0D[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var uIp=Symbol("internals");function PEa(e){return e&&String(e).trim().toLowerCase()}function L3o(e){return e===!1||e==null?e:os.isArray(e)?e.map(L3o):String(e)}function w0D(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}var S0D=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function bYs(e,t,r,i,n){if(os.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!os.isString(t)){if(os.isString(i))return t.indexOf(i)!==-1;if(os.isRegExp(i))return i.test(t)}}function D0D(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function E0D(e,t){let r=os.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,u){return this[i].call(this,t,n,a,u)},configurable:!0})})}var zFn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=PEa(d);if(!o)throw new Error("header name must be a non-empty string");let c=os.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=L3o(l))}let u=(l,d)=>os.forEach(l,(s,o)=>a(s,o,d));if(os.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(os.isString(t)&&(t=t.trim())&&!S0D(t))u(oIp(t),r);else if(os.isObject(t)&&os.isIterable(t)){let l={},d,s;for(let o of t){if(!os.isArray(o))throw TypeError("Object iterator must return a key-value pair");l[s=o[0]]=(d=l[s])?os.isArray(d)?[...d,o[1]]:[d,o[1]]:o[1]}u(l,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=PEa(t),t){let i=os.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return w0D(n);if(os.isFunction(r))return r.call(this,n,i);if(os.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=PEa(t),t){let i=os.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||bYs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=PEa(u),u){let l=os.findKey(i,u);l&&(!r||bYs(i,i[l],l,r))&&(delete i[l],n=!0)}}return os.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||bYs(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return os.forEach(this,(n,a)=>{let u=os.findKey(i,a);if(u){r[u]=L3o(n),delete r[a];return}let l=t?D0D(a):String(a).trim();l!==a&&delete r[a],r[l]=L3o(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return os.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&os.isArray(i)?i.join(", "):i)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
1717
1717
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let i=new this(t);return r.forEach(n=>i.set(n)),i}static accessor(t){let i=(this[uIp]=this[uIp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=PEa(u);i[l]||(E0D(n,u),i[l]=!0)}return os.isArray(t)?t.forEach(a):a(t),this}};zFn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);os.reduceDescriptors(zFn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});os.freezeMethods(zFn);var oR=zFn;function jEa(e,t){let r=this||IFn,i=t||r,n=oR.from(i.headers),a=i.data;return os.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function wEa(e){return!!(e&&e.__CANCEL__)}function sIp(e,t,r){Fp.call(this,e??"canceled",Fp.ERR_CANCELED,t,r),this.name="CanceledError"}os.inherits(sIp,Fp,{__CANCEL__:!0});var HEe=sIp;function Ktr(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Fp("Request failed with status code "+r.status,[Fp.ERR_BAD_REQUEST,Fp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function gYs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function OYs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function e$i(e,t,r){let i=!gYs(t);return e&&(i||r==!1)?OYs(e,t):t}var wIp=ui(oEa(),1),SIp=ui(require("http"),1),DIp=ui(require("https"),1),EIp=ui(require("util"),1),MIp=ui(OKs(),1),_fi=ui(require("zlib"),1);var t$i="1.10.0";function SEa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var M0D=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function mYs(e,t,r){let i=r&&r.Blob||oA.classes.Blob,n=SEa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=M0D.exec(e);if(!a)throw new Fp("Invalid URL",Fp.ERR_INVALID_URL);let u=a[1],l=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),l?"base64":"utf8");if(t){if(!i)throw new Fp("Blob is not supported",Fp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Fp("Unsupported protocol "+n,Fp.ERR_NOT_SUPPORT)}var i$i=ui(require("stream"),1);var cIp=ui(require("stream"),1);var PYs=Symbol("internals"),jYs=class extends cIp.default.Transform{constructor(t){t=os.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!os.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[PYs]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[PYs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[PYs],a=n.maxRate,u=this.readableHighWaterMark,l=n.timeWindow,d=1e3/l,s=a/d,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,c=(g,O)=>{let m=Buffer.byteLength(g);n.bytesSeen+=m,n.bytes+=m,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(g)?process.nextTick(O):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(O)}},b=(g,O)=>{let m=Buffer.byteLength(g),w=null,E=u,q,M=0;if(a){let D=Date.now();(!n.ts||(M=D-n.ts)>=l)&&(n.ts=D,q=s-n.bytes,n.bytes=q<0?-q:0,M=0),q=s-n.bytes}if(a){if(q<=0)return setTimeout(()=>{O(null,g)},l-M);q<E&&(E=q)}E&&m>E&&m-E>o&&(w=g.subarray(E),g=g.subarray(0,E)),c(g,w?()=>{process.nextTick(O,null,w)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},wYs=jYs;var AIp=require("events");var fIp=ui(require("util"),1),dIp=require("stream");var{asyncIterator:lIp}=Symbol,A0D=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[lIp]?yield*e[lIp]():yield e},U3o=A0D;var q0D=oA.ALPHABET.ALPHA_DIGIT+"-_",DEa=typeof TextEncoder=="function"?new TextEncoder:new fIp.default.TextEncoder,r$i=`\r
1718
1718
  `,T0D=DEa.encode(r$i),C0D=2,SYs=class{constructor(t,r){let{escapeName:i}=this.constructor,n=os.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${r$i}`;n?r=DEa.encode(String(r).replace(/\r?\n|\r\n?/g,r$i)):a+=`Content-Type: ${r.type||"application/octet-stream"}${r$i}`,this.headers=DEa.encode(a+r$i),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+C0D,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;os.isTypedArray(t)?yield t:yield*U3o(t),yield T0D}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},B0D=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+oA.generateString(n,q0D)}=r||{};if(!os.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=DEa.encode("--"+a+r$i),l=DEa.encode("--"+a+"--"+r$i),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new SYs(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=os.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),dIp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},pIp=B0D;var _Ip=ui(require("stream"),1),DYs=class extends _Ip.default.Transform{__transform(t,r,i){this.push(t),i()}_transform(t,r,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let n=Buffer.alloc(2);n[0]=120,n[1]=156,this.push(n,r)}this.__transform(t,r,i)}},hIp=DYs;var I0D=(e,t)=>os.isAsyncFn(e)?function(...r){let i=r.pop();e.apply(this,r).then(n=>{try{t?i(null,...t(n)):i(null,n)}catch(a){i(a)}},i)}:e,yIp=I0D;function z0D(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,u;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),o=i[a];u||(u=s),r[n]=d,i[n]=s;let c=a,b=0;for(;c!==n;)b+=r[c++],c=c%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-u<t)return;let g=o&&s-o;return g?Math.round(b*1e3/g):void 0}}var vIp=z0D;function x0D(e,t){let r=0,i=1e3/t,n,a,u=(s,o=Date.now())=>{r=o,n=null,a&&(clearTimeout(a),a=null),e.apply(null,s)};return[(...s)=>{let o=Date.now(),c=o-r;c>=i?u(s,o):(n=s,a||(a=setTimeout(()=>{a=null,u(n)},i-c)))},()=>n&&u(n)]}var bIp=x0D;var pfi=(e,t,r=3)=>{let i=0,n=vIp(50,250);return bIp(a=>{let u=a.loaded,l=a.lengthComputable?a.total:void 0,d=u-i,s=n(d),o=u<=l;i=u;let c={loaded:u,total:l,progress:l?u/l:void 0,bytes:d,rate:s||void 0,estimated:s&&l&&o?(l-u)/s:void 0,event:a,lengthComputable:l!=null,[t?"download":"upload"]:!0};e(c)},r)},xFn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},RFn=e=>(...t)=>os.asap(()=>e(...t));var gIp={flush:_fi.default.constants.Z_SYNC_FLUSH,finishFlush:_fi.default.constants.Z_SYNC_FLUSH},R0D={flush:_fi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:_fi.default.constants.BROTLI_OPERATION_FLUSH},OIp=os.isFunction(_fi.default.createBrotliDecompress),{http:N0D,https:F0D}=MIp.default,L0D=/https:?/,mIp=oA.protocols.map(e=>e+":"),PIp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function U0D(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function qIp(e,t,r){let i=t;if(!i&&i!==!1){let n=wIp.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){qIp(a,t,a.href)}}var V0D=typeof process<"u"&&os.kindOf(process)==="process",W0D=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},u=d=>{a(d),t(d)},l=d=>{a(d,!0),r(d)};e(u,l,d=>i=d).catch(l)}),H0D=({address:e,family:t})=>{if(!os.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},jIp=(e,t)=>H0D(os.isObject(e)?e:{address:e,family:t}),TIp=V0D&&function(t){return W0D(async function(i,n,a){let{data:u,lookup:l,family:d}=t,{responseType:s,responseEncoding:o}=t,c=t.method.toUpperCase(),b,g=!1,O;if(l){let Oe=yIp(l,Ue=>os.isArray(Ue)?Ue:[Ue]);l=(Ue,bt,De)=>{Oe(Ue,bt,(Te,xt,Pe)=>{if(Te)return De(Te);let ot=os.isArray(xt)?xt.map(at=>jIp(at)):[jIp(xt,Pe)];bt.all?De(Te,ot):De(Te,ot[0].address,ot[0].family)})}}let m=new AIp.EventEmitter,w=()=>{t.cancelToken&&t.cancelToken.unsubscribe(E),t.signal&&t.signal.removeEventListener("abort",E),m.removeAllListeners()};a((Oe,Ue)=>{b=!0,Ue&&(g=!0,w())});function E(Oe){m.emit("abort",!Oe||Oe.type?new HEe(null,t,O):Oe)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(E),t.signal&&(t.signal.aborted?E():t.signal.addEventListener("abort",E)));let q=e$i(t.baseURL,t.url,t.allowAbsoluteUrls),M=new URL(q,oA.hasBrowserEnv?oA.origin:void 0),D=M.protocol||mIp[0];if(D==="data:"){let Oe;if(c!=="GET")return Ktr(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{Oe=mYs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Ue){throw Fp.from(Ue,Fp.ERR_BAD_REQUEST,t)}return s==="text"?(Oe=Oe.toString(o),(!o||o==="utf8")&&(Oe=os.stripBOM(Oe))):s==="stream"&&(Oe=i$i.default.Readable.from(Oe)),Ktr(i,n,{data:Oe,status:200,statusText:"OK",headers:new oR,config:t})}if(mIp.indexOf(D)===-1)return n(new Fp("Unsupported protocol "+D,Fp.ERR_BAD_REQUEST,t));let C=oR.from(t.headers).normalize();C.set("User-Agent","axios/"+t$i,!1);let{onUploadProgress:x,onDownloadProgress:G}=t,I=t.maxRate,F,V;if(os.isSpecCompliantForm(u)){let Oe=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=pIp(u,Ue=>{C.set(Ue)},{tag:`axios-${t$i}-boundary`,boundary:Oe&&Oe[1]||void 0})}else if(os.isFormData(u)&&os.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let Oe=await EIp.default.promisify(u.getLength).call(u);Number.isFinite(Oe)&&Oe>=0&&C.setContentLength(Oe)}catch{}}else if(os.isBlob(u)||os.isFile(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=i$i.default.Readable.from(U3o(u));else if(u&&!os.isStream(u)){if(!Buffer.isBuffer(u))if(os.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(os.isString(u))u=Buffer.from(u,"utf-8");else return n(new Fp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Fp.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Fp("Request body larger than maxBodyLength limit",Fp.ERR_BAD_REQUEST,t))}let K=os.toFiniteNumber(C.getContentLength());os.isArray(I)?(F=I[0],V=I[1]):F=V=I,u&&(x||F)&&(os.isStream(u)||(u=i$i.default.Readable.from(u,{objectMode:!1})),u=i$i.default.pipeline([u,new wYs({maxRate:os.toFiniteNumber(F)})],os.noop),x&&u.on("progress",PIp(u,xFn(K,pfi(RFn(x),!1,3)))));let Y;if(t.auth){let Oe=t.auth.username||"",Ue=t.auth.password||"";Y=Oe+":"+Ue}if(!Y&&M.username){let Oe=M.username,Ue=M.password;Y=Oe+":"+Ue}Y&&C.delete("authorization");let Z;try{Z=kHi(M.pathname+M.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(Oe){let Ue=new Error(Oe.message);return Ue.config=t,Ue.url=t.url,Ue.exists=!0,n(Ue)}C.set("Accept-Encoding","gzip, compress, deflate"+(OIp?", br":""),!1);let oe={path:Z,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:Y,protocol:D,family:d,beforeRedirect:U0D,beforeRedirects:{}};!os.isUndefined(l)&&(oe.lookup=l),t.socketPath?oe.socketPath=t.socketPath:(oe.hostname=M.hostname.startsWith("[")?M.hostname.slice(1,-1):M.hostname,oe.port=M.port,qIp(oe,t.proxy,D+"//"+M.hostname+(M.port?":"+M.port:"")+oe.path));let pe,de=L0D.test(oe.protocol);if(oe.agent=de?t.httpsAgent:t.httpAgent,t.transport?pe=t.transport:t.maxRedirects===0?pe=de?DIp.default:SIp.default:(t.maxRedirects&&(oe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(oe.beforeRedirects.config=t.beforeRedirect),pe=de?F0D:N0D),t.maxBodyLength>-1?oe.maxBodyLength=t.maxBodyLength:oe.maxBodyLength=1/0,t.insecureHTTPParser&&(oe.insecureHTTPParser=t.insecureHTTPParser),O=pe.request(oe,function(Ue){if(O.destroyed)return;let bt=[Ue],De=+Ue.headers["content-length"];if(G||V){let at=new wYs({maxRate:os.toFiniteNumber(V)});G&&at.on("progress",PIp(at,xFn(De,pfi(RFn(G),!0,3)))),bt.push(at)}let Te=Ue,xt=Ue.req||O;if(t.decompress!==!1&&Ue.headers["content-encoding"])switch((c==="HEAD"||Ue.statusCode===204)&&delete Ue.headers["content-encoding"],(Ue.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":bt.push(_fi.default.createUnzip(gIp)),delete Ue.headers["content-encoding"];break;case"deflate":bt.push(new hIp),bt.push(_fi.default.createUnzip(gIp)),delete Ue.headers["content-encoding"];break;case"br":OIp&&(bt.push(_fi.default.createBrotliDecompress(R0D)),delete Ue.headers["content-encoding"])}Te=bt.length>1?i$i.default.pipeline(bt,os.noop):bt[0];let Pe=i$i.default.finished(Te,()=>{Pe(),w()}),ot={status:Ue.statusCode,statusText:Ue.statusMessage,headers:new oR(Ue.headers),config:t,request:xt};if(s==="stream")ot.data=Te,Ktr(i,n,ot);else{let at=[],me=0;Te.on("data",function(wt){at.push(wt),me+=wt.length,t.maxContentLength>-1&&me>t.maxContentLength&&(g=!0,Te.destroy(),n(new Fp("maxContentLength size of "+t.maxContentLength+" exceeded",Fp.ERR_BAD_RESPONSE,t,xt)))}),Te.on("aborted",function(){if(g)return;let wt=new Fp("stream has been aborted",Fp.ERR_BAD_RESPONSE,t,xt);Te.destroy(wt),n(wt)}),Te.on("error",function(wt){O.destroyed||n(Fp.from(wt,null,t,xt))}),Te.on("end",function(){try{let wt=at.length===1?at[0]:Buffer.concat(at);s!=="arraybuffer"&&(wt=wt.toString(o),(!o||o==="utf8")&&(wt=os.stripBOM(wt))),ot.data=wt}catch(wt){return n(Fp.from(wt,null,t,ot.request,ot))}Ktr(i,n,ot)})}m.once("abort",at=>{Te.destroyed||(Te.emit("error",at),Te.destroy())})}),m.once("abort",Oe=>{n(Oe),O.destroy(Oe)}),O.on("error",function(Ue){n(Fp.from(Ue,null,t,O))}),O.on("socket",function(Ue){Ue.setKeepAlive(!0,1e3*60)}),t.timeout){let Oe=parseInt(t.timeout,10);if(Number.isNaN(Oe)){n(new Fp("error trying to parse `config.timeout` to int",Fp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(Oe,function(){if(b)return;let bt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||BFn;t.timeoutErrorMessage&&(bt=t.timeoutErrorMessage),n(new Fp(bt,De.clarifyTimeoutError?Fp.ETIMEDOUT:Fp.ECONNABORTED,t,O)),E()})}if(os.isStream(u)){let Oe=!1,Ue=!1;u.on("end",()=>{Oe=!0}),u.once("error",bt=>{Ue=!0,O.destroy(bt)}),u.on("close",()=>{!Oe&&!Ue&&E(new HEe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var CIp=oA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,oA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(oA.origin),oA.navigator&&/(msie|trident)/i.test(oA.navigator.userAgent)):()=>!0;var BIp=oA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];os.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),os.isString(i)&&u.push("path="+i),os.isString(n)&&u.push("domain="+n),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 IIp=e=>e instanceof oR?{...e}:e;function lWt(e,t){t=t||{};let r={};function i(s,o,c,b){return os.isPlainObject(s)&&os.isPlainObject(o)?os.merge.call({caseless:b},s,o):os.isPlainObject(o)?os.merge({},o):os.isArray(o)?o.slice():o}function n(s,o,c,b){if(os.isUndefined(o)){if(!os.isUndefined(s))return i(void 0,s,c,b)}else return i(s,o,c,b)}function a(s,o){if(!os.isUndefined(o))return i(void 0,o)}function u(s,o){if(os.isUndefined(o)){if(!os.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function l(s,o,c){if(c in t)return i(s,o);if(c in e)return i(void 0,s)}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:l,headers:(s,o,c)=>n(IIp(s),IIp(o),c,!0)};return os.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);os.isUndefined(b)&&c!==l||(r[o]=b)}),r}var V3o=e=>{let t=lWt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=oR.from(u),t.url=kHi(e$i(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),l&&u.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let d;if(os.isFormData(r)){if(oA.hasStandardBrowserEnv||oA.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[s,...o]=d?d.split(";").map(c=>c.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(oA.hasStandardBrowserEnv&&(i&&os.isFunction(i)&&(i=i(t)),i||i!==!1&&CIp(t.url))){let s=n&&a&&BIp.read(a);s&&u.set(n,s)}return t};var $0D=typeof XMLHttpRequest<"u",zIp=$0D&&function(e){return new Promise(function(r,i){let n=V3o(e),a=n.data,u=oR.from(n.headers).normalize(),{responseType:l,onUploadProgress:d,onDownloadProgress:s}=n,o,c,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let w=new XMLHttpRequest;w.open(n.method.toUpperCase(),n.url,!0),w.timeout=n.timeout;function E(){if(!w)return;let M=oR.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:M,config:e,request:w};Ktr(function(G){r(G),m()},function(G){i(G),m()},C),w=null}"onloadend"in w?w.onloadend=E:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(E)},w.onabort=function(){w&&(i(new Fp("Request aborted",Fp.ECONNABORTED,e,w)),w=null)},w.onerror=function(){i(new Fp("Network Error",Fp.ERR_NETWORK,e,w)),w=null},w.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||BFn;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Fp(D,C.clarifyTimeoutError?Fp.ETIMEDOUT:Fp.ECONNABORTED,e,w)),w=null},a===void 0&&u.setContentType(null),"setRequestHeader"in w&&os.forEach(u.toJSON(),function(D,C){w.setRequestHeader(C,D)}),os.isUndefined(n.withCredentials)||(w.withCredentials=!!n.withCredentials),l&&l!=="json"&&(w.responseType=n.responseType),s&&([b,O]=pfi(s,!0),w.addEventListener("progress",b)),d&&w.upload&&([c,g]=pfi(d),w.upload.addEventListener("progress",c),w.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=M=>{w&&(i(!M||M.type?new HEe(null,e,w):M),w.abort(),w=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=SEa(n.url);if(q&&oA.protocols.indexOf(q)===-1){i(new Fp("Unsupported protocol "+q+":",Fp.ERR_BAD_REQUEST,e));return}w.send(a||null)})};var G0D=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,l();let o=s instanceof Error?s:this.reason;i.abort(o instanceof Fp?o:new HEe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Fp(`timeout ${t} of ms exceeded`,Fp.ETIMEDOUT))},t),l=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>os.asap(l),d}},xIp=G0D;var Q0D=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let i=0,n;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},J0D=async function*(e,t){for await(let r of K0D(e))yield*Q0D(r,t)},K0D=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)break;yield i}}finally{await t.cancel()}},EYs=(e,t,r,i)=>{let n=J0D(e,t),a=0,u,l=d=>{u||(u=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:o}=await n.next();if(s){l(),d.close();return}let c=o.byteLength;if(r){let b=a+=c;r(b)}d.enqueue(new Uint8Array(o))}catch(s){throw l(s),s}},cancel(d){return l(d),n.return()}},{highWaterMark:2})};var H3o=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",NIp=H3o&&typeof ReadableStream=="function",Y0D=H3o&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),FIp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},X0D=NIp&&FIp(()=>{let e=!1,t=new Request(oA.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),RIp=64*1024,MYs=NIp&&FIp(()=>os.isReadableStream(new Response("").body)),W3o={stream:MYs&&(e=>e.body)};H3o&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!W3o[t]&&(W3o[t]=os.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Fp(`Response type '${t}' is not supported`,Fp.ERR_NOT_SUPPORT,i)})})})(new Response);var Z0D=async e=>{if(e==null)return 0;if(os.isBlob(e))return e.size;if(os.isSpecCompliantForm(e))return(await new Request(oA.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(os.isArrayBufferView(e)||os.isArrayBuffer(e))return e.byteLength;if(os.isURLSearchParams(e)&&(e=e+""),os.isString(e))return(await Y0D(e)).byteLength},k0D=async(e,t)=>{let r=os.toFiniteNumber(e.getContentLength());return r??Z0D(t)},LIp=H3o&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:l,onUploadProgress:d,responseType:s,headers:o,withCredentials:c="same-origin",fetchOptions:b}=V3o(e);s=s?(s+"").toLowerCase():"text";let g=xIp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),w;try{if(d&&X0D&&r!=="get"&&r!=="head"&&(w=await k0D(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),x;if(os.isFormData(i)&&(x=C.headers.get("content-type"))&&o.setContentType(x),C.body){let[G,I]=xFn(w,pfi(RFn(d)));i=EYs(C.body,RIp,G,I)}}os.isString(c)||(c=c?"include":"omit");let E="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:E?c:void 0});let q=await fetch(O,b),M=MYs&&(s==="stream"||s==="response");if(MYs&&(l||M&&m)){let C={};["status","statusText","headers"].forEach(F=>{C[F]=q[F]});let x=os.toFiniteNumber(q.headers.get("content-length")),[G,I]=l&&xFn(x,pfi(RFn(l),!0))||[];q=new Response(EYs(q.body,RIp,G,()=>{I&&I(),m&&m()}),C)}s=s||"text";let D=await W3o[os.findKey(W3o,s)||"text"](q,e);return!M&&m&&m(),await new Promise((C,x)=>{Ktr(C,x,{data:D,headers:oR.from(q.headers),status:q.status,statusText:q.statusText,config:e,request:O})})}catch(E){throw m&&m(),E&&E.name==="TypeError"&&/Load failed|fetch/i.test(E.message)?Object.assign(new Fp("Network Error",Fp.ERR_NETWORK,e,O),{cause:E.cause||E}):Fp.from(E,E&&E.code,e,O)}});var AYs={http:TIp,xhr:zIp,fetch:LIp};os.forEach(AYs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var UIp=e=>`- ${e}`,egD=e=>os.isFunction(e)||e===null||e===!1,$3o={getAdapter:e=>{e=os.isArray(e)?e:[e];let{length:t}=e,r,i,n={};for(let a=0;a<t;a++){r=e[a];let u;if(i=r,!egD(r)&&(i=AYs[(u=String(r)).toLowerCase()],i===void 0))throw new Fp(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([l,d])=>`adapter ${l} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1954,7 +1954,7 @@ ${M}${q}${D}${CKp.default.cursorHide}`});var dCa=ui(Rwi(),1);function Cuc(e,t){i
1954
1954
  Run ${Ss.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1955
1955
  Run ${Ss.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),FFn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function Wuc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!rYp(e))return;let n=t??"",a=e.filter(l=>l.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((l,d)=>l.generatorName.localeCompare(d.generatorName)||l.currentVersion.localeCompare(d.currentVersion));for(let l of u)n+=`
1956
1956
  ${await bVD(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Ss.dim(l.currentVersion)+Ss.reset(" \u2192 ")+Ss.green(l.latestVersion);return n+=`
1957
- `,i?FFn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function bVD(e){let r=await new tYp.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 gVD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await nYp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=xwi(o.name,c),g=await rkt({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await nYp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=xwi(s.name,o),b=await rkt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function nYp({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await xVt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function aYp(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=qae(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function DUo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await gVD({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...aYp(s,d,t.logger));else u.push(...aYp(l.versions,void 0,t.logger))}return u}var OCa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var q4n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Huc=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),oYp=typeof globalThis.AbortController=="function",uYp=typeof globalThis.ReadableStream=="function",sYp=typeof globalThis.FormData=="function",EUo=["get","post","put","patch","head","delete"],OVD=()=>{};OVD();var cYp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},MUo=2147483647,lYp=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,AUo=Symbol("stop"),fYp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},dYp={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 mVD=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=lYp,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},pYp=(e,t)=>{let r=Number(e.headers.get("content-length"))||0,i=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(n){let a=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function u(){let{done:l,value:d}=await a.read();if(l){n.close();return}if(t){i+=d.byteLength;let s=r===0?0:i/r;t({percent:s,transferredBytes:i,totalBytes:r},d)}n.enqueue(d),await u()}await u()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},_Yp=(e,t)=>{let r=mVD(e.body),i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(n){let a=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function u(){let{done:l,value:d}=await a.read();if(l){t&&t({percent:1,transferredBytes:i,totalBytes:Math.max(r,i)},new Uint8Array),n.close();return}i+=d.byteLength;let s=r===0?0:i/r;(r<i||s===1)&&(s=.99),t&&t({percent:Number(s.toFixed(2)),transferredBytes:i,totalBytes:r},d),n.enqueue(d),await u()}await u()}})})};var T4n=e=>e!==null&&typeof e=="object";var mCa=(...e)=>{for(let t of e)if((!T4n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Quc({},...e)},$uc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function qUo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Quc(e[r]??[],t[r]??[])}var Guc=(e={},t={})=>({beforeRequest:qUo(e,t,"beforeRequest"),beforeRetry:qUo(e,t,"beforeRetry"),afterResponse:qUo(e,t,"afterResponse"),beforeError:qUo(e,t,"beforeError")}),Quc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(T4n(n)){for(let[a,u]of Object.entries(n))T4n(u)&&a in t&&(u=Quc(t[a],u)),t={...t,[a]:u};T4n(n.hooks)&&(i=Guc(i,n.hooks),t.hooks=i),T4n(n.headers)&&(r=$uc(r,n.headers),t.headers=r)}return t};var yYp=e=>EUo.includes(e)?e.toUpperCase():e,PVD=["get","put","head","delete","options","trace"],jVD=[408,413,429,500,502,503,504],wVD=[413,429,503],hYp={limit:2,methods:PVD,statusCodes:jVD,afterStatusCodes:wVD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},vYp=(e={})=>{if(typeof e=="number")return{...hYp,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{...hYp,...e}};async function Juc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new q4n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Kuc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var bYp=(e,t)=>{let r={};for(let i in t)!(i in dYp)&&!(i in fYp)&&!(i in e)&&(r[i]=t[i]);return r};var PCa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>MUo)throw new RangeError(`The \`timeout\` option cannot be greater than ${MUo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new OCa(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!uYp)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return pYp(l.clone(),i._options.onDownloadProgress)}return l},u=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{i.request.bodyUsed||await i.request.body?.cancel()});for(let[l,d]of Object.entries(cYp))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(l==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:$uc(this._input.headers,r.headers),hooks:Guc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:yYp(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:vYp(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(oYp){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(Huc&&(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 n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(sYp&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!Huc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=_Yp(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof q4n)throw t;if(t instanceof OCa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),MUo);if(this._retryCount<1)throw r;await Kuc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===AUo)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=bYp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Juc(r,t,this.abortController,this._options)}};var Yuc=e=>{let t=(r,i)=>PCa.create(r,mCa(e,i));for(let r of EUo)t[r]=(i,n)=>PCa.create(i,mCa(e,n,{method:r}));return t.create=r=>Yuc(mCa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Yuc(mCa(e,r))),t.stop=AUo,t},SVD=Yuc(),gYp=SVD;var VYp=ui(UYp(),1);function tsc(e){let t=(0,VYp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var xXp=ui(zXp(),1),RXp=ui(Rwi(),1),_sc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},hsc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function ysc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??tsc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,xXp.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,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await gYp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new _sc(e):c}if(t.allVersions)return s;let o=new hsc(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=RXp.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function MCa(e,t){let{version:r}=await ysc(e.toLowerCase(),t);return r}async function MEi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:MCa(e.packageName,{version:t?"prerelease":"latest"})}var NXp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],VUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Yv.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new SUo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.65.33"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ss.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new d9}failWithoutThrowing(t,r){this.didSucceed=!1,mUo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await qFn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await iYp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1957
+ `,i?FFn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function bVD(e){let r=await new tYp.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 gVD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await nYp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=xwi(o.name,c),g=await rkt({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await nYp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=xwi(s.name,o),b=await rkt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function nYp({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await xVt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function aYp(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=qae(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function DUo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await gVD({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...aYp(s,d,t.logger));else u.push(...aYp(l.versions,void 0,t.logger))}return u}var OCa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var q4n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Huc=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),oYp=typeof globalThis.AbortController=="function",uYp=typeof globalThis.ReadableStream=="function",sYp=typeof globalThis.FormData=="function",EUo=["get","post","put","patch","head","delete"],OVD=()=>{};OVD();var cYp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},MUo=2147483647,lYp=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,AUo=Symbol("stop"),fYp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},dYp={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 mVD=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=lYp,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},pYp=(e,t)=>{let r=Number(e.headers.get("content-length"))||0,i=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(n){let a=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function u(){let{done:l,value:d}=await a.read();if(l){n.close();return}if(t){i+=d.byteLength;let s=r===0?0:i/r;t({percent:s,transferredBytes:i,totalBytes:r},d)}n.enqueue(d),await u()}await u()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},_Yp=(e,t)=>{let r=mVD(e.body),i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(n){let a=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function u(){let{done:l,value:d}=await a.read();if(l){t&&t({percent:1,transferredBytes:i,totalBytes:Math.max(r,i)},new Uint8Array),n.close();return}i+=d.byteLength;let s=r===0?0:i/r;(r<i||s===1)&&(s=.99),t&&t({percent:Number(s.toFixed(2)),transferredBytes:i,totalBytes:r},d),n.enqueue(d),await u()}await u()}})})};var T4n=e=>e!==null&&typeof e=="object";var mCa=(...e)=>{for(let t of e)if((!T4n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Quc({},...e)},$uc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function qUo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Quc(e[r]??[],t[r]??[])}var Guc=(e={},t={})=>({beforeRequest:qUo(e,t,"beforeRequest"),beforeRetry:qUo(e,t,"beforeRetry"),afterResponse:qUo(e,t,"afterResponse"),beforeError:qUo(e,t,"beforeError")}),Quc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(T4n(n)){for(let[a,u]of Object.entries(n))T4n(u)&&a in t&&(u=Quc(t[a],u)),t={...t,[a]:u};T4n(n.hooks)&&(i=Guc(i,n.hooks),t.hooks=i),T4n(n.headers)&&(r=$uc(r,n.headers),t.headers=r)}return t};var yYp=e=>EUo.includes(e)?e.toUpperCase():e,PVD=["get","put","head","delete","options","trace"],jVD=[408,413,429,500,502,503,504],wVD=[413,429,503],hYp={limit:2,methods:PVD,statusCodes:jVD,afterStatusCodes:wVD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},vYp=(e={})=>{if(typeof e=="number")return{...hYp,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{...hYp,...e}};async function Juc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new q4n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Kuc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var bYp=(e,t)=>{let r={};for(let i in t)!(i in dYp)&&!(i in fYp)&&!(i in e)&&(r[i]=t[i]);return r};var PCa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>MUo)throw new RangeError(`The \`timeout\` option cannot be greater than ${MUo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new OCa(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!uYp)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return pYp(l.clone(),i._options.onDownloadProgress)}return l},u=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{i.request.bodyUsed||await i.request.body?.cancel()});for(let[l,d]of Object.entries(cYp))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(l==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:$uc(this._input.headers,r.headers),hooks:Guc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:yYp(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:vYp(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(oYp){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(Huc&&(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 n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(sYp&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!Huc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=_Yp(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof q4n)throw t;if(t instanceof OCa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),MUo);if(this._retryCount<1)throw r;await Kuc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===AUo)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=bYp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Juc(r,t,this.abortController,this._options)}};var Yuc=e=>{let t=(r,i)=>PCa.create(r,mCa(e,i));for(let r of EUo)t[r]=(i,n)=>PCa.create(i,mCa(e,n,{method:r}));return t.create=r=>Yuc(mCa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Yuc(mCa(e,r))),t.stop=AUo,t},SVD=Yuc(),gYp=SVD;var VYp=ui(UYp(),1);function tsc(e){let t=(0,VYp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var xXp=ui(zXp(),1),RXp=ui(Rwi(),1),_sc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},hsc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function ysc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??tsc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,xXp.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,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await gYp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new _sc(e):c}if(t.allVersions)return s;let o=new hsc(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=RXp.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function MCa(e,t){let{version:r}=await ysc(e.toLowerCase(),t);return r}async function MEi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:MCa(e.packageName,{version:t?"prerelease":"latest"})}var NXp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],VUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Yv.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new SUo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.65.34"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ss.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new d9}failWithoutThrowing(t,r){this.didSucceed=!1,mUo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await qFn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await iYp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1958
1958
  `)||(r+=`
1959
1959
  `),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=EIs(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new pCa(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new d9}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await qFn()).sendEvent(t)}logger=yXt((t,...r)=>this.log(t,...r));stderr=yXt((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=FXp(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?FXp(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=NXp[this.numTasks++%NXp.length],u=Ss.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===AB.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let i=t.filter(n=>Qji.indexOf(n.level)>=Qji.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Yv.Debug,stderr:r})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await MEi({cliEnvironment:this.environment,includePreReleases:t}),i=qae(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await DUo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await Euc({message:t,default:r})}async getInput(t){return await Muc({message:t.message,default:t.default})}};function FXp(e){return`[${e}]:`}var pg_=require("fs/promises");function tFe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Ss.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Ss.dim(r)),i.join(`
1960
1960
  `)}var ___=require("fs/promises");var HWt=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var fMe=class extends HWt{definition;sources;type="fern";constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var ACa=class{context;constructor(t){this.context=t}};var WUo=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?Zh.of(`${n}${eVt}${u}`):Zh.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${eVt}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(eVt))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Zh.of(t[0])]??={};let[r,...i]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(i)}};var pQi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new WUo,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return gkt(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let i of Object.values(this.rootApiFile["auth-schemes"]))LXp(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(LXp(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}getGlobalHeaders(){return this.rootApiFile.headers??{}}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??p_((fxe(r)+"/"+XUi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Zh.of(HF))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=Lgo(fxe(xBn.of(`/${t}`)),xBn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=Lgo(fxe(xBn.of(`/${t}`)),xBn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===Zh.of(HF))return;let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(l=>P2(l,i))??!1)||a.examples?.push(i)}addEndpoint(t,{name:r,schema:i,source:n}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),n!=null&&(a.service.source=n),a.service.endpoints[r]=i}addWebhook(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.webhooks==null&&(n.webhooks={}),n.webhooks[r]=i}addChannel(t,{channel:r}){let i=this.getOrCreateFile(t);i.channel=r;let n=this.basePath;n!=null&&(i.channel.path=TN(n,r.path))}addChannelExample(t,{example:r}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.examples==null&&(i.channel.examples=[]),i.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:i}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.messages[r]=i}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([n,a])=>[n,{...a,path:TN(r,a.path)}]))});for(let n of Object.values(t))n.service!=null&&(n.service={...n.service,endpoints:Object.fromEntries(Object.entries(n.service.endpoints).map(([a,u])=>[a,{...u,path:TN(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===L1?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function LXp(e){return e?.header!=null}var KQ={openapi:e=>({...e,type:"openapi",_visit:function(t){return KQ._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return KQ._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var N4n={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return N4n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var K9={basic:e=>({...e,type:"basic",_visit:function(t){return K9._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return K9._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return K9._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return K9._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return K9._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var Tg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return Tg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Tg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return Tg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return Tg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return Tg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Tg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Tg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return Tg._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var i_={int:e=>({value:e,type:"int",_visit:function(t){return i_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return i_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return i_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return i_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return i_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return i_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return i_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return i_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return i_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return i_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return i_._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var F4n={boolean:e=>({value:e,type:"boolean",_visit:function(t){return F4n._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return F4n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var AEi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return AEi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return AEi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var VW={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case VW.GenerallyAvailable:return t.generallyAvailable();case VW.Beta:return t.beta();case VW.Deprecated:return t.deprecated();default:return t._other()}}};var rFe={cursor:e=>({...e,type:"cursor",_visit:function(t){return rFe._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return rFe._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return rFe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);default:return t._other(e)}}};var ndi={language:e=>({...e,type:"language",_visit:function(t){return ndi._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return ndi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var WW={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",_visit:(e,t)=>{switch(e){case WW.Curl:return t.curl();case WW.Python:return t.python();case WW.Javascript:return t.javascript();case WW.Typescript:return t.typescript();case WW.Go:return t.go();case WW.Ruby:return t.ruby();case WW.Csharp:return t.csharp();case WW.Java:return t.java();case WW.Js:return t.js();case WW.Node:return t.node();case WW.Ts:return t.ts();case WW.Nodets:return t.nodets();case WW.Golang:return t.golang();case WW.Dotnet:return t.dotnet();case WW.Jvm:return t.jvm();default:return t._other()}}};var $Wt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return $Wt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return $Wt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var GWt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return GWt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return GWt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var HW={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case HW.Get:return t.get();case HW.Post:return t.post();case HW.Put:return t.put();case HW.Patch:return t.patch();case HW.Delete:return t.delete();case HW.Head:return t.head();case HW.Options:return t.options();case HW.Trace:return t.trace();default:return t._other()}}};var qEi={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return qEi._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return qEi._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return qEi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var adi={file:e=>({...e,type:"file",_visit:function(t){return adi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return adi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var YQ={file:e=>({...e,type:"file",_visit:function(t){return YQ._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return YQ._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return YQ._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return YQ._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return YQ._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return YQ._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return YQ._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Qy={primitive:e=>({...e,type:"primitive",_visit:function(t){return Qy._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Qy._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Qy._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Qy._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Qy._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Qy._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Qy._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Qy._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Qy._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Qy._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Qy._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Xj={int:e=>({...e,type:"int",_visit:function(t){return Xj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Xj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return Xj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return Xj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return Xj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return Xj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Xj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return Xj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return Xj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return Xj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Xj._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var lz={boolean:e=>({value:e,type:"boolean",_visit:function(t){return lz._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return lz._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var odi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return odi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return odi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var dMe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return dMe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return dMe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return dMe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var gC={file:e=>({...e,type:"file",_visit:function(t){return gC._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return gC._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return gC._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return gC._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return gC._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return gC._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return gC._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var El={primitive:e=>({...e,type:"primitive",_visit:function(t){return El._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return El._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return El._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return El._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return El._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return El._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return El._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return El._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return El._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return El._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return El._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var NZ={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return NZ._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return NZ._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var tp={int:e=>({...e,type:"int",_visit:function(t){return tp._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return tp._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return tp._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return tp._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return tp._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return tp._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return tp._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return tp._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return tp._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return tp._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return tp._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var Cv={};Po(Cv,{AllOfPropertyConflict:()=>s2n,ArraySchema:()=>aWo,ArraySchemaWithExample:()=>BWo,Availability:()=>kUo,Base64WithExample:()=>MWo,BasicSecurityScheme:()=>rVo,BearerSecurityScheme:()=>iVo,BooleanSchema:()=>kVo,BooleanWithExample:()=>AWo,BytesResponse:()=>k4n,CasingOverrides:()=>oVo,CommonProperty:()=>pWo,CommonPropertyWithExample:()=>VWo,CursorPagination:()=>xVo,CustomCodeSample:()=>IVo,CustomCodeSampleLanguage:()=>TVo,CustomCodeSampleSdk:()=>BVo,CustomPagination:()=>NVo,DateWithExample:()=>EWo,DatetimeWithExample:()=>DWo,DiscriminatedOneOfSchema:()=>fWo,DiscriminatedOneOfSchemaWithExample:()=>LWo,DoubleSchema:()=>XVo,DoubleWithExample:()=>wWo,Encoding:()=>ZUo,Endpoint:()=>FVo,EndpointExample:()=>i2n,EndpointResponseExample:()=>qVo,EndpointSdkName:()=>Frr,EndpointWithExample:()=>yZp,EnumSchema:()=>W4n,EnumSchemaWithExample:()=>TWo,EnumValue:()=>BEi,ErrorExample:()=>SVo,FernExample:()=>EVo,FileResponse:()=>X4n,FileSchema:()=>bVo,FloatWithExample:()=>jWo,FullEndpointExample:()=>zVo,FullExample:()=>Uq,FullObjectExample:()=>pVo,FullOneOfExample:()=>hVo,GlobalHeader:()=>tWo,Header:()=>zEi,HeaderExample:()=>r2n,HeaderSecurityScheme:()=>nVo,HeaderWithExample:()=>NEi,HttpEndpointServer:()=>e2n,HttpError:()=>DVo,HttpErrorWithExample:()=>bWo,HttpMethod:()=>G4n,IdempotencyHeader:()=>rWo,Int64WithExample:()=>OWo,IntSchema:()=>KVo,IntWithExample:()=>gWo,JsonRequest:()=>PVo,JsonRequestWithExample:()=>hWo,JsonResponse:()=>Z4n,JsonResponseWithExample:()=>f2n,KeyValuePair:()=>_Vo,LiteralExample:()=>dVo,LiteralSchema:()=>u2n,LiteralSchemaValue:()=>iWo,LongSchema:()=>YVo,MapSchema:()=>oWo,MapSchemaWithExample:()=>IWo,MultipartRequest:()=>Y4n,MultipartRequestProperty:()=>mVo,MultipartRequestPropertyEncoding:()=>OVo,MultipartSchema:()=>gVo,NamedFullExample:()=>Urr,Namespace:()=>uVo,NamespaceId:()=>fVo,NullableSchema:()=>sWo,NullableSchemaWithExample:()=>xWo,OauthSecurityScheme:()=>cVo,ObjectProperty:()=>lWo,ObjectPropertyConflictInfo:()=>c2n,ObjectPropertyWithExample:()=>FWo,ObjectSchema:()=>nWo,ObjectSchemaWithExample:()=>RWo,OctetStreamRequest:()=>K4n,OffsetPagination:()=>RVo,OneOfSchema:()=>cWo,OneOfSchemaWithExample:()=>NWo,OpenApiIntermediateRepresentation:()=>_Zp,OpenApiSource:()=>JUo,OptionalSchema:()=>uWo,OptionalSchemaWithExample:()=>zWo,Pagination:()=>n2n,PathParameter:()=>Q4n,PathParameterExample:()=>MVo,PathParameterWithExample:()=>_Wo,PrimitiveExample:()=>$4n,PrimitiveSchema:()=>REi,PrimitiveSchemaValue:()=>eWo,PrimitiveSchemaValueWithExample:()=>qWo,PrimitiveSchemaWithExample:()=>d2n,PropertyKey:()=>H4n,ProtobufEncoding:()=>XUo,ProtobufSource:()=>KUo,QueryParameter:()=>J4n,QueryParameterExample:()=>t2n,QueryParameterWithExample:()=>l2n,QuerySecurityScheme:()=>aVo,ReferencedSchema:()=>Lrr,Request:()=>jVo,RequestWithExample:()=>yWo,Response:()=>wVo,ResponseWithExample:()=>vWo,Schema:()=>Sm,SchemaId:()=>FZ,SchemaWithExample:()=>fA,Schemas:()=>JVo,SdkGroup:()=>sVo,SdkGroupInfo:()=>yVo,SdkGroupName:()=>IEi,SecurityScheme:()=>lVo,SecuritySchemeId:()=>tVo,Server:()=>BCa,Source:()=>YUo,StatusCode:()=>Nrr,StreamingResponseExample:()=>AVo,StringSchema:()=>ZVo,StringSchemaWithExample:()=>SWo,SupportedSdkLanguage:()=>CVo,Tag:()=>eVo,TagId:()=>LZ,Tags:()=>vVo,TextResponse:()=>xEi,Uint64WithExample:()=>PWo,UintWithExample:()=>mWo,UnDiscriminatedOneOfSchema:()=>dWo,UnDiscriminatedOneOfSchemaWithExample:()=>UWo,UnknownSchemaWithExample:()=>CWo,Webhook:()=>LVo,WebhookExampleCall:()=>o2n,WebhookHttpMethod:()=>a2n,WebhookWithExample:()=>vZp,WebsocketChannel:()=>QVo,WebsocketHandshake:()=>UVo,WebsocketHandshakeWithExample:()=>hZp,WebsocketMessageExample:()=>$Vo,WebsocketMessageOrigin:()=>VVo,WebsocketMessageSchema:()=>WVo,WebsocketServer:()=>HVo,WebsocketSessionExample:()=>GVo,WithAvailability:()=>Bh,WithDescription:()=>Of,WithEncoding:()=>Tae,WithInline:()=>WE,WithName:()=>z0,WithNamespace:()=>a0,WithSdkGroupName:()=>sm,WithSource:()=>ty,WithStatusCode:()=>iFe,WithTitle:()=>um,commons:()=>msc,example:()=>Psc,finalIr:()=>jsc,parseIr:()=>wsc});var msc={};Po(msc,{BasicSecurityScheme:()=>rVo,BearerSecurityScheme:()=>iVo,Encoding:()=>ZUo,HeaderSecurityScheme:()=>nVo,Namespace:()=>uVo,NamespaceId:()=>fVo,OauthSecurityScheme:()=>cVo,OpenApiSource:()=>JUo,ProtobufEncoding:()=>XUo,ProtobufSource:()=>KUo,QuerySecurityScheme:()=>aVo,SchemaId:()=>FZ,SdkGroup:()=>sVo,SdkGroupName:()=>IEi,SecurityScheme:()=>lVo,SecuritySchemeId:()=>tVo,Server:()=>BCa,Source:()=>YUo,StatusCode:()=>Nrr,Tag:()=>eVo,TagId:()=>LZ,WithAvailability:()=>Bh,WithDescription:()=>Of,WithEncoding:()=>Tae,WithInline:()=>WE,WithName:()=>z0,WithNamespace:()=>a0,WithSdkGroupName:()=>sm,WithSource:()=>ty,WithStatusCode:()=>iFe,WithTitle:()=>um});var Mt={};Po(Mt,{JsonError:()=>L4n,ParseError:()=>U4n,any:()=>tZp,bigint:()=>VXp,boolean:()=>rZp,booleanLiteral:()=>eZp,date:()=>WXp,discriminant:()=>fZp,enum_:()=>$Uo,getObjectLikeUtils:()=>QWt,getObjectUtils:()=>_Qi,getSchemaUtils:()=>Lq,isProperty:()=>CEi,lazy:()=>HXp,lazyObject:()=>XXp,list:()=>QUo,number:()=>iZp,object:()=>GUo,objectWithoutOptionalProperties:()=>YXp,optional:()=>vsc,property:()=>GXp,record:()=>uZp,set:()=>sZp,string:()=>nZp,stringLiteral:()=>kXp,transform:()=>bsc,undiscriminatedUnion:()=>lZp,union:()=>pZp,unknown:()=>aZp,withParsedProperties:()=>Osc});var Mj={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function lA(e,t){return`Expected ${t}. Received ${TWD(e)}.`}function TWD(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function Y9(e){return{...e,json:UXp(e.json),parse:UXp(e.parse)}}function UXp(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
@@ -2048,7 +2048,7 @@ ${a}]`:`[${e.join(u)}]`},Gko=(e,t,r)=>`let ${e} = ${dmc(t,r)}`,dmc=(e,t,r)=>{swi
2048
2048
  `)},e.heapify=function(t,r){var i=new e(r);return i.heapArray=t,i.init(),i},e.heappop=function(t,r){var i=new e(r);return i.heapArray=t,i.pop()},e.heappush=function(t,r,i){var n=new e(i);n.heapArray=t,n.push(r)},e.heappushpop=function(t,r,i){var n=new e(i);return n.heapArray=t,n.pushpop(r)},e.heapreplace=function(t,r,i){var n=new e(i);return n.heapArray=t,n.replace(r)},e.heaptop=function(t,r,i){r===void 0&&(r=1);var n=new e(i);return n.heapArray=t,n.top(r)},e.heapbottom=function(t,r,i){r===void 0&&(r=1);var n=new e(i);return n.heapArray=t,n.bottom(r)},e.nlargest=function(t,r,i){var n=new e(i);return n.heapArray=rk([],oH(r),!1),n.init(),n.top(t)},e.nsmallest=function(t,r,i){var n=new e(i);return n.heapArray=rk([],oH(r),!1),n.init(),n.bottom(t)},e.prototype.add=function(t){return this._sortNodeUp(this.heapArray.push(t)-1),this._applyLimit(),!0},e.prototype.addAll=function(t){var r,i=this.length;(r=this.heapArray).push.apply(r,rk([],oH(t),!1));for(var n=this.length;i<n;++i)this._sortNodeUp(i);return this._applyLimit(),!0},e.prototype.bottom=function(t){return t===void 0&&(t=1),this.heapArray.length===0||t<=0?[]:this.heapArray.length===1?[this.heapArray[0]]:t>=this.heapArray.length?rk([],oH(this.heapArray),!1):this._bottomN_push(~~t)},e.prototype.check=function(){var t=this;return this.heapArray.find(function(r,i){return!!t.getChildrenOf(i).find(function(n){return t.compare(r,n)>0})})},e.prototype.clear=function(){this.heapArray=[]},e.prototype.clone=function(){var t=new e(this.comparator());return t.heapArray=this.toArray(),t._limit=this._limit,t},e.prototype.comparator=function(){return this.compare},e.prototype.contains=function(t,r){return r===void 0&&(r=e.defaultIsEqual),this.indexOf(t,r)!==-1},e.prototype.init=function(t){t&&(this.heapArray=rk([],oH(t),!1));for(var r=Math.floor(this.heapArray.length);r>=0;--r)this._sortNodeDown(r);this._applyLimit()},e.prototype.isEmpty=function(){return this.length===0},e.prototype.indexOf=function(t,r){if(r===void 0&&(r=e.defaultIsEqual),this.heapArray.length===0)return-1;for(var i=[],n=0;n<this.heapArray.length;){var a=this.heapArray[n];if(r(a,t))return n;this.compare(a,t)<=0&&i.push.apply(i,rk([],oH(e.getChildrenIndexOf(n)),!1)),n=i.shift()||this.heapArray.length}return-1},e.prototype.indexOfEvery=function(t,r){if(r===void 0&&(r=e.defaultIsEqual),this.heapArray.length===0)return[];for(var i=[],n=[],a=0;a<this.heapArray.length;){var u=this.heapArray[a];r(u,t)?(n.push(a),i.push.apply(i,rk([],oH(e.getChildrenIndexOf(a)),!1))):this.compare(u,t)<=0&&i.push.apply(i,rk([],oH(e.getChildrenIndexOf(a)),!1)),a=i.shift()||this.heapArray.length}return n},e.prototype.leafs=function(){if(this.heapArray.length===0)return[];var t=e.getParentIndexOf(this.heapArray.length-1);return this.heapArray.slice(t+1)},Object.defineProperty(e.prototype,"length",{get:function(){return this.heapArray.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"limit",{get:function(){return this._limit},set:function(t){t<0||isNaN(t)?this._limit=0:this._limit=~~t,this._applyLimit()},enumerable:!1,configurable:!0}),e.prototype.setLimit=function(t){return this.limit=t,t<0||isNaN(t)?NaN:this._limit},e.prototype.peek=function(){return this.heapArray[0]},e.prototype.pop=function(){var t=this.heapArray.pop();return this.length>0&&t!==void 0?this.replace(t):t},e.prototype.push=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return t.length<1?!1:t.length===1?this.add(t[0]):this.addAll(t)},e.prototype.pushpop=function(t){var r;return this.compare(this.heapArray[0],t)<0&&(r=oH([this.heapArray[0],t],2),t=r[0],this.heapArray[0]=r[1],this._sortNodeDown(0)),t},e.prototype.remove=function(t,r){var i=this;if(r===void 0&&(r=e.defaultIsEqual),!this.heapArray.length)return!1;if(t===void 0)return this.pop(),!0;for(var n=[0];n.length;){var a=n.shift();if(r(this.heapArray[a],t))return a===0?this.pop():a===this.heapArray.length-1?this.heapArray.pop():(this.heapArray.splice(a,1,this.heapArray.pop()),this._sortNodeUp(a),this._sortNodeDown(a)),!0;if(this.compare(this.heapArray[a],t)<=0){var u=e.getChildrenIndexOf(a).filter(function(l){return l<i.heapArray.length});n.push.apply(n,rk([],oH(u),!1))}}return!1},e.prototype.replace=function(t){var r=this.heapArray[0];return this.heapArray[0]=t,this._sortNodeDown(0),r},e.prototype.size=function(){return this.length},e.prototype.top=function(t){return t===void 0&&(t=1),this.heapArray.length===0||t<=0?[]:this.heapArray.length===1||t===1?[this.heapArray[0]]:t>=this.heapArray.length?rk([],oH(this.heapArray),!1):this._topN_push(~~t)},e.prototype.toArray=function(){return rk([],oH(this.heapArray),!1)},e.prototype.toString=function(){return this.heapArray.toString()},e.prototype.get=function(t){return this.heapArray[t]},e.prototype.getChildrenOf=function(t){var r=this;return e.getChildrenIndexOf(t).map(function(i){return r.heapArray[i]}).filter(function(i){return i!==void 0})},e.prototype.getParentOf=function(t){var r=e.getParentIndexOf(t);return this.heapArray[r]},e.prototype[Symbol.iterator]=function(){return d2E(this,function(t){switch(t.label){case 0:return this.length?[4,this.pop()]:[3,2];case 1:return t.sent(),[3,0];case 2:return[2]}})},e.prototype.iterator=function(){return this.toArray()},e.prototype._applyLimit=function(){if(this._limit>0&&this._limit<this.heapArray.length)for(var t=this.heapArray.length-this._limit;t;)this.heapArray.pop(),--t},e.prototype._bottomN_push=function(t){var r=new e(this.compare);r.limit=t,r.heapArray=this.heapArray.slice(-t),r.init();for(var i=this.heapArray.length-1-t,n=e.getParentIndexOf(i),a=[],u=i;u>n;--u)a.push(u);for(var l=this.heapArray;a.length;){var u=a.shift();this.compare(l[u],r.peek())>0&&(r.replace(l[u]),u%2&&a.push(e.getParentIndexOf(u)))}return r.toArray()},e.prototype._moveNode=function(t,r){var i;i=oH([this.heapArray[r],this.heapArray[t]],2),this.heapArray[t]=i[0],this.heapArray[r]=i[1]},e.prototype._sortNodeDown=function(t){for(var r=this.heapArray.length;;){var i=2*t+1,n=i+1,a=t;if(i<r&&this.compare(this.heapArray[i],this.heapArray[a])<0&&(a=i),n<r&&this.compare(this.heapArray[n],this.heapArray[a])<0&&(a=n),a===t)break;this._moveNode(t,a),t=a}},e.prototype._sortNodeUp=function(t){for(;t>0;){var r=e.getParentIndexOf(t);if(this.compare(this.heapArray[t],this.heapArray[r])<0)this._moveNode(t,r),t=r;else break}},e.prototype._topN_push=function(t){var r=new e(this._invertedCompare);r.limit=t;for(var i=[0],n=this.heapArray;i.length;){var a=i.shift();a<n.length&&(r.length<t?(r.push(n[a]),i.push.apply(i,rk([],oH(e.getChildrenIndexOf(a)),!1))):this.compare(n[a],r.peek())<0&&(r.replace(n[a]),i.push.apply(i,rk([],oH(e.getChildrenIndexOf(a)),!1))))}return r.toArray()},e.prototype._topN_fill=function(t){var r=this.heapArray,i=new e(this._invertedCompare);i.limit=t,i.heapArray=r.slice(0,t),i.init();for(var n=e.getParentIndexOf(t-1)+1,a=[],u=n;u<t;++u)a.push.apply(a,rk([],oH(e.getChildrenIndexOf(u).filter(function(l){return l<r.length})),!1));for((t-1)%2&&a.push(t);a.length;){var u=a.shift();u<r.length&&this.compare(r[u],i.peek())<0&&(i.replace(r[u]),a.push.apply(a,rk([],oH(e.getChildrenIndexOf(u)),!1)))}return i.toArray()},e.prototype._topN_heap=function(t){for(var r=this.clone(),i=[],n=0;n<t;++n)i.push(r.pop());return i},e.prototype._topIdxOf=function(t){if(!t.length)return-1;for(var r=0,i=t[r],n=1;n<t.length;++n){var a=this.compare(t[n],i);a<0&&(r=n,i=t[n])}return r},e.prototype._topOf=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var i=new e(this.compare);return i.init(t),i.peek()},e}();function lx_(e,t,r,i,n){if(r<=0)return[];let a=i??(l=>l),u=new sx_(p2E);for(let l of t){let d=cx_.default.get(a(e),a(l));n!=null&&d>n||(u.push({neighbor:l,distance:d}),u.size()>r&&u.pop())}return _2E(u).reverse().map(l=>l.neighbor)}function p2E(e,t){return e.distance!==t.distance?t.distance-e.distance:t.neighbor.localeCompare(e.neighbor)}function _2E(e){let t=[];for(;e.size()>0;){let r=e.pop();r&&t.push(r)}return t}var h2E=3,y2E=5;function TAi(e,t){let r=lx_(e,t,h2E,v2E,y2E),i=Array.from(t),n=`Failed to locate API section ${e}.`;switch(r.length){case 0:return n=`${n} No similar API sections found. Available API sections:`,i.length===0?`${n} []`:`${n} [
2049
2049
  ${i.map(a=>` ${a}`).join(`,
2050
2050
  `)}
2051
- ]`;case 1:return`${n} Did you mean ${r[0]}?`;case 2:return`${n} Did you mean ${r[0]} or ${r[1]}?`;default:return`${n} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function EKi(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function v2E(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function C9n({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(l=>{if(l.type!=="endpoint"){a.push(l);return}let d=t(l.endpointId);if(d==null)throw new Error(`Endpoint ${l.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,l),o==null||o.isResponseStream===l.isResponseStream){a.push(l);return}let c=a.indexOf(o),b=l.isResponseStream?l:o,g=l.isResponseStream?o:l,O={id:Oo.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function Xeu({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return C9n({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function Nir(e,t){if(t!=null)return zq(e.absoluteFilePath,t)}function Zeu({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let l=Oo.V1.PageId(Nir(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Bq(t.title)});return{id:i.get(l),type:"page",pageId:l,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var keu=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=l,this.workspace=s,this.hideChildren=o,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Oo.V1.ApiDefinitionId(r.id),this.#e=qAi.create(r,a),this.#c=d,this.#f=this.apiSection.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Bq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#l(this.apiSection.navigation,this.#e.api.rootPackage,this.#u)),this.#s=this.#y(this.#s.map(b=>this.#j(b)),this.#w(this.#e.api.rootPackage,this.#u))}get(){let t=Oo.V1.followRedirects(this.#s),r=new mpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#g(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#l(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?qAi.getSubpackageId(r):void 0;return t.map(a=>vRa(a)._visit({link:u=>({id:this.#c.get(u.url),type:"link",title:u.text,icon:u.icon,url:Oo.Url(u.url)}),page:u=>this.#p(u,i),package:u=>this.#_(u,i),section:u=>this.#h(u,i),item:({value:u})=>this.#v(u,n,i),endpoint:u=>this.#O(u,n,i)})).filter(ev)}#p(t,r){return Zeu({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#c,hideChildren:this.hideChildren})}#_(t,r){let i=t.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=qAi.getSubpackageId(a),l=this.#c.get(i??`${this.apiDefinitionId}:${u}`);this.#a.has(u)&&this.taskContext.logger.warn(EKi(t.package)),this.#a.add(u),this.#o.set(l,[u]);let d=t.slug??(Rir(a)?a.urlSlug:this.apiSection.slug??Bq(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,a,s);return{id:l,type:"apiPackage",children:o,title:t.title??(Rir(a)?a.displayName??SHt(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(TAi(t.package,this.#e.subpackageLocators));let u=t.slug??Bq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#l(t.contents,void 0,l);return{id:this.#c.get(i??`${this.apiDefinitionId}:${Bq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#h(t,r){let i=t.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#c.get(i??n??r.get()),l=t.referencedSubpackages.map(c=>{let b=this.#e.getSubpackageByIdOrLocator(c),g=b!=null?qAi.getSubpackageId(b):void 0;if(g===void 0){this.taskContext.logger.error(TAi(c,this.#e.subpackageLocators));return}return{subpackageId:g,locator:c}}).filter(c=>c!=null).filter(ev);this.#o.set(u,l.map(c=>c.subpackageId)),l.forEach(c=>{this.#a.has(c.subpackageId)&&this.taskContext.logger.error(EKi(c.locator)),this.#a.add(c.subpackageId)});let d=t.slug??Bq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#v(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(p_(t));if(n!=null){let a=qAi.getSubpackageId(n),u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(EKi(t)),this.#a.add(a),this.#o.set(u,[a]);let l=Rir(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:Rir(n)?n.displayName??SHt(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,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,featureFlags:void 0}}return this.#O({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,featureFlags:void 0},r,i)}#O(t,r,i){let n=(r!=null?this.#e.subpackages.get(k6.SubpackageId(r))?.endpoints.get(k6.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let l=this.#e.getEndpointId(n);if(l==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${DKi(n.method,n.path.parts)}. Got undefined.`);else{this.#t.has(l)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${l}`),this.#t.add(l);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#c.get(`${this.apiDefinitionId}:${l}`),type:"endpoint",method:n.method,endpointId:l,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??PC(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let a=(r!=null?this.#e.subpackages.get(k6.SubpackageId(r))?.webSockets.get(k6.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let l=this.#e.getWebSocketId(a);if(l==null)this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);else return this.#r.has(l)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${l}`),this.#r.add(l),{id:this.#c.get(`${this.apiDefinitionId}:${l}`),type:"webSocket",webSocketId:l,title:t.title??a.name??PC(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(a.availability),playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(k6.SubpackageId(r))?.webhooks.get(k6.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Oo.V1.WebhookId(t.endpoint));if(u!=null){let l=this.#e.getWebhookId(u);if(l==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#n.has(l)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${l}`),this.#n.add(l),{id:this.#c.get(`${this.apiDefinitionId}:${l}`),type:"webhook",webhookId:l,method:u.method,title:t.title??u.name??lb("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return Xeu({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>PC(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#j(t){return bRa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#m(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#w(t,r){let i=[];return t.endpoints.forEach(n=>{if(n.protocol?.type==="grpc"){let a=this.#e.getGrpcId(n);if(a==null){this.taskContext.logger.error(`Expected Grpc ID for ${n.id} at path: ${DKi(n.method,n.path.parts)}. Got undefined.`);return}if(this.#i.has(a))return;let u=r.apply(n);i.push({id:Oo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"grpc",grpcId:a,title:n.name??PC(n.path.parts),method:n.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:void 0,slug:u.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let a=this.#e.getEndpointId(n);if(a==null){this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${DKi(n.method,n.path.parts)}. Got undefined.`);return}if(this.#t.has(a))return;let u=r.apply(n);i.push({id:Oo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??PC(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null){this.taskContext.logger.error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return}this.#r.has(a)||i.push({id:Oo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??PC(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null){this.taskContext.logger.error(`Expected Webhook ID for ${n.id}. Got undefined.`);return}this.#n.has(a)||i.push({id:Oo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??SHt(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#a.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=Rir(a)?r.apply(a):r,l=this.#m(n,u);l.length>0&&i.push({id:Oo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:Rir(a)?a.displayName??SHt(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,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,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#m(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(TAi(t||"unknown",[])),[]):this.#w(i,r)}#g(t){return Yeu(t)}mergeEndpointPairs(t){return C9n({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>PC(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var etu=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[p_(r).toLowerCase()]=i,this.#e[`subpackage_${p_(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${lb(a.baseUrl,PC(i.path))}`]=i,this.#r[`${n} ${lb(a.baseUrl,MFe(i.path))}`]=i;let u=Keu(a);u!=null&&(this.#r[`${n} ${lb(u,PC(i.path))}`]=i,this.#r[`${n} ${lb(u,MFe(i.path))}`]=i)}),this.#r[`${i.method} ${PC(i.path)}`]=i,this.#r[`${i.method} ${MFe(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${PC(i.path)}`]=i,this.#n[`STREAM ${MFe(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}get subpackageLocators(){return new Set(Object.keys(this.#e))}};function ORa({item:e,parentSlug:t}){return t.apply({urlSlug:Bq(e.id.split(".").pop()??"")}).get()}var mRa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;#l=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=d,this.hideChildren=o,this.#e=r,this.#t=new etu(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Oo.V1.ApiDefinitionId(r.id),this.#c=s,this.#f=this.apiSection.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Bq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#p(this.apiSection.navigation,void 0,this.#u)),this.#s=this.#j(this.#s.map(b=>this.#w(b)),this.#m(this.#e,this.#u))}get(){let t=Oo.V1.followRedirects(this.#s),r=new mpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#p(t,r,i){return t.map(n=>vRa(n)._visit({link:a=>({id:this.#c.get(a.url),type:"link",title:a.text,icon:a.icon,url:Oo.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#h(a,i),section:a=>this.#v(a,i),item:({value:a})=>this.#O(a,r,i),endpoint:a=>this.#y(a,r,i)})).filter(ev)}#_(t,r){return Zeu({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#c,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#h(t,r){let i=t.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#c.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let l=t.slug??Bq(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#p(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??SHt(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(a.id,o),o}else{this.taskContext.logger.warn(TAi(t.package,this.#t.subpackageLocators));let u=t.slug??Bq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#p(t.contents,t.package,l),s={id:this.#c.get(i??`${this.apiDefinitionId}:${Bq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(t.package,s),s}}#v(t,r){let i=t.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#c.get(i??n??r.get()),u=t.referencedSubpackages.map(b=>{let g=this.#t.getSubpackageByLocator(b);if(g==null){this.taskContext.logger.error(TAi(b,this.#t.subpackageLocators));return}return{subpackageId:g.id,locator:b}}).filter(b=>b!=null).filter(ev),l=u.map(b=>b.subpackageId);this.#o.set(a,l),u.forEach(b=>{this.#a.has(b.subpackageId)&&this.taskContext.logger.error(EKi(b.locator)),this.#a.add(b.subpackageId)});let d=t.slug??Bq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#p(t.contents,t.title,s),c={id:a,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return l.forEach(b=>{this.#l.set(b,c)}),c}#O(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.warn(EKi(t)),this.#a.add(a),this.#o.set(u,[a]);let l=Bq(n.name),d=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??SHt(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,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,featureFlags:void 0};return this.#l.set(a,s),s}return this.#y({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,featureFlags:void 0},r,i)}#y(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null)if(this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),n.id==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${DKi(n.method,n.path)}. Got undefined.`);else{this.#r.add(n.id);let l=t.slug!=null?i.append(t.slug).get():ORa({item:n,parentSlug:i});return{id:this.#c.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??PC(n.path),slug:l,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null)if(this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),a.id==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}else return this.#n.add(a.id),{id:this.#c.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??PC(a.path),slug:t.slug!=null?i.append(t.slug).get():ORa({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null)if(this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),u.id==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#i.add(u.id),{id:this.#c.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??lb("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():ORa({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return Xeu({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>PC(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#w(t){return bRa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#E(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#m(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#g(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Endpoint ID for ${a.id} at path: ${DKi(a.method,a.path)}. Got undefined.`);return}!this.#r.has(YA.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#P(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}!this.#n.has(YA.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#A(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}!this.#i.has(YA.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)}),i}#g(t,r,i){let n=Oo.V1.SlugGenerator.init(i.get()).apply({urlSlug:Bq(r.name)}),a=this.#E(t,n),u={id:Oo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??SHt(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,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,featureFlags:void 0};return this.#l.set(t,u),a.length>0?u:void 0}#D(t,r,i,n){r.slug=ORa({item:t,parentSlug:i}),n.push(r)}#P(t,r,i,n){let a={id:Oo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:YA.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??PC(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#A(t,r,i,n){let a={id:Oo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:YA.WebSocketId(t),title:r.displayName??PC(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#d(t,r,i,n){let a={id:Oo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:YA.WebhookId(t),method:r.method,title:r.displayName??SHt(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,l])=>t===this.#e.id?l.id.split(".").length===1:l.id!=null&&l.id.includes(t)&&l.id!==t&&l.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===YA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===YA.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===YA.api.v1.SubpackageId(t)));return{id:YA.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#E(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(TAi(t||"unknown",[])),[]):this.#m(i,r)}#S(t){return Yeu(t)}mergeEndpointPairs(t){return C9n({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>PC(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var fx_=ui(require("crypto"),1);function b2E(e){return fx_.default.createHash("sha256").update(e).digest("hex")}var ttu=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),b2E(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Oo.V1.NodeId(this.#n(t))}};function rtu(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,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var itu=ui(AEe(),1);var hwc=ui(AEe(),1);function dx_(e,t,r){if(e.schemes.length>0&&e.schemes[0]!=null){let i=e.schemes[0];switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix,description:e.docs};case"oauth":{let n=i.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:hwc.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:hwc.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:wo(i)}}}var lm=ui(AEe(),1);var CAi=ui(AEe(),1);function _x_(e){return e._visit({alias:t=>({type:"alias",value:wE(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:i4(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>CAi.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:CAi.FernRegistry.PropertyKey(r.name.wireValue),valueType:wE(r.valueType),availability:i4(r.availability),propertyAccess:r.propertyAccess})),extraProperties:m2E(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:CAi.FernRegistry.PropertyKey(i.name.wireValue),valueType:wE(i.valueType),availability:i4(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?i4(i.availability):void 0,additionalProperties:Us.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[CAi.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:CAi.FernRegistry.PropertyKey(n.name.wireValue),valueType:wE(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.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:wE(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function wE(e){return e._visit({container:t=>Us.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:wE(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:wE(r),valueType:wE(i)}),optional:r=>({type:"optional",itemType:wE(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:wE(r)}),set:r=>({type:"set",itemType:wE(r)}),literal:r=>Us.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:CAi.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Us.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>O2E(t.v2),float:()=>px_(t.v2),double:()=>px_(t.v2),string:()=>g2E(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),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 g2E(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function O2E(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 px_(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 m2E(e){return typeof e=="boolean"?e?Kc.unknown():void 0:typeof e=="string"?{type:"id",value:CAi.FernRegistry.TypeId(e),default:void 0}:wE(e)}function vwc(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?j2E(r,t):[],webhooks:i!=null?P2E(i):[],websockets:n!=null?[w2E(n,t)]:[],types:e.types.map(a=>lm.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>lm.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?lm.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function P2E(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(i=>({payload:i.payload.jsonExample}))??[]),{description:t.docs??void 0,id:lm.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??gUi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:wE(i.valueType),availability:i4(i.availability)})),payload:T2E(t.payload),examples:r}})}function j2E(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let l,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,o=Object.keys(d).length>1;for(let[b,g]of Object.entries(d))l=yx_({shouldUseExampleName:o,exampleName:g.displayName??b,example:g,irEndpoint:i}),l!=null&&a.push(l);let c=Object.keys(s).length>1;for(let[b,g]of Object.entries(s))l=yx_({shouldUseExampleName:c,exampleName:g.displayName??b,example:g,irEndpoint:i}),l!=null&&a.push(l)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>ywc({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(ev));else if(n!=null){let l=ywc({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=tCa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=ywc({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:i4(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:M2E(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?lm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?S2E({environmentsConfig:t.environments,endpoint:i}):void 0,id:lm.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??gUi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:lm.FernRegistry.PropertyKey(l.name.originalName),type:wE(l.valueType),availability:void 0})),parts:[...B9n(i.basePath),...B9n(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:lm.FernRegistry.PropertyKey(l.name.originalName),type:wE(l.valueType),availability:void 0})),parts:[...t.basePath!=null?B9n(t.basePath):[],...B9n(e.basePath),...B9n(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:wE(l.valueType),availability:i4(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:wE(l.valueType),availability:i4(l.availability)})),request:i.requestBody!=null?A2E(i.requestBody):void 0,response:i.response!=null?hx_(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(hx_).filter(ev)},errors:void 0,errorsV2:q2E(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:l=>({type:"grpc",methodName:i.id,methodType:l.methodType}),_other:()=>{}})};r.push(u)}return r}function w2E(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(u=>({type:lm.FernRegistry.api.v1.WebSocketMessageId(u.type),body:u.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[lm.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:lm.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:i4(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?lm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?D2E({environmentsConfig:t.environments,channel:e}):[],id:lm.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??gUi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:lm.FernRegistry.PropertyKey(i.name.originalName),type:wE(i.valueType),availability:void 0})),parts:B9n(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:wE(i.valueType),description:i.docs,availability:i4(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:wE(i.valueType),availability:i4(i.availability)})),messages:e.messages.map(i=>({type:lm.FernRegistry.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:C2E(i.body),description:i.docs,availability:i4(i.availability)})),examples:r}}function i4(e){if(e!=null)switch(e.status){case"DEPRECATED":return lm.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return lm.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return lm.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return lm.FernRegistry.Availability.Beta;default:wo(e.status)}}function S2E({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:lm.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(u=>r.environments.map(l=>{let d=l.urls[u];if(d==null)throw new Error(`Expected environment ${l.id} to contain url for ${u}`);return{id:lm.FernRegistry.EnvironmentId(u),baseUrl:d}})).filter((u,l,d)=>l===d.findIndex(s=>s.id===u.id&&s.baseUrl===u.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let u=a.urls[i];if(u==null)throw new Error(`Expected environment ${a.id} to contain url for ${i}`);return{id:lm.FernRegistry.EnvironmentId(a.id),baseUrl:u}});default:wo(r)}}function D2E({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:lm.FernRegistry.EnvironmentId(n.id),baseUrl:E2E(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:lm.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:wo(r)}}function E2E(e,t){return e.replace(/^[^:]+/,t)}function M2E(e){return Us.http.HttpMethod._visit(e,{get:()=>lm.FernRegistry.HttpMethod.Get,post:()=>lm.FernRegistry.HttpMethod.Post,put:()=>lm.FernRegistry.HttpMethod.Put,patch:()=>lm.FernRegistry.HttpMethod.Patch,delete:()=>lm.FernRegistry.HttpMethod.Delete,head:()=>lm.FernRegistry.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function B9n(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:lm.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function A2E(e){let t=Us.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??hM.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>lm.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:lm.FernRegistry.PropertyKey(i.name.wireValue),valueType:wE(i.valueType),availability:i4(i.availability),propertyAccess:void 0})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??hM.APPLICATION_JSON,shape:{type:"reference",value:wE(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(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:lm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:lm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:lm.FernRegistry.PropertyKey(n.name.wireValue),valueType:wE(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:i4(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(ev)},contentType:r.contentType,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 hx_(e){if(e.body==null)return;let t,r=Us.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:wE(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:wE(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:wE(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function q2E(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:wE(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:B2E(n)})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:lm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:lm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:wE(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function yx_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i}){if(r==null)return;let n=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:r.request?.headers??{},requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:a=>{if(r.request==null)return;let u={};if(Qj(r.request.requestBody)){let l=r.request.requestBody;for(let d of a.properties)d._visit({file:s=>{let o=l[s.key.wireValue];if(s.type==="file")u[s.key.wireValue]={type:"filename",value:typeof o=="string"?o:"<file1>"};else if(s.type==="fileArray"){let c=(Array.isArray(o)?o:[o]).filter(b=>typeof b=="string");u[s.key.wireValue]={type:"filenames",value:c}}},bodyProperty:s=>{if(s.style==="exploded"){let o=l[s.name.wireValue];u[s.name.wireValue]={type:"exploded",value:Array.isArray(o)?o:[o]}}else u[s.name.wireValue]={type:"json",value:l[s.name.wireValue]}},_other:kze})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:n??void 0,responseBodyV3:n!=null?r.response?.body?._visit({json:a=>({type:"json",value:a}),stream:a=>({type:"stream",value:a.map(u=>({type:"json",value:u}))}),error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(a=>({name:a.name,description:a.docs??void 0,install:void 0,language:a.language,code:a.code})).filter(ev)}}function ywc({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(l=>{let d=l.valueType.type==="container"&&l.valueType.container.type==="literal"?l.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:l.name,value:{jsonExample:d,shape:Us.ExampleTypeReferenceShape.primitive(Us.ExamplePrimitive.string({original:d}))}}}).filter(ev),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((l,d)=>(l[lm.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,l),{}),queryParameters:a.queryParameters.reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),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:l=>{if(a.request==null)return;let d={};if(Qj(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of l.properties)o._visit({file:c=>{let b=s[c.key.wireValue];if(c.type==="file")d[c.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(c.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];d[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:kze})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Us.http.ExampleResponse._visit(a.response,{ok:l=>l._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: "+l.type)}}),error:({error:l})=>{let d=i.errors[l.errorId];if(d==null)throw new Error("Cannot find error "+l.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:l=>l._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:l=>l.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:l=>l._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:l=>l.body!=null?{type:"json",value:l.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(l=>TEe._visit(l,{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(ev)}}function T2E(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>lm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:lm.FernRegistry.PropertyKey(t.name.wireValue),valueType:wE(t.valueType),availability:i4(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:wE(e.payloadType)},description:e.docs};default:wo(e)}}function C2E(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>lm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:lm.FernRegistry.PropertyKey(t.name.wireValue),valueType:wE(t.valueType),availability:i4(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:wE(e.bodyType)};default:wo(e)}}function B2E(e){let t=e.v2Examples?.userSpecifiedExamples,r=e.v2Examples?.autogeneratedExamples,i=e.examples;return t!=null&&Object.keys(t).length>0?Object.entries(t).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):r!=null&&Object.keys(r).length>0?Object.entries(r).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):i.length>0?i.map(n=>({name:n.name?.originalName,responseBody:{type:"json",value:n.jsonExample},description:n.docs})):[]}function ik({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:vwc(e.rootPackage,e),auth:dx_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:i4(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:wE(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[itu.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:_x_(a.shape),availability:i4(a.availability),displayName:a.name.displayName};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[itu.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:itu.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName??a.displayName,name:a.name.originalName,description:a.docs??void 0,...vwc(a,e)}}return i}var bwc=ui(AEe(),1);async function gwc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=gR({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new bR(r,t)}),d=QWi({token:i.value}),s=ik({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:bwc.FernRegistry.OrgId(e),apiId:bwc.FernRegistry.ApiId(l.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:l};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 I2E=new hKi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function PRa(e,t,r){return Gxa(Wxa(ik({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),k6.ApiDefinitionId(t),I2E))}var uh={};Po(uh,{AlgoliaSearchIndex:()=>vx_,ApiDefinitionId:()=>Nx_,ApiId:()=>Vx_,Availability:()=>iR_,DocsConfigId:()=>Wx_,EndpointId:()=>$x_,EndpointPathLiteral:()=>tR_,EnvironmentId:()=>Hx_,FileId:()=>Yx_,HttpMethod:()=>rR_,IndexSegmentId:()=>bx_,JqString:()=>Zx_,OrgId:()=>Lx_,PageId:()=>Kx_,PayloadLocation:()=>qR_,PropertyKey:()=>kx_,PullRequestState:()=>SR_,RoleId:()=>eR_,TokenId:()=>Ux_,TypeId:()=>Jx_,Url:()=>Xx_,VersionId:()=>Fx_,WebSocketId:()=>Gx_,WebhookId:()=>Qx_,algolia:()=>Owc,api:()=>qwc,commons:()=>Twc,diff:()=>nR_,docs:()=>Lwc,generators:()=>Vwc,git:()=>Wwc,navigation:()=>Gwc,sdks:()=>Jwc,snippets:()=>MR_,snippetsFactory:()=>AR_,templates:()=>Kwc,tokens:()=>TR_});var Owc={};Po(Owc,{AlgoliaSearchIndex:()=>vx_,IndexSegmentId:()=>bx_});function vx_(e){return e}function bx_(e){return e}var qwc={};Po(qwc,{latest:()=>jwc,v1:()=>Awc});var jwc={};Po(jwc,{AuthSchemeId:()=>gx_,WebhookHttpMethod:()=>jx_,auth:()=>mwc,commons:()=>Ox_,endpoint:()=>mx_,type_:()=>Px_,webhook:()=>Pwc,websocket:()=>wx_});var mwc={};Po(mwc,{AuthSchemeId:()=>gx_});function gx_(e){return e}var Ox_={};var mx_={};var Px_={};var Pwc={};Po(Pwc,{WebhookHttpMethod:()=>jx_});var jx_={Get:"GET",Post:"POST"};var wx_={};var Awc={};Po(Awc,{SubpackageId:()=>Ix_,WebSocketMessageId:()=>zx_,WebSocketMessageOrigin:()=>xx_,WebhookHttpMethod:()=>Rx_,commons:()=>Mwc,db:()=>wwc,read:()=>Dwc,register:()=>Ewc});var wwc={};Po(wwc,{endpoint:()=>Sx_});var Sx_={};var Dwc={};Po(Dwc,{SupportedLanguage:()=>Dx_,endpoint:()=>Swc,type_:()=>Ex_,webhook:()=>Mx_,websocket:()=>Ax_});var Swc={};Po(Swc,{SupportedLanguage:()=>Dx_});var Dx_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var Ex_={};var Mx_={};var Ax_={};var Ewc={};Po(Ewc,{SourceId:()=>z2E,endpoint:()=>qx_,type_:()=>Tx_,webhook:()=>Cx_,websocket:()=>Bx_});var qx_={};var Tx_={};var Cx_={};var Bx_={};function z2E(e){return e}var Mwc={};Po(Mwc,{SubpackageId:()=>Ix_,WebSocketMessageId:()=>zx_,WebSocketMessageOrigin:()=>xx_,WebhookHttpMethod:()=>Rx_});function Ix_(e){return e}function zx_(e){return e}var xx_={Client:"client",Server:"server"};var Rx_={Get:"GET",Post:"POST"};var Twc={};Po(Twc,{ApiDefinitionId:()=>Nx_,ApiId:()=>Vx_,Availability:()=>iR_,DocsConfigId:()=>Wx_,EndpointId:()=>$x_,EndpointPathLiteral:()=>tR_,EnvironmentId:()=>Hx_,FileId:()=>Yx_,HttpMethod:()=>rR_,JqString:()=>Zx_,OrgId:()=>Lx_,PageId:()=>Kx_,PropertyKey:()=>kx_,RoleId:()=>eR_,TokenId:()=>Ux_,TypeId:()=>Jx_,Url:()=>Xx_,VersionId:()=>Fx_,WebSocketId:()=>Gx_,WebhookId:()=>Qx_});function Nx_(e){return e}function Fx_(e){return e}function Lx_(e){return e}function Ux_(e){return e}function Vx_(e){return e}function Wx_(e){return e}function Hx_(e){return e}function $x_(e){return e}function Gx_(e){return e}function Qx_(e){return e}function Jx_(e){return e}function Kx_(e){return e}function Yx_(e){return e}function Xx_(e){return e}function Zx_(e){return e}function kx_(e){return e}function eR_(e){return e}function tR_(e){return e}var rR_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var iR_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var nR_={};var Lwc={};Po(Lwc,{latest:()=>Iwc,v1:()=>Nwc,v2:()=>Fwc});var Iwc={};Po(Iwc,{Layout:()=>oR_,MdxEngine:()=>x2E,TwitterCardSetting:()=>uR_,commons:()=>aR_,frontmatter:()=>Cwc,seo:()=>Bwc});var x2E={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var aR_={};var Cwc={};Po(Cwc,{Layout:()=>oR_});var oR_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var Bwc={};Po(Bwc,{TwitterCardSetting:()=>uR_});var uR_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Nwc={};Po(Nwc,{commons:()=>Rwc,db:()=>sR_,read:()=>cR_,write:()=>zwc});var sR_={};var cR_={};var zwc={};Po(zwc,{DocsRegistrationId:()=>N2E,FilePath:()=>R2E});function R2E(e){return e}function N2E(e){return e}var Rwc={};Po(Rwc,{ContentAlignment:()=>pR_,FontDisplay:()=>bR_,FontStyle:()=>vR_,HeaderPosition:()=>_R_,JsScriptStrategy:()=>yR_,ProgrammingLanguage:()=>lR_,SearchbarPlacement:()=>fR_,TabsPlacement:()=>dR_,TwitterCardSetting:()=>hR_,commons:()=>xwc});var xwc={};Po(xwc,{ContentAlignment:()=>pR_,FontDisplay:()=>bR_,FontStyle:()=>vR_,HeaderPosition:()=>_R_,JsScriptStrategy:()=>yR_,ProgrammingLanguage:()=>lR_,SearchbarPlacement:()=>fR_,TabsPlacement:()=>dR_,TwitterCardSetting:()=>hR_});var lR_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var fR_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var dR_={Header:"HEADER",Sidebar:"SIDEBAR"};var pR_={Center:"CENTER",Left:"LEFT"};var _R_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var hR_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var yR_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var vR_={Normal:"normal",Italic:"italic"};var bR_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Fwc={};Po(Fwc,{read:()=>gR_,write:()=>OR_});var gR_={};var OR_={};var Vwc={};Po(Vwc,{ChangelogEntryType:()=>PR_,GeneratorId:()=>F2E,GeneratorLanguage:()=>L2E,ReleaseType:()=>jR_,cli:()=>mR_,commons:()=>Uwc,versions:()=>wR_});var mR_={};var Uwc={};Po(Uwc,{ChangelogEntryType:()=>PR_,ReleaseType:()=>jR_});var PR_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var jR_={Ga:"GA",Rc:"RC"};var wR_={};function F2E(e){return e}var L2E={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Wwc={};Po(Wwc,{PullRequestState:()=>SR_});var SR_={Open:"open",Closed:"closed",Merged:"merged"};var Gwc={};Po(Gwc,{latest:()=>Hwc,v1:()=>$wc});var Hwc={};Po(Hwc,{NodeId:()=>W2E,ProductId:()=>H2E,Slug:()=>U2E,TabId:()=>V2E});function U2E(e){return e}function V2E(e){return e}function W2E(e){return e}function H2E(e){return e}var $wc={};Po($wc,{NavigationV1Availability:()=>K2E,NodeId:()=>Q2E,ProductId:()=>J2E,Slug:()=>$2E,TabId:()=>G2E});function $2E(e){return e}function G2E(e){return e}function Q2E(e){return e}function J2E(e){return e}var K2E={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Jwc={};Po(Jwc,{Language:()=>DR_,VersionBump:()=>ER_,versions:()=>Qwc});var Qwc={};Po(Qwc,{Language:()=>DR_,VersionBump:()=>ER_});var DR_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var ER_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var MR_={};var AR_={};var Kwc={};Po(Kwc,{PayloadLocation:()=>qR_});var qR_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var TR_={};var I9n=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Gd(e){return e!=null}var BR_=ui(UCn(),1);var CR_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function Fir(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,BR_.default)(e,{special:CR_}).replace(/V\s(\d)/g,"V$1")}function ntu({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],l=uh.api.v1.SubpackageId(u.join("."));r[l]={id:l,name:a,displayName:Fir(a)},n.push(a)})}),r}var atu=class{errors=new I9n},z9n=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function IR_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var otu=class extends atu{},a_=class extends z9n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,l)=>u===this.accessPath[this.accessPath.length-a.length+l])||this.accessPath.push(...a)}r.logger.debug(`Processing ${IR_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},x3=class extends a_{},eoe=class extends x3{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var zR_="x-fern-base-path",xR_="x-fern-availability",utu="x-fern-sdk-group-name",RR_="x-fern-global-headers",NR_="x-fern-sdk-method-name";var FR_="x-fern-webhook",LR_="x-fern-access-token-locator",UR_="x-fern-basic",VR_="x-fern-username-variable-name",WR_="x-fern-password-variable-name",HR_="x-fern-bearer",$R_="x-fern-token-variable-name",GR_="x-fern-header",QR_="x-fern-header-variable-name",JR_="x-fern-server-name",KR_="x-fern-examples";var stu=class extends a_{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[JR_]}convert(){if(this.serverName!=null)return this.serverName}};var ctu=class extends a_{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new stu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:uh.EnvironmentId(t),baseUrl:this.url}}};function Lir(e,t,r,i){let n=e??[],a=new Set(n.map(l=>l.url)),u=(t??[]).filter(l=>!a.has(l.url)).map((l,d)=>new ctu({input:l,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function VS(e){return typeof e=="object"&&Gd(e)&&"$ref"in e&&typeof e.$ref=="string"}function uH(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(VS(n)&&(n=uH(n,t,r)),n)}function ltu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return VS(r)?uH(r,t,void 0):r}var uN_=ui(pz());var ftu=class extends a_{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[UR_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var dtu=class extends a_{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[WR_]}convert(){return this.passwordVariableName}};var ptu=class extends a_{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[VR_]}convert(){return this.usernameVariableName}};var _tu=class extends a_{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[HR_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var htu=class extends a_{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[$R_]}convert(){return this.tokenVariableName}};function YR_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var XR_="x-bearer-format",ZR_="x-code-samples",kR_="x-codeSamples";var ytu=class extends a_{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[XR_]}convert(){return this.bearerFormat}};var vtu=class extends a_{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[GR_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var btu=class extends a_{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[QR_]}convert(){return this.headerVariableName}};function eN_(e){return e.type==="apiKey"}var x9n=class extends a_{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){eN_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new vtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new btu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new ytu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function tN_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function rN_(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function iN_(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let l=e[i];a?l==="\\"&&i+1<r?(i++,n+=e[i]):l===a?a="":n+=l:u?l==='"'||l==="'"?a=l:l==="]"?(u=!1,t.push(n),n=""):n+=l:l==="["?(u=!0,n&&(t.push(n),n="")):l==="."?n&&(t.push(n),n=""):n+=l,i++}return n&&t.push(n),t}function Ywc(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?tN_(t)?Ywc(e,iN_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=rN_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return Y2E(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function Y2E(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null)return r;i=i[t[n]]}return i===void 0?r:i}function nN_(e){return function(t){return Ywc(t,e)}}function Xwc(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Xwc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function gtu(e,t){switch(t=t??tC_,typeof t){case"string":case"symbol":case"number":case"object":return oL(e,nN_(t));case"function":return oL(e,t)}}function aN_(e){return typeof e!="string"&&(e=Xwc(e)),e.replace(/['\u2019]/g,"")}function DHt(e){return qE_(aN_(e))}function vA(e){if(e!=null)return Array.isArray(e)?e:[e]}function Otu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let l=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&l==null))return`${X2E(u)}${Z2E(e)}.${k2E(i,n,a,l)}`}function X2E(e){return e?"webhook_":"endpoint_"}function Z2E(e){return e!=null?vA(e)?.map(t=>DHt(t)).join("/"):""}function k2E(e,t,r,i){return e||t||DHt(r??"")||DHt(i??"")}function oN_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var mtu=class extends a_{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[LR_],this.accessTokenLocator!=null&&(oN_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var Ptu=class extends a_{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new x9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new mtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=Otu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:uh.EndpointId(r),accessTokenLocator:uh.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var R9n=class extends a_{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new ftu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new ptu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new dtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new _tu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new htu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{YR_(this.input)?(this.authScheme="header",this.headerAuthNode=new x9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new Ptu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new uN_.UnreachableCaseError(this.authScheme);return}}};var N9n=class extends a_{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=ltu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new R9n({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(Gd))}};var jtu=class extends a_{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[zR_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function sN_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function cN_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function F9n(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>vA(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!sN_(n))&&(u=cN_(u,u.type==="enum"?u.default:void 0)),{key:uh.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(Gd)).filter(Gd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function wtu(e,t){return VS(e)?uH(e,t,void 0):e}function BAi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function lN_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function fN_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var dN_=ui(pz());var Zwc=["decimal","decimal128","double-int","double","float","sf-decimal"],kwc=["int16","int32","int64","int8","sf-integer","uint8"],e1c=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],t1c=["beta","pre-release","in-development","generally-available","deprecated"];function R3(e,t){return VS(e)?uH(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var qFe=class extends a_{availability;constructor(t){super(t),this.safeParse()}parse(){if(R3(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[xR_];r!=null&&(t1c.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${t1c.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return uh.Availability.Beta;case"in-development":return uh.Availability.InDevelopment;case"generally-available":return uh.Availability.GenerallyAvailable;case"deprecated":return uh.Availability.Deprecated;case void 0:return;default:new dN_.UnreachableCaseError(this.availability);return}}};var Dtu=ui(pz());function pN_(e){return typeof e=="object"&&e!=null&&"language"in e}function _N_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function hN_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function yN_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Stu(e){return typeof e=="object"&&e!=null&&"event"in e}function r1c(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Stu)}function IAi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function vN_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var Etu=class extends a_{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[KR_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return IAi(u)?[n,{type:"filenameWithData",filename:u.filename,data:uh.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>IAi(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:uh.FileId(l.data)}))}];if(u.every(l=>typeof l=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new Dtu.UnreachableCaseError(a.multipartType);return}}).filter(Gd))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=vN_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new Dtu.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{hN_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{r1c(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!r1c(r.response)&&yN_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new Dtu.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{pN_(c)?c.language!=null&&(l[c.language]??=[],l[c.language]?.push({name:c.name,language:c.language,install:c.install,code:c.code,generated:!1,description:c.docs})):_N_(c)&&c.sdk!=null&&(l[c.sdk]??=[],l[c.sdk]?.push({name:c.name,language:c.sdk,install:void 0,code:c.code,generated:!1,description:c.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([c,b])=>[uh.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[uh.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[uh.PropertyKey(c),b]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:l}}))}};var jRa=class extends a_{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[utu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>uh.api.v1.SubpackageId(DHt(r)))}};var Mtu=class extends a_{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[NR_]}convert(){return this.sdkMethodName}};var Atu=class extends a_{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[FR_]}convert(){return this.isWebhook}};var qtu=class extends a_{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[ZR_]??[],...this.input[kR_]??[]],this.codeSamples.forEach(t=>{[...Object.values(uh.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var MKi=ui(pz());function i1c(e,t){return VS(e)?uH(e,t,void 0):e}function bN_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var dL="",Uir=class extends a_{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(IAi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>IAi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new MKi.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=i1c(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=i1c(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new MKi.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(Stu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new MKi.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return IAi(n)?[r,{type:"filenameWithData",filename:n.filename,data:uh.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>IAi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:uh.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new MKi.UnreachableCaseError(i.multipartType);return}}).filter(Gd))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new MKi.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new MKi.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Gd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Gd));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:bN_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?Fir(this.name):this.summary!=null?Fir(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function gN_(e,t){return VS(e)?uH(e,t,void 0):e}var CN_=ui(pz());var ON_="#/components/schemas/";function L9n(e){if(e.$ref.startsWith(ON_))return e.$ref.replace(ON_,"")}function jpi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function zAi(e){return typeof e.type=="string"&&e.type==="array"}function mN_(e){return e.type==="boolean"}function PN_(e){return e.type==="integer"}function xAi(e){return!Array.isArray(e.type)&&!zAi(e)}function jN_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||xAi(t)||zAi(t))}function wN_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function SN_(e){return e.type==="null"}function DN_(e){return e.type==="number"}function n1c(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function EN_(e){return e.type==="string"}var Ttu=class extends eoe{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new Jq({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return vA(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var Ctu=class extends x3{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new qFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var Btu=class extends eoe{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new Jq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Gd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>vA(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(Gd).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(l=>[...u,l]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(jpi).filter(Gd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function Itu(e){return e!=null&&e.length>0?e:[void 0]}var U9n=class extends eoe{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new Jq({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new Jq({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(VS(t))return L9n(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new Jq({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Gd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return F9n(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:vA(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Gd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>Itu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>uh.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=R3(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new Jq({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var ztu=class extends eoe{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>R3(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>R3(t,this.context.document)?.type!=="null"?new Jq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Gd);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=R3({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new Jq({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Gd);return this.isNullable&&n!=null?n.map(jpi).filter(Gd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:uh.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>vA(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??Fir(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Gd)).filter(Gd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>vA(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?Fir(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?Fir(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Gd)).filter(Gd)}:void 0,i=this.isNullable?jpi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var xtu=class extends x3{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var RAi=class extends x3{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(VS(r)){let n=R3(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(Gd),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var MN_=ui(pz());function e8E(e){return kwc.includes(e)}var Rtu=class extends x3{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(e8E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${kwc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new MN_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var Ntu=class extends x3{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return jpi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var AN_=ui(pz());function t8E(e){return Zwc.includes(e)}var Ftu=class extends x3{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(t8E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Zwc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new AN_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var qN_=ui(pz());function r8E(e){return e1c.includes(e)}var Ltu=class extends x3{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new qN_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(r8E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${e1c.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new RAi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var TN_=ui(pz());var Utu=class extends x3{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,TN_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var AKi=class extends eoe{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=L9n(this.input);let t=R3(this.input,this.context.document);t?.enum!=null&&xAi(t)&&(this.maybeEnumConverterNode=new RAi({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:uh.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=R3(this.input,this.context.document);if(r!=null)return new Jq({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var Jq=class e extends eoe{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new qFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),xAi(this.input)&&wN_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),VS(this.input)){let t=L9n(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new AKi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new Ctu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(jN_(this.input))this.typeShapeNode=new Btu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(xAi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new ztu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(n1c(this.input)&&this.input.allOf!=null)this.typeShapeNode=new U9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(xAi(this.input)&&this.input.enum!=null)this.typeShapeNode=new RAi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":n1c(this.input)&&(this.typeShapeNode=new U9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":zAi(this.input)&&(this.typeShapeNode=new Ttu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":mN_(this.input)&&(this.typeShapeNode=new xtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":PN_(this.input)&&(this.typeShapeNode=new Rtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":DN_(this.input)&&(this.typeShapeNode=new Ftu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":EN_(this.input)&&(this.typeShapeNode=new Ltu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":SN_(this.input)&&(this.typeShapeNode=new Ntu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new CN_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new U9n({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new Utu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!VS(this.input)&&(!zAi(this.input)&&this.input==null||zAi(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=vA(t)?.map(i=>this.nullable?jpi(i):i).filter(Gd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function NAi(e){if(e!=null)return F9n(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Gd))}var Vir=class extends x3{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;VS(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new qFe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new Jq({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=gN_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function BN_(e,t){return VS(e)?uH(e,t,void 0):e}var a1c=ui(pz());function Vtu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[uh.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var IN_=ui(dIs(),1),V9n=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=IN_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function i8E(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var W9n=class extends a_{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new Jq({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),i8E(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(VS(r)?n=ltu(r.$ref,this.context.document):n=r,n!=null)return[t,new R9n({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Gd)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[uh.api.latest.AuthSchemeId(t),i]}).filter(Gd)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=vA(r.convert());return n==null?[t,void 0]:[uh.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Gd(r))):void 0}}};var Wtu=class extends Jq{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=R3(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${VS(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=R3(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var Htu=class extends a_{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=R3(this.input.schema,this.context.document);this.availability=new qFe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=VS(this.input.schema)?new AKi({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=V9n.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new Jq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new Wtu({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Gd))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[dL]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[dL]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:vA(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=DHt([this.method,this.path,this.contentType,"request"].join("_"));return Vtu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uh.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new a1c.UnreachableCaseError(n);return}}).filter(Gd)}convert(){if(this.schema instanceof AKi)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:uh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:uh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=vA(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:uh.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new a1c.UnreachableCaseError(n.multipartType),[]}}).filter(Gd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var $tu=class extends a_{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=BN_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new Htu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>vA(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Gd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>vA(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Gd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var zN_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function xN_(e,t){if(VS(e)){let r=uH(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Gtu=ui(pz());var RN_="application/json";var NN_="application/octet-stream";function FN_(e,t){return e===t||t===dL||e===dL}var wRa=class extends a_{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,d]of Object.entries(r))for(let s of d)FN_(l,a)&&(i.add(l),this.examples?.push(new Uir({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,BAi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,l]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new Uir({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,BAi(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[l,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new Uir({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,BAi(d,a),{requestBody:l,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[l,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new Uir({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,BAi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[dL];if(a!=null)for(let u of a)this.examples?.push(new Uir({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,BAi(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let l=V9n.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=RN_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new Jq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(l?.isOctetStream())this.contentType=NN_,this.contentSubtype=R3(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new Jq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=gtu(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[dL]??=[],r[dL]=[{value:this.input.example}]);let i=R3(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=gtu(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[dL]??=[],r[dL]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[dL]??=[],r[dL]?.push(l!=null?{value:l}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let l of this.requests)a.push(...Object.entries(l.examples??{}).filter(([d])=>!n.has(d)&&d!==dL).map(([d,s])=>[l,d,s]));let u=Object.entries(r).filter(([l,d])=>!n.has(l)&&Gd(d)&&l!==dL);Object.keys(r).every(l=>l===dL)||this.matchExamplesByIndex(a,u),!n.has(dL)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return vA(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new Gtu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return vA(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=DHt([this.method,this.path,this.statusCode,"response"].join("_"));return Vtu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uh.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new Gtu.UnreachableCaseError(i);return}}).filter(Gd)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new Gtu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var SRa=class extends a_{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=xN_(this.input,this.context.document);if(r==null){this.context.errors.error({message:VS(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new Vir({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new wRa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new wRa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Gd)}};var Qtu=class extends a_{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new SRa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new SRa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return Itu(NAi(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(l=>l.convert()).filter(Gd))})))}).filter(Gd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=vA(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??zN_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(l=>{let d=l.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(Gd)})).filter(Gd)})).filter(Gd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var FAi=class extends a_{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new Uir({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,BAi(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new qFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=Lir(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new Atu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(VS(i)){let a=wtu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new Vir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new Vir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new Vir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new qtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new $tu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new Qtu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new N9n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new jRa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new jRa({input:{[utu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Mtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>Otu({namespace:vA(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Gd),this.xFernExamplesNode=new Etu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(Gd)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:uh.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(Gd),n=fN_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:lN_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:uh.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[c]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:NAi(this.queryParameters)?.flat(),headers:NAi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Gd)}}).filter(Gd);let a=this.servers?.map(o=>o.convert()).filter(Gd),u=this.convertPathToPathParts();if(u==null)return;let l,d=this.auth?.convert();d!=null&&(l=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(Gd);return this.endpointIds.map((o,c)=>({id:uh.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>uh.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>uh.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:NAi(this.pathParameters)?.flat(),queryParameters:NAi(this.queryParameters)?.flat(),requestHeaders:NAi(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var H9n=class extends a_{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=Lir(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new FAi({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new FAi({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new FAi({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new FAi({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new FAi({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Gd)}};function Jtu(e){return"payloads"in e}var Ktu=class extends a_{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new H9n({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:Lir(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Gd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{Jtu(a)?r[uh.WebhookId(a.id)]=a:t[uh.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var Ytu=class extends a_{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[RR_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||wtu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new Vir({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return F9n(this.globalHeaders,this.requiredProperties)?.flat()}};function LN_(e,t){if(VS(e)){let r=uH(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Xtu=class extends a_{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=LN_(a,this.context.document);if(u!=null)return new H9n({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Gd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{Jtu(i)&&(t[uh.WebhookId(i.id)]=i)}),t),{})}};var Ztu=class extends a_{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=Lir(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new N9n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new jtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new Ktu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new Xtu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new W9n({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new Ytu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=yae(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=ntu({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:uh.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var $9n=class extends z9n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function TFe(e){return typeof e=="object"&&Gd(e)&&"$ref"in e&&typeof e.$ref=="string"}function EHt(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(TFe(n)&&(n=EHt(n,t,r)),n)}function UN_(e,t){return TFe(e)?EHt(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var $N_=ui(pz());function wpi(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=wpi(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>wpi(t)):[wpi(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return wpi(e.oneOf[0]);if(e.anyOf?.[0]!=null)return wpi(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,wpi(r));return t}}function DRa(e,t){return TFe(e)?EHt(e,t,{name:"",schema:{type:"object"}}):e}function VN_(e,t){return TFe(e)?EHt(e,t,void 0):e}function WN_(e,t){return TFe(e)?EHt(e,t,void 0):e}function HN_(e,t){return TFe(e)?EHt(e,t,void 0):e}var n8E={key:uh.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},ktu=class extends $9n{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?DRa(this.method.result,this.context.openrpc):void 0,r=t?new Jq({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(l=>DRa(l,this.context.openrpc)).filter(Gd)?.map(l=>{let d=new Jq({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:uh.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(Gd),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(l=>{let d=WN_(l,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=VN_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Gd))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(Gd)??[];if(u.length<=0){let l=wpi({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=DRa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:wpi(DRa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:uh.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:uh.PropertyKey("apiKey")}],auth:void 0,pathParameters:[n8E],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(Gd):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(l=>l.convert()).filter(Gd),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=HN_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[uh.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=vA(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new $N_.UnreachableCaseError(u);return}}).filter(Gd)[0];if(n)return{statusCode:200,body:n,description:r}}};var ERa=class extends $9n{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=Lir(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=UN_(t,this.context.openrpc);r!=null&&this.methods.push(new ktu({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new W9n({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=yae(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Gd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=ntu({endpoints:n});return{id:uh.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var MRa=class extends otu{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function ARa(e,t){if(e instanceof pir){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof hR))return;let r=new uHt(e.absoluteFilePath),i=await yFe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let l={document:u.value,logger:t.logger,errors:new I9n,generatedTypes:{}},d=new Ztu({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=MIs(a,d.convert())}return a}var GN_=require("fs/promises");async function QN_(e,t){let r=await(0,GN_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new MRa({openrpc:i,logger:t.logger});return new ERa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function a8E(e){return e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function o8E(e){return/^(https?:)?\/\//.test(e)}async function u8E({pathToImage:e,absolutePathToFernFolder:t}){if(e==null||o8E(e))return;let r=Gv(t,Ra.of(e));if(await yf(r))return r}async function G9n({iconPath:e,filepaths:t,docsWorkspace:r}){if(a8E(e)){let i=await u8E({pathToImage:e,absolutePathToFernFolder:r.absoluteFilePath});i&&t.add(i)}}async function JN_({parsedDocsConfig:e,docsWorkspace:t}){let r=new Set;return e.logo?.dark!=null&&r.add(e.logo.dark),e.logo?.light!=null&&r.add(e.logo.light),e.favicon!=null&&r.add(e.favicon),e.backgroundImage?.dark!=null&&r.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&r.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&r.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&r.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&r.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(n=>{n.image!=null&&r.add(n.image)}),(await o1c({navigation:e.navigation,docsWorkspace:t})).forEach(n=>{r.add(n)}),e.js!=null&&e.js.files.forEach(n=>{r.add(n.absolutePath)}),r}async function o1c({navigation:e,docsWorkspace:t}){let r=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(i=>qRa({item:i,filepaths:r,docsWorkspace:t})));break;case"tabbed":await Promise.all(e.items.map(async i=>{i.icon!=null&&await G9n({iconPath:i.icon,filepaths:r,docsWorkspace:t}),i.child.type==="layout"&&i.child.layout!=null&&await Promise.all(i.child.layout.map(n=>qRa({item:n,filepaths:r,docsWorkspace:t})))}));break;case"versioned":await Promise.all(e.versions.map(async i=>{i.landingPage!=null&&await qRa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await o1c({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break;case"productgroup":await Promise.all(e.products.map(async i=>{i.landingPage!=null&&await qRa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await o1c({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break}return r}async function qRa({item:e,filepaths:t,docsWorkspace:r}){switch(e.type){case"page":e.icon!=null&&await G9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"section":e.icon!=null&&await G9n({iconPath:e.icon,filepaths:t,docsWorkspace:r}),await Promise.all(e.contents.map(i=>qRa({item:i,filepaths:t,docsWorkspace:r})));break;case"apiSection":e.icon!=null&&await G9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"link":e.icon!=null&&await G9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"changelog":e.icon!=null&&await G9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break}}async function KN_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){c8E(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await u1c({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await u1c({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function u1c({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await JYt(e,{alphabetized:Go,api:Go,apiName:Go,audiences:Go,displayErrors:Go,snippets:Go,summary:Go,title:Go,layout:Go,icon:Go,slug:Go,hidden:Go,skipSlug:Go,paginated:Go,playground:Go,flattened:Go,path:Go,page:Go,featureFlag:Go,openrpc:Go,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await u1c({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Go,orphaned:Go}),s8E(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function s8E(e){return e.api!=null}function c8E(e){return e[0]?.tab!=null}function nk(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}YN_.default.extend(XN_.default);var l8E=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),eru=0,f8E=async({ir:e})=>(eru++,`${e.apiName.snakeCase.unsafeName}-${eru}`),d8E=async({api:e})=>(eru++,`${e.id}-${eru}`),MHt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=l8E,d=f8E,s=d8E){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=ttu.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;async resolve(){this._parsedDocsConfig=await w6s({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await KN_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:o})=>{(await o.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(b=>{let g=zq(this.docsWorkspace.absoluteFilePath,b.absoluteFilepath);this.parsedDocsConfig.pages[g]=b.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ra.of(o)]=await Lgc({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ra.of(o)]=await Fgc({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});let i=await JN_({parsedDocsConfig:this.parsedDocsConfig,docsWorkspace:this.docsWorkspace});for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:b,markdown:g}=Pxa(c,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Ra.of(o)]=g;for(let O of b)i.add(O)}catch(b){throw this.taskContext.logger.error(`Failed to parse ${o}: ${b instanceof Error?b.message:String(b)}`),b}let n=Array.from(i).map(o=>({absoluteFilePath:o,relativeFilePath:this.toRelativeFilepath(o)}));(await this.uploadFiles(n)).forEach(o=>{this.collectedFileIds.set(o.absoluteFilePath,o.fileId)});let u=await this.getMarkdownFilesToFullyQualifiedPathNames();for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ra.of(o)]=Ngc(c,this.collectedFileIds,u,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let l={};Object.entries(this.parsedDocsConfig.pages).forEach(([o,c])=>{let b=p8E(this.editThisPage,o);l[gHt.PageId(o)]={markdown:c,editThisPageUrl:b?gHt.Url(b):void 0}});let d=await this.convertDocsConfiguration(),s={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let o=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let b=Gv(this.docsWorkspace.absoluteFilePath,c);(await(0,tru.stat)(b)).isDirectory()?(await hxe(b,"{js,ts,jsx,tsx,md,mdx}")).forEach(m=>{o.add(m)}):b.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&o.add(b)})),s=Object.fromEntries(await Promise.all([...o].map(async c=>{let b=this.toRelativeFilepath(c),g=(await(0,tru.readFile)(c)).toString();return[b,g]})))}return{config:d,pages:l,jsFiles:s}}resolveFilepath(t){if(t!=null)return Gv(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return zq(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,s1c.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,s1c.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(){let t={},r=Oo.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return Oo.NodeCollector.collect(r).slugMap.forEach((n,a)=>{if(n==null||!Oo.isPage(n))return;let u=Oo.getPageId(n);if(u==null)return;let l=Tu(this.docsWorkspace.absoluteFilePath,Ra.of(u));t[l]=a}),t}getDocsBasePath(){return new URL(nk(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?gHt.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(i=>({...i,url:gHt.Url(i.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(i=>({...i,value:gHt.Url(i.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:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}: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,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=Oo.V1.SlugGenerator.init(Oo.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,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,roles:this.parsedDocsConfig.roles?.map(n=>Oo.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return gCn(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),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Oo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??Bq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(u=>this.toProductNode(u,i)))}}async toProductNode(t,r){let i=r.setProductSlug(t.slug??Bq(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:wo(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Oo.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??Bq(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Oo.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?_8E(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(l)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return gCn(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let b=Gv(this.docsWorkspace.absoluteFilePath,Ra.of(t.openrpc));if(!await yf(b))throw new Error(`OpenRPC file does not exist at path: ${b}`);let g=await QN_(b,this.taskContext);if(g==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:g,apiName:t.apiName,snippetsConfig:rtu(t.snippetsConfiguration)}),new mRa(t,g,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let b=this.getOpenApiWorkspaceForApiSection(t),g=rtu(t.snippetsConfiguration),O=await ARa(b,this.taskContext);if(O==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:O,snippetsConfig:g,apiName:t.apiName}),new mRa(t,O,r,b,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=rtu(t.snippetsConfiguration),a,u,l=this.parsedDocsConfig.experimental?.openapiParserV3;if(l==null||l)try{a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}a==null&&(u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),a=gR({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new bR(this.taskContext,u)}));let s=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),o=PRa(a,s,{oauth:t.playground?.oauth});return new keu(t,o,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new mpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Oo.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=Oo.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??Bq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?Oo.PageId(a):void 0,l=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??Bq(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:l,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(c=>this.toNavigationChild(l,c,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return gCn(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new mpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,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:Oo.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??Bq(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,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):gHt.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:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(ev),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:gHt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return gCn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:gHt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function p8E(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${nk(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function _8E(e){switch(e){case"beta":return Oo.V1.NavigationV1Availability.Beta;case"deprecated":return Oo.V1.NavigationV1Availability.Deprecated;case"ga":return Oo.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Oo.V1.NavigationV1Availability.Stable;default:wo(e)}}async function sH(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof hR?t:null))).filter(ev)}async function c1c(e,t,r){if(e instanceof pir){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof hR))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return ik({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0}})}var K6_=ui(Eru(),1),ok=require("fs/promises"),Y6_=require("os"),X6_=ui(XX(),1),Z6_=ui(J6_(),1);var Hru=process.platform==="win32",uLE="etag",sLE="preview",cLE="app-preview",lLE="bundle",fLE=".next",dLE="standalone",pLE=".fern",_LE="packages/fern-docs/bundle/.next/server/instrumentation.js",hLE=".npmrc",yLE=".pnpmfile.cjs",vLE="pnpm-workspace.yaml",bLE='Cannot find matching keyid: {"signatures":';function gLE(){return Tu(pl.of((0,Y6_.homedir)()),Ra.of(pLE))}function $ru({app:e=!1}){return Tu(gLE(),Ra.of(e?cLE:sLE))}function $Ai({app:e=!1}){return Tu($ru({app:e}),Ra.of(e?fLE:lLE))}function YRa({app:e=!1}){return Tu($Ai({app:e}),Ra.of(dLE))}function OLE({app:e=!1}){return Tu(YRa({app:e}),Ra.of(_LE))}function mLE({app:e=!1}){return Tu(YRa({app:e}),Ra.of(vLE))}function PLE({app:e=!1}){return Tu(YRa({app:e}),Ra.of(yLE))}function jLE({app:e=!1}){return Tu(YRa({app:e}),Ra.of(hLE))}function zKi(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function wLE({app:e=!1}){return Tu($ru({app:e}),Ra.of(uLE))}var SLE=`packages:
2051
+ ]`;case 1:return`${n} Did you mean ${r[0]}?`;case 2:return`${n} Did you mean ${r[0]} or ${r[1]}?`;default:return`${n} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function EKi(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function v2E(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function C9n({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(l=>{if(l.type!=="endpoint"){a.push(l);return}let d=t(l.endpointId);if(d==null)throw new Error(`Endpoint ${l.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,l),o==null||o.isResponseStream===l.isResponseStream){a.push(l);return}let c=a.indexOf(o),b=l.isResponseStream?l:o,g=l.isResponseStream?o:l,O={id:Oo.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function Xeu({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return C9n({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function Nir(e,t){if(t!=null)return zq(e.absoluteFilePath,t)}function Zeu({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let l=Oo.V1.PageId(Nir(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Bq(t.title)});return{id:i.get(l),type:"page",pageId:l,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var keu=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=l,this.workspace=s,this.hideChildren=o,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Oo.V1.ApiDefinitionId(r.id),this.#e=qAi.create(r,a),this.#c=d,this.#f=this.apiSection.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Bq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#l(this.apiSection.navigation,this.#e.api.rootPackage,this.#u)),this.#s=this.#y(this.#s.map(b=>this.#j(b)),this.#w(this.#e.api.rootPackage,this.#u))}get(){let t=Oo.V1.followRedirects(this.#s),r=new mpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#g(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#l(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?qAi.getSubpackageId(r):void 0;return t.map(a=>vRa(a)._visit({link:u=>({id:this.#c.get(u.url),type:"link",title:u.text,icon:u.icon,url:Oo.Url(u.url)}),page:u=>this.#p(u,i),package:u=>this.#_(u,i),section:u=>this.#h(u,i),item:({value:u})=>this.#v(u,n,i),endpoint:u=>this.#O(u,n,i)})).filter(ev)}#p(t,r){return Zeu({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#c,hideChildren:this.hideChildren})}#_(t,r){let i=t.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=qAi.getSubpackageId(a),l=this.#c.get(i??`${this.apiDefinitionId}:${u}`);this.#a.has(u)&&this.taskContext.logger.warn(EKi(t.package)),this.#a.add(u),this.#o.set(l,[u]);let d=t.slug??(Rir(a)?a.urlSlug:this.apiSection.slug??Bq(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,a,s);return{id:l,type:"apiPackage",children:o,title:t.title??(Rir(a)?a.displayName??SHt(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(TAi(t.package,this.#e.subpackageLocators));let u=t.slug??Bq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#l(t.contents,void 0,l);return{id:this.#c.get(i??`${this.apiDefinitionId}:${Bq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#h(t,r){let i=t.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#c.get(i??n??r.get()),l=t.referencedSubpackages.map(c=>{let b=this.#e.getSubpackageByIdOrLocator(c),g=b!=null?qAi.getSubpackageId(b):void 0;if(g===void 0){this.taskContext.logger.error(TAi(c,this.#e.subpackageLocators));return}return{subpackageId:g,locator:c}}).filter(c=>c!=null).filter(ev);this.#o.set(u,l.map(c=>c.subpackageId)),l.forEach(c=>{this.#a.has(c.subpackageId)&&this.taskContext.logger.error(EKi(c.locator)),this.#a.add(c.subpackageId)});let d=t.slug??Bq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#v(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(p_(t));if(n!=null){let a=qAi.getSubpackageId(n),u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(EKi(t)),this.#a.add(a),this.#o.set(u,[a]);let l=Rir(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:Rir(n)?n.displayName??SHt(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,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,featureFlags:void 0}}return this.#O({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,featureFlags:void 0},r,i)}#O(t,r,i){let n=(r!=null?this.#e.subpackages.get(k6.SubpackageId(r))?.endpoints.get(k6.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let l=this.#e.getEndpointId(n);if(l==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${DKi(n.method,n.path.parts)}. Got undefined.`);else{this.#t.has(l)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${l}`),this.#t.add(l);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#c.get(`${this.apiDefinitionId}:${l}`),type:"endpoint",method:n.method,endpointId:l,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??PC(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let a=(r!=null?this.#e.subpackages.get(k6.SubpackageId(r))?.webSockets.get(k6.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let l=this.#e.getWebSocketId(a);if(l==null)this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);else return this.#r.has(l)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${l}`),this.#r.add(l),{id:this.#c.get(`${this.apiDefinitionId}:${l}`),type:"webSocket",webSocketId:l,title:t.title??a.name??PC(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(a.availability),playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(k6.SubpackageId(r))?.webhooks.get(k6.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Oo.V1.WebhookId(t.endpoint));if(u!=null){let l=this.#e.getWebhookId(u);if(l==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#n.has(l)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${l}`),this.#n.add(l),{id:this.#c.get(`${this.apiDefinitionId}:${l}`),type:"webhook",webhookId:l,method:u.method,title:t.title??u.name??lb("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return Xeu({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>PC(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#j(t){return bRa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#m(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#w(t,r){let i=[];return t.endpoints.forEach(n=>{if(n.protocol?.type==="grpc"){let a=this.#e.getGrpcId(n);if(a==null){this.taskContext.logger.error(`Expected Grpc ID for ${n.id} at path: ${DKi(n.method,n.path.parts)}. Got undefined.`);return}if(this.#i.has(a))return;let u=r.apply(n);i.push({id:Oo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"grpc",grpcId:a,title:n.name??PC(n.path.parts),method:n.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:void 0,slug:u.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let a=this.#e.getEndpointId(n);if(a==null){this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${DKi(n.method,n.path.parts)}. Got undefined.`);return}if(this.#t.has(a))return;let u=r.apply(n);i.push({id:Oo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??PC(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null){this.taskContext.logger.error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return}this.#r.has(a)||i.push({id:Oo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??PC(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null){this.taskContext.logger.error(`Expected Webhook ID for ${n.id}. Got undefined.`);return}this.#n.has(a)||i.push({id:Oo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??SHt(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#a.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=Rir(a)?r.apply(a):r,l=this.#m(n,u);l.length>0&&i.push({id:Oo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:Rir(a)?a.displayName??SHt(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,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,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#m(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(TAi(t||"unknown",[])),[]):this.#w(i,r)}#g(t){return Yeu(t)}mergeEndpointPairs(t){return C9n({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>PC(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var etu=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[p_(r).toLowerCase()]=i,this.#e[`subpackage_${p_(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${lb(a.baseUrl,PC(i.path))}`]=i,this.#r[`${n} ${lb(a.baseUrl,MFe(i.path))}`]=i;let u=Keu(a);u!=null&&(this.#r[`${n} ${lb(u,PC(i.path))}`]=i,this.#r[`${n} ${lb(u,MFe(i.path))}`]=i)}),this.#r[`${i.method} ${PC(i.path)}`]=i,this.#r[`${i.method} ${MFe(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${PC(i.path)}`]=i,this.#n[`STREAM ${MFe(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}get subpackageLocators(){return new Set(Object.keys(this.#e))}};function ORa({item:e,parentSlug:t}){return t.apply({urlSlug:Bq(e.id.split(".").pop()??"")}).get()}var mRa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;#l=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=d,this.hideChildren=o,this.#e=r,this.#t=new etu(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Oo.V1.ApiDefinitionId(r.id),this.#c=s,this.#f=this.apiSection.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Bq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#p(this.apiSection.navigation,void 0,this.#u)),this.#s=this.#j(this.#s.map(b=>this.#w(b)),this.#m(this.#e,this.#u))}get(){let t=Oo.V1.followRedirects(this.#s),r=new mpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#p(t,r,i){return t.map(n=>vRa(n)._visit({link:a=>({id:this.#c.get(a.url),type:"link",title:a.text,icon:a.icon,url:Oo.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#h(a,i),section:a=>this.#v(a,i),item:({value:a})=>this.#O(a,r,i),endpoint:a=>this.#y(a,r,i)})).filter(ev)}#_(t,r){return Zeu({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#c,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#h(t,r){let i=t.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#c.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let l=t.slug??Bq(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#p(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??SHt(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(a.id,o),o}else{this.taskContext.logger.warn(TAi(t.package,this.#t.subpackageLocators));let u=t.slug??Bq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#p(t.contents,t.package,l),s={id:this.#c.get(i??`${this.apiDefinitionId}:${Bq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(t.package,s),s}}#v(t,r){let i=t.overviewAbsolutePath!=null?Oo.V1.PageId(Nir(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#c.get(i??n??r.get()),u=t.referencedSubpackages.map(b=>{let g=this.#t.getSubpackageByLocator(b);if(g==null){this.taskContext.logger.error(TAi(b,this.#t.subpackageLocators));return}return{subpackageId:g.id,locator:b}}).filter(b=>b!=null).filter(ev),l=u.map(b=>b.subpackageId);this.#o.set(a,l),u.forEach(b=>{this.#a.has(b.subpackageId)&&this.taskContext.logger.error(EKi(b.locator)),this.#a.add(b.subpackageId)});let d=t.slug??Bq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#p(t.contents,t.title,s),c={id:a,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return l.forEach(b=>{this.#l.set(b,c)}),c}#O(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.warn(EKi(t)),this.#a.add(a),this.#o.set(u,[a]);let l=Bq(n.name),d=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??SHt(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,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,featureFlags:void 0};return this.#l.set(a,s),s}return this.#y({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,featureFlags:void 0},r,i)}#y(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null)if(this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),n.id==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${DKi(n.method,n.path)}. Got undefined.`);else{this.#r.add(n.id);let l=t.slug!=null?i.append(t.slug).get():ORa({item:n,parentSlug:i});return{id:this.#c.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??PC(n.path),slug:l,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null)if(this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),a.id==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}else return this.#n.add(a.id),{id:this.#c.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??PC(a.path),slug:t.slug!=null?i.append(t.slug).get():ORa({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null)if(this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),u.id==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#i.add(u.id),{id:this.#c.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??lb("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():ORa({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return Xeu({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>PC(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#w(t){return bRa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#E(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#m(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#g(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Endpoint ID for ${a.id} at path: ${DKi(a.method,a.path)}. Got undefined.`);return}!this.#r.has(YA.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#P(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}!this.#n.has(YA.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#A(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}!this.#i.has(YA.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)}),i}#g(t,r,i){let n=Oo.V1.SlugGenerator.init(i.get()).apply({urlSlug:Bq(r.name)}),a=this.#E(t,n),u={id:Oo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??SHt(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,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,featureFlags:void 0};return this.#l.set(t,u),a.length>0?u:void 0}#D(t,r,i,n){r.slug=ORa({item:t,parentSlug:i}),n.push(r)}#P(t,r,i,n){let a={id:Oo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:YA.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??PC(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#A(t,r,i,n){let a={id:Oo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:YA.WebSocketId(t),title:r.displayName??PC(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Oo.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#d(t,r,i,n){let a={id:Oo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:YA.WebhookId(t),method:r.method,title:r.displayName??SHt(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,l])=>t===this.#e.id?l.id.split(".").length===1:l.id!=null&&l.id.includes(t)&&l.id!==t&&l.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===YA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===YA.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===YA.api.v1.SubpackageId(t)));return{id:YA.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#E(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(TAi(t||"unknown",[])),[]):this.#m(i,r)}#S(t){return Yeu(t)}mergeEndpointPairs(t){return C9n({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>PC(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var fx_=ui(require("crypto"),1);function b2E(e){return fx_.default.createHash("sha256").update(e).digest("hex")}var ttu=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),b2E(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Oo.V1.NodeId(this.#n(t))}};function rtu(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,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var itu=ui(AEe(),1);var hwc=ui(AEe(),1);function dx_(e,t,r){if(e.schemes.length>0&&e.schemes[0]!=null){let i=e.schemes[0];switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix,description:e.docs};case"oauth":{let n=i.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:hwc.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:hwc.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:wo(i)}}}var lm=ui(AEe(),1);var CAi=ui(AEe(),1);function _x_(e){return e._visit({alias:t=>({type:"alias",value:wE(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:i4(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>CAi.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:CAi.FernRegistry.PropertyKey(r.name.wireValue),valueType:wE(r.valueType),availability:i4(r.availability),propertyAccess:r.propertyAccess})),extraProperties:m2E(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:CAi.FernRegistry.PropertyKey(i.name.wireValue),valueType:wE(i.valueType),availability:i4(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?i4(i.availability):void 0,additionalProperties:Us.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[CAi.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:CAi.FernRegistry.PropertyKey(n.name.wireValue),valueType:wE(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.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:wE(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function wE(e){return e._visit({container:t=>Us.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:wE(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:wE(r),valueType:wE(i)}),optional:r=>({type:"optional",itemType:wE(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:wE(r)}),set:r=>({type:"set",itemType:wE(r)}),literal:r=>Us.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:CAi.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Us.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>O2E(t.v2),float:()=>px_(t.v2),double:()=>px_(t.v2),string:()=>g2E(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),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 g2E(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function O2E(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 px_(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 m2E(e){return typeof e=="boolean"?e?Kc.unknown():void 0:typeof e=="string"?{type:"id",value:CAi.FernRegistry.TypeId(e),default:void 0}:wE(e)}function vwc(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?j2E(r,t):[],webhooks:i!=null?P2E(i):[],websockets:n!=null?[w2E(n,t)]:[],types:e.types.map(a=>lm.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>lm.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?lm.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function P2E(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(i=>({payload:i.payload.jsonExample}))??[]),{description:t.docs??void 0,id:lm.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??gUi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:wE(i.valueType),availability:i4(i.availability)})),payload:T2E(t.payload),examples:r}})}function j2E(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let l,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,o=Object.keys(d).length>1;for(let[b,g]of Object.entries(d))l=yx_({shouldUseExampleName:o,exampleName:g.displayName??b,example:g,irEndpoint:i}),l!=null&&a.push(l);let c=Object.keys(s).length>1;for(let[b,g]of Object.entries(s))l=yx_({shouldUseExampleName:c,exampleName:g.displayName??b,example:g,irEndpoint:i}),l!=null&&a.push(l)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>ywc({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(ev));else if(n!=null){let l=ywc({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=tCa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=ywc({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:i4(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:M2E(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?lm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?S2E({environmentsConfig:t.environments,endpoint:i}):void 0,id:lm.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??gUi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:lm.FernRegistry.PropertyKey(l.name.originalName),type:wE(l.valueType),availability:void 0})),parts:[...B9n(i.basePath),...B9n(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:lm.FernRegistry.PropertyKey(l.name.originalName),type:wE(l.valueType),availability:void 0})),parts:[...t.basePath!=null?B9n(t.basePath):[],...B9n(e.basePath),...B9n(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:wE(l.valueType),availability:i4(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:wE(l.valueType),availability:i4(l.availability)})),request:i.requestBody!=null?A2E(i.requestBody):void 0,response:i.response!=null?hx_(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(hx_).filter(ev)},errors:void 0,errorsV2:q2E(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:l=>({type:"grpc",methodName:i.id,methodType:l.methodType}),_other:()=>{}})};r.push(u)}return r}function w2E(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(u=>({type:lm.FernRegistry.api.v1.WebSocketMessageId(u.type),body:u.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[lm.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:lm.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:i4(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?lm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?D2E({environmentsConfig:t.environments,channel:e}):[],id:lm.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??gUi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:lm.FernRegistry.PropertyKey(i.name.originalName),type:wE(i.valueType),availability:void 0})),parts:B9n(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:wE(i.valueType),description:i.docs,availability:i4(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:wE(i.valueType),availability:i4(i.availability)})),messages:e.messages.map(i=>({type:lm.FernRegistry.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:C2E(i.body),description:i.docs,availability:i4(i.availability)})),examples:r}}function i4(e){if(e!=null)switch(e.status){case"DEPRECATED":return lm.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return lm.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return lm.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return lm.FernRegistry.Availability.Beta;default:wo(e.status)}}function S2E({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:lm.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(u=>r.environments.map(l=>{let d=l.urls[u];if(d==null)throw new Error(`Expected environment ${l.id} to contain url for ${u}`);return{id:lm.FernRegistry.EnvironmentId(u),baseUrl:d}})).filter((u,l,d)=>l===d.findIndex(s=>s.id===u.id&&s.baseUrl===u.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let u=a.urls[i];if(u==null)throw new Error(`Expected environment ${a.id} to contain url for ${i}`);return{id:lm.FernRegistry.EnvironmentId(a.id),baseUrl:u}});default:wo(r)}}function D2E({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:lm.FernRegistry.EnvironmentId(n.id),baseUrl:E2E(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:lm.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:wo(r)}}function E2E(e,t){return e.replace(/^[^:]+/,t)}function M2E(e){return Us.http.HttpMethod._visit(e,{get:()=>lm.FernRegistry.HttpMethod.Get,post:()=>lm.FernRegistry.HttpMethod.Post,put:()=>lm.FernRegistry.HttpMethod.Put,patch:()=>lm.FernRegistry.HttpMethod.Patch,delete:()=>lm.FernRegistry.HttpMethod.Delete,head:()=>lm.FernRegistry.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function B9n(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:lm.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function A2E(e){let t=Us.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??hM.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>lm.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:lm.FernRegistry.PropertyKey(i.name.wireValue),valueType:wE(i.valueType),availability:i4(i.availability),propertyAccess:void 0})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??hM.APPLICATION_JSON,shape:{type:"reference",value:wE(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(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:lm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:lm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:lm.FernRegistry.PropertyKey(n.name.wireValue),valueType:wE(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:i4(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(ev)},contentType:r.contentType,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 hx_(e){if(e.body==null)return;let t,r=Us.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:wE(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:wE(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:wE(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function q2E(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:wE(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:B2E(n)})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:lm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:lm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:wE(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function yx_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i}){if(r==null)return;let n=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:r.request?.headers??{},requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:a=>{if(r.request==null)return;let u={};if(Qj(r.request.requestBody)){let l=r.request.requestBody;for(let d of a.properties)d._visit({file:s=>{let o=l[s.key.wireValue];if(s.type==="file")u[s.key.wireValue]={type:"filename",value:typeof o=="string"?o:"<file1>"};else if(s.type==="fileArray"){let c=(Array.isArray(o)?o:[o]).filter(b=>typeof b=="string");u[s.key.wireValue]={type:"filenames",value:c}}},bodyProperty:s=>{if(s.style==="exploded"){let o=l[s.name.wireValue];u[s.name.wireValue]={type:"exploded",value:Array.isArray(o)?o:[o]}}else u[s.name.wireValue]={type:"json",value:l[s.name.wireValue]}},_other:kze})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:n??void 0,responseBodyV3:n!=null?r.response?.body?._visit({json:a=>({type:"json",value:a}),stream:a=>({type:"stream",value:a.map(u=>({type:"json",value:u}))}),error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(a=>({name:a.name,description:a.docs??void 0,install:void 0,language:a.language,code:a.code})).filter(ev)}}function ywc({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(l=>{let d=l.valueType.type==="container"&&l.valueType.container.type==="literal"?l.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:l.name,value:{jsonExample:d,shape:Us.ExampleTypeReferenceShape.primitive(Us.ExamplePrimitive.string({original:d}))}}}).filter(ev),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((l,d)=>(l[lm.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,l),{}),queryParameters:a.queryParameters.reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),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:l=>{if(a.request==null)return;let d={};if(Qj(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of l.properties)o._visit({file:c=>{let b=s[c.key.wireValue];if(c.type==="file")d[c.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(c.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];d[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:kze})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Us.http.ExampleResponse._visit(a.response,{ok:l=>l._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: "+l.type)}}),error:({error:l})=>{let d=i.errors[l.errorId];if(d==null)throw new Error("Cannot find error "+l.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:l=>l._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:l=>l.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:l=>l._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:l=>l.body!=null?{type:"json",value:l.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(l=>TEe._visit(l,{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(ev)}}function T2E(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>lm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:lm.FernRegistry.PropertyKey(t.name.wireValue),valueType:wE(t.valueType),availability:i4(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:wE(e.payloadType)},description:e.docs};default:wo(e)}}function C2E(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>lm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:lm.FernRegistry.PropertyKey(t.name.wireValue),valueType:wE(t.valueType),availability:i4(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:wE(e.bodyType)};default:wo(e)}}function B2E(e){let t=e.v2Examples?.userSpecifiedExamples,r=e.v2Examples?.autogeneratedExamples,i=e.examples;return t!=null&&Object.keys(t).length>0?Object.entries(t).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):r!=null&&Object.keys(r).length>0?Object.entries(r).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):i.length>0?i.map(n=>({name:n.name?.originalName,responseBody:{type:"json",value:n.jsonExample},description:n.docs})):[]}function ik({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:vwc(e.rootPackage,e),auth:dx_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:i4(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:wE(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[itu.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:_x_(a.shape),availability:i4(a.availability),displayName:a.name.displayName};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[itu.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:itu.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName??a.displayName,name:a.name.originalName,description:a.docs??void 0,...vwc(a,e)}}return i}var bwc=ui(AEe(),1);async function gwc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=gR({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new bR(r,t)}),d=QWi({token:i.value}),s=ik({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:bwc.FernRegistry.OrgId(e),apiId:bwc.FernRegistry.ApiId(l.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:l};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 I2E=new hKi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function PRa(e,t,r){return Gxa(Wxa(ik({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),k6.ApiDefinitionId(t),I2E))}var uh={};Po(uh,{AlgoliaSearchIndex:()=>vx_,ApiDefinitionId:()=>Nx_,ApiId:()=>Vx_,Availability:()=>iR_,DocsConfigId:()=>Wx_,EndpointId:()=>$x_,EndpointPathLiteral:()=>tR_,EnvironmentId:()=>Hx_,FileId:()=>Yx_,HttpMethod:()=>rR_,IndexSegmentId:()=>bx_,JqString:()=>Zx_,OrgId:()=>Lx_,PageId:()=>Kx_,PayloadLocation:()=>qR_,PropertyKey:()=>kx_,PullRequestState:()=>SR_,RoleId:()=>eR_,TokenId:()=>Ux_,TypeId:()=>Jx_,Url:()=>Xx_,VersionId:()=>Fx_,WebSocketId:()=>Gx_,WebhookId:()=>Qx_,algolia:()=>Owc,api:()=>qwc,commons:()=>Twc,diff:()=>nR_,docs:()=>Lwc,generators:()=>Vwc,git:()=>Wwc,navigation:()=>Gwc,sdks:()=>Jwc,snippets:()=>MR_,snippetsFactory:()=>AR_,templates:()=>Kwc,tokens:()=>TR_});var Owc={};Po(Owc,{AlgoliaSearchIndex:()=>vx_,IndexSegmentId:()=>bx_});function vx_(e){return e}function bx_(e){return e}var qwc={};Po(qwc,{latest:()=>jwc,v1:()=>Awc});var jwc={};Po(jwc,{AuthSchemeId:()=>gx_,WebhookHttpMethod:()=>jx_,auth:()=>mwc,commons:()=>Ox_,endpoint:()=>mx_,type_:()=>Px_,webhook:()=>Pwc,websocket:()=>wx_});var mwc={};Po(mwc,{AuthSchemeId:()=>gx_});function gx_(e){return e}var Ox_={};var mx_={};var Px_={};var Pwc={};Po(Pwc,{WebhookHttpMethod:()=>jx_});var jx_={Get:"GET",Post:"POST"};var wx_={};var Awc={};Po(Awc,{SubpackageId:()=>Ix_,WebSocketMessageId:()=>zx_,WebSocketMessageOrigin:()=>xx_,WebhookHttpMethod:()=>Rx_,commons:()=>Mwc,db:()=>wwc,read:()=>Dwc,register:()=>Ewc});var wwc={};Po(wwc,{endpoint:()=>Sx_});var Sx_={};var Dwc={};Po(Dwc,{SupportedLanguage:()=>Dx_,endpoint:()=>Swc,type_:()=>Ex_,webhook:()=>Mx_,websocket:()=>Ax_});var Swc={};Po(Swc,{SupportedLanguage:()=>Dx_});var Dx_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var Ex_={};var Mx_={};var Ax_={};var Ewc={};Po(Ewc,{SourceId:()=>z2E,endpoint:()=>qx_,type_:()=>Tx_,webhook:()=>Cx_,websocket:()=>Bx_});var qx_={};var Tx_={};var Cx_={};var Bx_={};function z2E(e){return e}var Mwc={};Po(Mwc,{SubpackageId:()=>Ix_,WebSocketMessageId:()=>zx_,WebSocketMessageOrigin:()=>xx_,WebhookHttpMethod:()=>Rx_});function Ix_(e){return e}function zx_(e){return e}var xx_={Client:"client",Server:"server"};var Rx_={Get:"GET",Post:"POST"};var Twc={};Po(Twc,{ApiDefinitionId:()=>Nx_,ApiId:()=>Vx_,Availability:()=>iR_,DocsConfigId:()=>Wx_,EndpointId:()=>$x_,EndpointPathLiteral:()=>tR_,EnvironmentId:()=>Hx_,FileId:()=>Yx_,HttpMethod:()=>rR_,JqString:()=>Zx_,OrgId:()=>Lx_,PageId:()=>Kx_,PropertyKey:()=>kx_,RoleId:()=>eR_,TokenId:()=>Ux_,TypeId:()=>Jx_,Url:()=>Xx_,VersionId:()=>Fx_,WebSocketId:()=>Gx_,WebhookId:()=>Qx_});function Nx_(e){return e}function Fx_(e){return e}function Lx_(e){return e}function Ux_(e){return e}function Vx_(e){return e}function Wx_(e){return e}function Hx_(e){return e}function $x_(e){return e}function Gx_(e){return e}function Qx_(e){return e}function Jx_(e){return e}function Kx_(e){return e}function Yx_(e){return e}function Xx_(e){return e}function Zx_(e){return e}function kx_(e){return e}function eR_(e){return e}function tR_(e){return e}var rR_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var iR_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var nR_={};var Lwc={};Po(Lwc,{latest:()=>Iwc,v1:()=>Nwc,v2:()=>Fwc});var Iwc={};Po(Iwc,{Layout:()=>oR_,MdxEngine:()=>x2E,TwitterCardSetting:()=>uR_,commons:()=>aR_,frontmatter:()=>Cwc,seo:()=>Bwc});var x2E={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var aR_={};var Cwc={};Po(Cwc,{Layout:()=>oR_});var oR_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var Bwc={};Po(Bwc,{TwitterCardSetting:()=>uR_});var uR_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Nwc={};Po(Nwc,{commons:()=>Rwc,db:()=>sR_,read:()=>cR_,write:()=>zwc});var sR_={};var cR_={};var zwc={};Po(zwc,{DocsRegistrationId:()=>N2E,FilePath:()=>R2E});function R2E(e){return e}function N2E(e){return e}var Rwc={};Po(Rwc,{ContentAlignment:()=>pR_,FontDisplay:()=>bR_,FontStyle:()=>vR_,HeaderPosition:()=>_R_,JsScriptStrategy:()=>yR_,ProgrammingLanguage:()=>lR_,SearchbarPlacement:()=>fR_,TabsPlacement:()=>dR_,TwitterCardSetting:()=>hR_,commons:()=>xwc});var xwc={};Po(xwc,{ContentAlignment:()=>pR_,FontDisplay:()=>bR_,FontStyle:()=>vR_,HeaderPosition:()=>_R_,JsScriptStrategy:()=>yR_,ProgrammingLanguage:()=>lR_,SearchbarPlacement:()=>fR_,TabsPlacement:()=>dR_,TwitterCardSetting:()=>hR_});var lR_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var fR_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var dR_={Header:"HEADER",Sidebar:"SIDEBAR"};var pR_={Center:"CENTER",Left:"LEFT"};var _R_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var hR_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var yR_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var vR_={Normal:"normal",Italic:"italic"};var bR_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Fwc={};Po(Fwc,{read:()=>gR_,write:()=>OR_});var gR_={};var OR_={};var Vwc={};Po(Vwc,{ChangelogEntryType:()=>PR_,GeneratorId:()=>F2E,GeneratorLanguage:()=>L2E,ReleaseType:()=>jR_,cli:()=>mR_,commons:()=>Uwc,versions:()=>wR_});var mR_={};var Uwc={};Po(Uwc,{ChangelogEntryType:()=>PR_,ReleaseType:()=>jR_});var PR_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var jR_={Ga:"GA",Rc:"RC"};var wR_={};function F2E(e){return e}var L2E={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Wwc={};Po(Wwc,{PullRequestState:()=>SR_});var SR_={Open:"open",Closed:"closed",Merged:"merged"};var Gwc={};Po(Gwc,{latest:()=>Hwc,v1:()=>$wc});var Hwc={};Po(Hwc,{NodeId:()=>W2E,ProductId:()=>H2E,Slug:()=>U2E,TabId:()=>V2E});function U2E(e){return e}function V2E(e){return e}function W2E(e){return e}function H2E(e){return e}var $wc={};Po($wc,{NavigationV1Availability:()=>K2E,NodeId:()=>Q2E,ProductId:()=>J2E,Slug:()=>$2E,TabId:()=>G2E});function $2E(e){return e}function G2E(e){return e}function Q2E(e){return e}function J2E(e){return e}var K2E={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Jwc={};Po(Jwc,{Language:()=>DR_,VersionBump:()=>ER_,versions:()=>Qwc});var Qwc={};Po(Qwc,{Language:()=>DR_,VersionBump:()=>ER_});var DR_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var ER_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var MR_={};var AR_={};var Kwc={};Po(Kwc,{PayloadLocation:()=>qR_});var qR_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var TR_={};var I9n=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Gd(e){return e!=null}var BR_=ui(UCn(),1);var CR_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function Fir(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,BR_.default)(e,{special:CR_}).replace(/V\s(\d)/g,"V$1")}function ntu({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],l=uh.api.v1.SubpackageId(u.join("."));r[l]={id:l,name:a,displayName:Fir(a)},n.push(a)})}),r}var atu=class{errors=new I9n},z9n=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function IR_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var otu=class extends atu{},a_=class extends z9n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,l)=>u===this.accessPath[this.accessPath.length-a.length+l])||this.accessPath.push(...a)}r.logger.debug(`Processing ${IR_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},x3=class extends a_{},eoe=class extends x3{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var zR_="x-fern-base-path",xR_="x-fern-availability",utu="x-fern-sdk-group-name",RR_="x-fern-global-headers",NR_="x-fern-sdk-method-name";var FR_="x-fern-webhook",LR_="x-fern-access-token-locator",UR_="x-fern-basic",VR_="x-fern-username-variable-name",WR_="x-fern-password-variable-name",HR_="x-fern-bearer",$R_="x-fern-token-variable-name",GR_="x-fern-header",QR_="x-fern-header-variable-name",JR_="x-fern-server-name",KR_="x-fern-examples";var stu=class extends a_{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[JR_]}convert(){if(this.serverName!=null)return this.serverName}};var ctu=class extends a_{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new stu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:uh.EnvironmentId(t),baseUrl:this.url}}};function Lir(e,t,r,i){let n=e??[],a=new Set(n.map(l=>l.url)),u=(t??[]).filter(l=>!a.has(l.url)).map((l,d)=>new ctu({input:l,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function VS(e){return typeof e=="object"&&Gd(e)&&"$ref"in e&&typeof e.$ref=="string"}function uH(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(VS(n)&&(n=uH(n,t,r)),n)}function ltu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return VS(r)?uH(r,t,void 0):r}var uN_=ui(pz());var ftu=class extends a_{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[UR_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var dtu=class extends a_{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[WR_]}convert(){return this.passwordVariableName}};var ptu=class extends a_{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[VR_]}convert(){return this.usernameVariableName}};var _tu=class extends a_{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[HR_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var htu=class extends a_{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[$R_]}convert(){return this.tokenVariableName}};function YR_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var XR_="x-bearer-format",ZR_="x-code-samples",kR_="x-codeSamples";var ytu=class extends a_{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[XR_]}convert(){return this.bearerFormat}};var vtu=class extends a_{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[GR_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var btu=class extends a_{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[QR_]}convert(){return this.headerVariableName}};function eN_(e){return e.type==="apiKey"}var x9n=class extends a_{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){eN_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new vtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new btu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new ytu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function tN_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function rN_(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function iN_(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let l=e[i];a?l==="\\"&&i+1<r?(i++,n+=e[i]):l===a?a="":n+=l:u?l==='"'||l==="'"?a=l:l==="]"?(u=!1,t.push(n),n=""):n+=l:l==="["?(u=!0,n&&(t.push(n),n="")):l==="."?n&&(t.push(n),n=""):n+=l,i++}return n&&t.push(n),t}function Ywc(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?tN_(t)?Ywc(e,iN_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=rN_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return Y2E(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function Y2E(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null)return r;i=i[t[n]]}return i===void 0?r:i}function nN_(e){return function(t){return Ywc(t,e)}}function Xwc(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Xwc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function gtu(e,t){switch(t=t??tC_,typeof t){case"string":case"symbol":case"number":case"object":return oL(e,nN_(t));case"function":return oL(e,t)}}function aN_(e){return typeof e!="string"&&(e=Xwc(e)),e.replace(/['\u2019]/g,"")}function DHt(e){return qE_(aN_(e))}function vA(e){if(e!=null)return Array.isArray(e)?e:[e]}function Otu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let l=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&l==null))return`${X2E(u)}${Z2E(e)}.${k2E(i,n,a,l)}`}function X2E(e){return e?"webhook_":"endpoint_"}function Z2E(e){return e!=null?vA(e)?.map(t=>DHt(t)).join("/"):""}function k2E(e,t,r,i){return e||t||DHt(r??"")||DHt(i??"")}function oN_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var mtu=class extends a_{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[LR_],this.accessTokenLocator!=null&&(oN_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var Ptu=class extends a_{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new x9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new mtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=Otu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:uh.EndpointId(r),accessTokenLocator:uh.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var R9n=class extends a_{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new ftu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new ptu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new dtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new _tu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new htu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{YR_(this.input)?(this.authScheme="header",this.headerAuthNode=new x9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new Ptu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new uN_.UnreachableCaseError(this.authScheme);return}}};var N9n=class extends a_{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=ltu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new R9n({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(Gd))}};var jtu=class extends a_{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[zR_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function sN_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function cN_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function F9n(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>vA(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!sN_(n))&&(u=cN_(u,u.type==="enum"?u.default:void 0)),{key:uh.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(Gd)).filter(Gd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function wtu(e,t){return VS(e)?uH(e,t,void 0):e}function BAi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function lN_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function fN_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var dN_=ui(pz());var Zwc=["decimal","decimal128","double-int","double","float","sf-decimal"],kwc=["int16","int32","int64","int8","sf-integer","uint8"],e1c=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],t1c=["beta","pre-release","in-development","generally-available","deprecated"];function R3(e,t){return VS(e)?uH(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var qFe=class extends a_{availability;constructor(t){super(t),this.safeParse()}parse(){if(R3(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[xR_];r!=null&&(t1c.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${t1c.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return uh.Availability.Beta;case"in-development":return uh.Availability.InDevelopment;case"generally-available":return uh.Availability.GenerallyAvailable;case"deprecated":return uh.Availability.Deprecated;case void 0:return;default:new dN_.UnreachableCaseError(this.availability);return}}};var Dtu=ui(pz());function pN_(e){return typeof e=="object"&&e!=null&&"language"in e}function _N_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function hN_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function yN_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Stu(e){return typeof e=="object"&&e!=null&&"event"in e}function r1c(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Stu)}function IAi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function vN_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var Etu=class extends a_{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[KR_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return IAi(u)?[n,{type:"filenameWithData",filename:u.filename,data:uh.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>IAi(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:uh.FileId(l.data)}))}];if(u.every(l=>typeof l=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new Dtu.UnreachableCaseError(a.multipartType);return}}).filter(Gd))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=vN_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new Dtu.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{hN_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{r1c(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!r1c(r.response)&&yN_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new Dtu.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{pN_(c)?c.language!=null&&(l[c.language]??=[],l[c.language]?.push({name:c.name,language:c.language,install:c.install,code:c.code,generated:!1,description:c.docs})):_N_(c)&&c.sdk!=null&&(l[c.sdk]??=[],l[c.sdk]?.push({name:c.name,language:c.sdk,install:void 0,code:c.code,generated:!1,description:c.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([c,b])=>[uh.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[uh.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[uh.PropertyKey(c),b]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:l}}))}};var jRa=class extends a_{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[utu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>uh.api.v1.SubpackageId(DHt(r)))}};var Mtu=class extends a_{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[NR_]}convert(){return this.sdkMethodName}};var Atu=class extends a_{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[FR_]}convert(){return this.isWebhook}};var qtu=class extends a_{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[ZR_]??[],...this.input[kR_]??[]],this.codeSamples.forEach(t=>{[...Object.values(uh.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var MKi=ui(pz());function i1c(e,t){return VS(e)?uH(e,t,void 0):e}function bN_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var dL="",Uir=class extends a_{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(IAi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>IAi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new MKi.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=i1c(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=i1c(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new MKi.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(Stu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new MKi.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return IAi(n)?[r,{type:"filenameWithData",filename:n.filename,data:uh.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>IAi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:uh.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new MKi.UnreachableCaseError(i.multipartType);return}}).filter(Gd))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new MKi.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new MKi.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Gd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Gd));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:bN_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?Fir(this.name):this.summary!=null?Fir(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function gN_(e,t){return VS(e)?uH(e,t,void 0):e}var CN_=ui(pz());var ON_="#/components/schemas/";function L9n(e){if(e.$ref.startsWith(ON_))return e.$ref.replace(ON_,"")}function jpi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function zAi(e){return typeof e.type=="string"&&e.type==="array"}function mN_(e){return e.type==="boolean"}function PN_(e){return e.type==="integer"}function xAi(e){return!Array.isArray(e.type)&&!zAi(e)}function jN_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||xAi(t)||zAi(t))}function wN_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function SN_(e){return e.type==="null"}function DN_(e){return e.type==="number"}function n1c(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function EN_(e){return e.type==="string"}var Ttu=class extends eoe{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new Jq({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return vA(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var Ctu=class extends x3{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new qFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var Btu=class extends eoe{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new Jq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Gd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>vA(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(Gd).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(l=>[...u,l]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(jpi).filter(Gd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function Itu(e){return e!=null&&e.length>0?e:[void 0]}var U9n=class extends eoe{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new Jq({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new Jq({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(VS(t))return L9n(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new Jq({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Gd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return F9n(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:vA(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Gd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>Itu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>uh.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=R3(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new Jq({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var ztu=class extends eoe{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>R3(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>R3(t,this.context.document)?.type!=="null"?new Jq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Gd);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=R3({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new Jq({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Gd);return this.isNullable&&n!=null?n.map(jpi).filter(Gd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:uh.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>vA(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??Fir(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Gd)).filter(Gd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>vA(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?Fir(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?Fir(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Gd)).filter(Gd)}:void 0,i=this.isNullable?jpi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var xtu=class extends x3{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var RAi=class extends x3{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(VS(r)){let n=R3(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(Gd),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var MN_=ui(pz());function e8E(e){return kwc.includes(e)}var Rtu=class extends x3{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(e8E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${kwc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new MN_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var Ntu=class extends x3{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return jpi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var AN_=ui(pz());function t8E(e){return Zwc.includes(e)}var Ftu=class extends x3{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(t8E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Zwc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new AN_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var qN_=ui(pz());function r8E(e){return e1c.includes(e)}var Ltu=class extends x3{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new qN_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(r8E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${e1c.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new RAi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var TN_=ui(pz());var Utu=class extends x3{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,TN_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var AKi=class extends eoe{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=L9n(this.input);let t=R3(this.input,this.context.document);t?.enum!=null&&xAi(t)&&(this.maybeEnumConverterNode=new RAi({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:uh.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=R3(this.input,this.context.document);if(r!=null)return new Jq({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var Jq=class e extends eoe{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new qFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),xAi(this.input)&&wN_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),VS(this.input)){let t=L9n(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new AKi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new Ctu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(jN_(this.input))this.typeShapeNode=new Btu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(xAi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new ztu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(n1c(this.input)&&this.input.allOf!=null)this.typeShapeNode=new U9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(xAi(this.input)&&this.input.enum!=null)this.typeShapeNode=new RAi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":n1c(this.input)&&(this.typeShapeNode=new U9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":zAi(this.input)&&(this.typeShapeNode=new Ttu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":mN_(this.input)&&(this.typeShapeNode=new xtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":PN_(this.input)&&(this.typeShapeNode=new Rtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":DN_(this.input)&&(this.typeShapeNode=new Ftu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":EN_(this.input)&&(this.typeShapeNode=new Ltu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":SN_(this.input)&&(this.typeShapeNode=new Ntu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new CN_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new U9n({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new Utu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!VS(this.input)&&(!zAi(this.input)&&this.input==null||zAi(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=vA(t)?.map(i=>this.nullable?jpi(i):i).filter(Gd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function NAi(e){if(e!=null)return F9n(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Gd))}var Vir=class extends x3{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;VS(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new qFe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new Jq({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=gN_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function BN_(e,t){return VS(e)?uH(e,t,void 0):e}var a1c=ui(pz());function Vtu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[uh.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var IN_=ui(dIs(),1),V9n=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=IN_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function i8E(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var W9n=class extends a_{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new Jq({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),i8E(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(VS(r)?n=ltu(r.$ref,this.context.document):n=r,n!=null)return[t,new R9n({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Gd)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[uh.api.latest.AuthSchemeId(t),i]}).filter(Gd)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=vA(r.convert());return n==null?[t,void 0]:[uh.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Gd(r))):void 0}}};var Wtu=class extends Jq{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=R3(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${VS(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=R3(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var Htu=class extends a_{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=R3(this.input.schema,this.context.document);this.availability=new qFe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=VS(this.input.schema)?new AKi({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=V9n.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new Jq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new Wtu({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Gd))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[dL]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[dL]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:vA(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=DHt([this.method,this.path,this.contentType,"request"].join("_"));return Vtu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uh.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new a1c.UnreachableCaseError(n);return}}).filter(Gd)}convert(){if(this.schema instanceof AKi)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:uh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:uh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=vA(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:uh.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new a1c.UnreachableCaseError(n.multipartType),[]}}).filter(Gd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var $tu=class extends a_{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=BN_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new Htu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>vA(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Gd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>vA(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Gd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var zN_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function xN_(e,t){if(VS(e)){let r=uH(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Gtu=ui(pz());var RN_="application/json";var NN_="application/octet-stream";function FN_(e,t){return e===t||t===dL||e===dL}var wRa=class extends a_{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,d]of Object.entries(r))for(let s of d)FN_(l,a)&&(i.add(l),this.examples?.push(new Uir({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,BAi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,l]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new Uir({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,BAi(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[l,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new Uir({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,BAi(d,a),{requestBody:l,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[l,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new Uir({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,BAi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[dL];if(a!=null)for(let u of a)this.examples?.push(new Uir({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,BAi(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let l=V9n.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=RN_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new Jq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(l?.isOctetStream())this.contentType=NN_,this.contentSubtype=R3(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new Jq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=gtu(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[dL]??=[],r[dL]=[{value:this.input.example}]);let i=R3(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=gtu(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[dL]??=[],r[dL]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[dL]??=[],r[dL]?.push(l!=null?{value:l}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let l of this.requests)a.push(...Object.entries(l.examples??{}).filter(([d])=>!n.has(d)&&d!==dL).map(([d,s])=>[l,d,s]));let u=Object.entries(r).filter(([l,d])=>!n.has(l)&&Gd(d)&&l!==dL);Object.keys(r).every(l=>l===dL)||this.matchExamplesByIndex(a,u),!n.has(dL)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return vA(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new Gtu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return vA(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=DHt([this.method,this.path,this.statusCode,"response"].join("_"));return Vtu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uh.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new Gtu.UnreachableCaseError(i);return}}).filter(Gd)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new Gtu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var SRa=class extends a_{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=xN_(this.input,this.context.document);if(r==null){this.context.errors.error({message:VS(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new Vir({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new wRa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new wRa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Gd)}};var Qtu=class extends a_{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new SRa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new SRa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return Itu(NAi(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(l=>l.convert()).filter(Gd))})))}).filter(Gd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=vA(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??zN_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(l=>{let d=l.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(Gd)})).filter(Gd)})).filter(Gd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var FAi=class extends a_{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new Uir({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,BAi(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new qFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=Lir(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new Atu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(VS(i)){let a=wtu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new Vir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new Vir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new Vir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new qtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new $tu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new Qtu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new N9n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new jRa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new jRa({input:{[utu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Mtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>Otu({namespace:vA(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Gd),this.xFernExamplesNode=new Etu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(Gd)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:uh.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(Gd),n=fN_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:lN_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:uh.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[c]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:NAi(this.queryParameters)?.flat(),headers:NAi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Gd)}}).filter(Gd);let a=this.servers?.map(o=>o.convert()).filter(Gd),u=this.convertPathToPathParts();if(u==null)return;let l,d=this.auth?.convert();d!=null&&(l=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(Gd);return this.endpointIds.map((o,c)=>({id:uh.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>uh.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>uh.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:NAi(this.pathParameters)?.flat(),queryParameters:NAi(this.queryParameters)?.flat(),requestHeaders:NAi(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var H9n=class extends a_{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=Lir(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new FAi({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new FAi({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new FAi({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new FAi({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new FAi({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Gd)}};function Jtu(e){return"payloads"in e}var Ktu=class extends a_{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new H9n({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:Lir(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Gd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{Jtu(a)?r[uh.WebhookId(a.id)]=a:t[uh.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var Ytu=class extends a_{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[RR_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||wtu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new Vir({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return F9n(this.globalHeaders,this.requiredProperties)?.flat()}};function LN_(e,t){if(VS(e)){let r=uH(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Xtu=class extends a_{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=LN_(a,this.context.document);if(u!=null)return new H9n({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Gd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{Jtu(i)&&(t[uh.WebhookId(i.id)]=i)}),t),{})}};var Ztu=class extends a_{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=Lir(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new N9n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new jtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new Ktu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new Xtu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new W9n({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new Ytu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=yae(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=ntu({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:uh.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var $9n=class extends z9n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function TFe(e){return typeof e=="object"&&Gd(e)&&"$ref"in e&&typeof e.$ref=="string"}function EHt(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(TFe(n)&&(n=EHt(n,t,r)),n)}function UN_(e,t){return TFe(e)?EHt(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var $N_=ui(pz());function wpi(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=wpi(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>wpi(t)):[wpi(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return wpi(e.oneOf[0]);if(e.anyOf?.[0]!=null)return wpi(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,wpi(r));return t}}function DRa(e,t){return TFe(e)?EHt(e,t,{name:"",schema:{type:"object"}}):e}function VN_(e,t){return TFe(e)?EHt(e,t,void 0):e}function WN_(e,t){return TFe(e)?EHt(e,t,void 0):e}function HN_(e,t){return TFe(e)?EHt(e,t,void 0):e}var n8E={key:uh.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},ktu=class extends $9n{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?DRa(this.method.result,this.context.openrpc):void 0,r=t?new Jq({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(l=>DRa(l,this.context.openrpc)).filter(Gd)?.map(l=>{let d=new Jq({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:uh.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(Gd),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(l=>{let d=WN_(l,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=VN_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Gd))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(Gd)??[];if(u.length<=0){let l=wpi({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=DRa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:wpi(DRa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:uh.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:uh.PropertyKey("apiKey")}],auth:void 0,pathParameters:[n8E],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(Gd):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(l=>l.convert()).filter(Gd),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=HN_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[uh.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=vA(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new $N_.UnreachableCaseError(u);return}}).filter(Gd)[0];if(n)return{statusCode:200,body:n,description:r}}};var ERa=class extends $9n{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=Lir(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=UN_(t,this.context.openrpc);r!=null&&this.methods.push(new ktu({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new W9n({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=yae(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Gd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=ntu({endpoints:n});return{id:uh.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var MRa=class extends otu{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function ARa(e,t){if(e instanceof pir){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof hR))return;let r=new uHt(e.absoluteFilePath),i=await yFe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let l={document:u.value,logger:t.logger,errors:new I9n,generatedTypes:{}},d=new Ztu({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=MIs(a,d.convert())}return a}var GN_=require("fs/promises");async function QN_(e,t){let r=await(0,GN_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new MRa({openrpc:i,logger:t.logger});return new ERa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function a8E(e){return e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function o8E(e){return/^(https?:)?\/\//.test(e)}async function u8E({pathToImage:e,absolutePathToFernFolder:t}){if(e==null||o8E(e))return;let r=Gv(t,Ra.of(e));if(await yf(r))return r}async function G9n({iconPath:e,filepaths:t,docsWorkspace:r}){if(a8E(e)){let i=await u8E({pathToImage:e,absolutePathToFernFolder:r.absoluteFilePath});i&&t.add(i)}}async function JN_({parsedDocsConfig:e,docsWorkspace:t}){let r=new Set;return e.logo?.dark!=null&&r.add(e.logo.dark),e.logo?.light!=null&&r.add(e.logo.light),e.favicon!=null&&r.add(e.favicon),e.backgroundImage?.dark!=null&&r.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&r.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&r.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&r.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&r.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(n=>{n.image!=null&&r.add(n.image)}),(await o1c({navigation:e.navigation,docsWorkspace:t})).forEach(n=>{r.add(n)}),e.js!=null&&e.js.files.forEach(n=>{r.add(n.absolutePath)}),r}async function o1c({navigation:e,docsWorkspace:t}){let r=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(i=>qRa({item:i,filepaths:r,docsWorkspace:t})));break;case"tabbed":await Promise.all(e.items.map(async i=>{i.icon!=null&&await G9n({iconPath:i.icon,filepaths:r,docsWorkspace:t}),i.child.type==="layout"&&i.child.layout!=null&&await Promise.all(i.child.layout.map(n=>qRa({item:n,filepaths:r,docsWorkspace:t})))}));break;case"versioned":await Promise.all(e.versions.map(async i=>{i.landingPage!=null&&await qRa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await o1c({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break;case"productgroup":await Promise.all(e.products.map(async i=>{i.landingPage!=null&&await qRa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await o1c({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break}return r}async function qRa({item:e,filepaths:t,docsWorkspace:r}){switch(e.type){case"page":e.icon!=null&&await G9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"section":e.icon!=null&&await G9n({iconPath:e.icon,filepaths:t,docsWorkspace:r}),await Promise.all(e.contents.map(i=>qRa({item:i,filepaths:t,docsWorkspace:r})));break;case"apiSection":e.icon!=null&&await G9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"link":e.icon!=null&&await G9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"changelog":e.icon!=null&&await G9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break}}async function KN_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){c8E(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await u1c({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await u1c({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function u1c({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await JYt(e,{alphabetized:Go,api:Go,apiName:Go,audiences:Go,displayErrors:Go,snippets:Go,summary:Go,title:Go,layout:Go,icon:Go,slug:Go,hidden:Go,skipSlug:Go,paginated:Go,playground:Go,flattened:Go,path:Go,page:Go,featureFlag:Go,openrpc:Go,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await u1c({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Go,orphaned:Go}),s8E(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function s8E(e){return e.api!=null}function c8E(e){return e[0]?.tab!=null}function nk(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}YN_.default.extend(XN_.default);var l8E=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),eru=0,f8E=async({ir:e})=>(eru++,`${e.apiName.snakeCase.unsafeName}-${eru}`),d8E=async({api:e})=>(eru++,`${e.id}-${eru}`),MHt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=l8E,d=f8E,s=d8E){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=ttu.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;async resolve(){this._parsedDocsConfig=await w6s({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await KN_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:o})=>{(await o.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(b=>{let g=zq(this.docsWorkspace.absoluteFilePath,b.absoluteFilepath);this.parsedDocsConfig.pages[g]=b.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ra.of(o)]=await Lgc({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ra.of(o)]=await Fgc({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});let i=await JN_({parsedDocsConfig:this.parsedDocsConfig,docsWorkspace:this.docsWorkspace});for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:b,markdown:g}=Pxa(c,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Ra.of(o)]=g;for(let O of b)i.add(O)}catch(b){throw this.taskContext.logger.error(`Failed to parse ${o}: ${b instanceof Error?b.message:String(b)}`),b}let n=Array.from(i).map(o=>({absoluteFilePath:o,relativeFilePath:this.toRelativeFilepath(o)}));(await this.uploadFiles(n)).forEach(o=>{this.collectedFileIds.set(o.absoluteFilePath,o.fileId)});let u=await this.getMarkdownFilesToFullyQualifiedPathNames();for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ra.of(o)]=Ngc(c,this.collectedFileIds,u,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let l={};Object.entries(this.parsedDocsConfig.pages).forEach(([o,c])=>{let b=p8E(this.editThisPage,o);l[gHt.PageId(o)]={markdown:c,editThisPageUrl:b?gHt.Url(b):void 0}});let d=await this.convertDocsConfiguration(),s={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let o=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let b=Gv(this.docsWorkspace.absoluteFilePath,c);(await(0,tru.stat)(b)).isDirectory()?(await hxe(b,"{js,ts,jsx,tsx,md,mdx}")).forEach(m=>{o.add(m)}):b.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&o.add(b)})),s=Object.fromEntries(await Promise.all([...o].map(async c=>{let b=this.toRelativeFilepath(c),g=(await(0,tru.readFile)(c)).toString();return[b,g]})))}return{config:d,pages:l,jsFiles:s}}resolveFilepath(t){if(t!=null)return Gv(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return zq(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,s1c.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,s1c.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(){let t={},r=Oo.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return Oo.NodeCollector.collect(r).slugMap.forEach((n,a)=>{if(n==null||!Oo.isPage(n))return;let u=Oo.getPageId(n);if(u==null)return;let l=Tu(this.docsWorkspace.absoluteFilePath,Ra.of(u));t[l]=a}),t}getDocsBasePath(){return new URL(nk(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?gHt.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(i=>({...i,url:gHt.Url(i.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(i=>({...i,value:gHt.Url(i.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:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}: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,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=Oo.V1.SlugGenerator.init(Oo.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,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,roles:this.parsedDocsConfig.roles?.map(n=>Oo.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return gCn(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),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Oo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??Bq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(u=>this.toProductNode(u,i)))}}async toProductNode(t,r){let i=r.setProductSlug(t.slug??Bq(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:wo(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Oo.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??Bq(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Oo.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?_8E(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(l)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return gCn(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let b=Gv(this.docsWorkspace.absoluteFilePath,Ra.of(t.openrpc));if(!await yf(b))throw new Error(`OpenRPC file does not exist at path: ${b}`);let g=await QN_(b,this.taskContext);if(g==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:g,apiName:t.apiName,snippetsConfig:rtu(t.snippetsConfiguration)}),new mRa(t,g,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let b=this.getOpenApiWorkspaceForApiSection(t),g=rtu(t.snippetsConfiguration),O=await ARa(b,this.taskContext);if(O==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:O,snippetsConfig:g,apiName:t.apiName}),new mRa(t,O,r,b,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=rtu(t.snippetsConfiguration),a,u,l=this.parsedDocsConfig.experimental?.openapiParserV3;if(l==null||l)try{a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}a==null&&(u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),a=gR({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new bR(this.taskContext,u)}));let s=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),o=PRa(a,s,{oauth:t.playground?.oauth});return new keu(t,o,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new mpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Oo.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=Oo.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??Bq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?Oo.PageId(a):void 0,l=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??Bq(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:l,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(c=>this.toNavigationChild(l,c,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return gCn(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new mpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,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:Oo.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??Bq(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,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):gHt.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:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(ev),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:gHt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return gCn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:gHt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function p8E(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${nk(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function _8E(e){switch(e){case"beta":return Oo.V1.NavigationV1Availability.Beta;case"deprecated":return Oo.V1.NavigationV1Availability.Deprecated;case"ga":return Oo.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Oo.V1.NavigationV1Availability.Stable;default:wo(e)}}async function sH(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof hR?t:null))).filter(ev)}async function c1c(e,t,r){if(e instanceof pir){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof hR))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return ik({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0}})}var K6_=ui(Eru(),1),ok=require("fs/promises"),Y6_=require("os"),X6_=ui(XX(),1),Z6_=ui(J6_(),1);var Hru=process.platform==="win32",uLE="etag",sLE="preview",cLE="app-preview",lLE="bundle",fLE=".next",dLE="standalone",pLE=".fern",_LE="packages/fern-docs/bundle/.next/server/instrumentation.js",hLE=".npmrc",yLE=".pnpmfile.cjs",vLE="pnpm-workspace.yaml",bLE='Cannot find matching keyid: {"signatures":';function gLE(){return Tu(pl.of((0,Y6_.homedir)()),Ra.of(pLE))}function $ru({app:e=!1}){return Tu(gLE(),Ra.of(e?cLE:sLE))}function $Ai({app:e=!1}){return Tu($ru({app:e}),Ra.of(e?fLE:lLE))}function YRa({app:e=!1}){return Tu($Ai({app:e}),Ra.of(dLE))}function OLE({app:e=!1}){return Tu(YRa({app:e}),Ra.of(_LE))}function mLE({app:e=!1}){return Tu(YRa({app:e}),Ra.of(vLE))}function PLE({app:e=!1}){return Tu(YRa({app:e}),Ra.of(yLE))}function jLE({app:e=!1}){return Tu(YRa({app:e}),Ra.of(hLE))}function zKi(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function wLE({app:e=!1}){return Tu($ru({app:e}),Ra.of(uLE))}var SLE=`packages:
2052
2052
  - "packages/**"
2053
2053
  - "!**/dist"
2054
2054
  `,DLE=`module.exports = {