fern-api 2.15.1 → 2.15.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +3 -3
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1152,7 +1152,7 @@ ${GUp.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&M9s(th
|
|
|
1152
1152
|
`+GHi.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?GHi.default.cyan(e4p(t,this.opt.mask)):GHi.default.italic(GHi.default.dim("[hidden]")):this.opt.mask?e4p(t,this.opt.mask):GHi.default.italic(GHi.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 v0o=ae(b1(),1);var e3p=ae(cGs(),1),y0o=require("child_process"),aTn=require("fs"),h0o=ae(require("path"),1),t3p=ae(require("os"),1),r3p=require("crypto"),KGs=ae(Z4p(),1);var d0o=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var Zga=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var p0o=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var _0o=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function b0o(e="",t,r){let i=new JGs(e,r);i.runAsync((n,a)=>{if(n)setImmediate(t,n,void 0);else try{i.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function k4p(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function CgS(e){let t=[],r="";for(let i=0;i<e.length;i++){let n=e.charAt(i);i>0&&n===" "&&e[i-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${n}`}return r.length>0&&t.push(r),t}var JGs=class{text="";tempFile;editor;lastExitStatus=0;fileOptions={};get temp_file(){return console.log("DEPRECATED: temp_file. Use tempFile moving forward."),this.tempFile}get last_exit_status(){return console.log("DEPRECATED: last_exit_status. Use lastExitStatus moving forward."),this.lastExitStatus}constructor(t="",r){this.text=t,r&&(this.fileOptions=r),this.determineEditor(),this.createTemporaryFile()}run(){return this.launchEditor(),this.readTemporaryFile(),this.text}runAsync(t){try{this.launchEditorAsync(()=>{try{this.readTemporaryFile(),setImmediate(t,void 0,this.text)}catch(r){setImmediate(t,r,void 0)}})}catch(r){setImmediate(t,r,void 0)}}cleanup(){this.removeTemporaryFile()}determineEditor(){let t=process.env.VISUAL?process.env.VISUAL:process.env.EDITOR?process.env.EDITOR:process.platform.startsWith("win")?"notepad":"vim",r=CgS(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??t3p.default.tmpdir(),r=(0,r3p.randomUUID)(),i=k4p(this.fileOptions.prefix),n=k4p(this.fileOptions.postfix),a=`${i}${r}${n}`,o=h0o.default.resolve(t,a),c=h0o.default.resolve(t)+h0o.default.sep;if(!o.startsWith(c))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=o;let f={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(f.mode=this.fileOptions.mode),(0,aTn.writeFileSync)(this.tempFile,this.text,f)}catch(t){throw new d0o(t)}}readTemporaryFile(){try{let t=(0,aTn.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,e3p.detect)(t)??"utf8";KGs.default.encodingExists(r)||(r="utf8"),this.text=KGs.default.decode(t,r)}}catch(t){throw new p0o(t)}}removeTemporaryFile(){try{(0,aTn.unlinkSync)(this.tempFile)}catch(t){throw new _0o(t)}}launchEditor(){try{let t=(0,y0o.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new Zga(t)}}launchEditorAsync(t){try{(0,y0o.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new Zga(r)}}};var i3p=ae(Z_e(),1);var kga=class extends v1{_run(t){this.done=t,this.editorResult=new i3p.Subject;let r=qQ(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"?v0o.default.dim("Received"):v0o.default.dim("Press <enter> to launch your preferred editor."),t&&(r=v0o.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),b0o(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 s3p=require("stream");var o3p=ae(require("readline"),1),u3p=ae(a3p(),1),$Hi=class{constructor(t){this.rl||=o3p.default.createInterface(TgS(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 TgS(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 u3p.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var eOa=class extends $Hi{constructor(t={}){super(t),this.log=new s3p.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return Nga(this.rl,this.bottomBar.split(`
|
|
1153
1153
|
`).length),this}updateBottomBar(t){return Nga(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+`
|
|
1154
1154
|
`}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&&Umo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var dO=ae(Z_e(),1),f3p=ae(nga(),1);var g0o=ae(Z_e(),1),c3p=ae(nga(),1),O0o=function(e,t,r){return typeof e[t]!="function"?(0,g0o.of)(e):(0,g0o.from)((0,c3p.default)(e[t])(r).then(i=>(e[t]=i,e)))};var l3p={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,o)=>{n==="__proto__"||n==="constructor"||(a===o.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((o,c)=>o!=null?o[c]:o,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},oTn=class extends $Hi{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,dO.from)(t):(0,dO.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,dO.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,dO.from)([t]),this.process=i.pipe((0,dO.concatMap)(this.processQuestion.bind(this)),(0,dO.publish)()),this.process.connect(),this.process.pipe((0,dO.reduce)((n,a)=>(l3p.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,dO.defer)(()=>(0,dO.of)(t).pipe((0,dO.concatMap)(this.setDefaultType.bind(this)),(0,dO.concatMap)(this.filterIfRunnable.bind(this)),(0,dO.concatMap)(()=>O0o(t,"message",this.answers)),(0,dO.concatMap)(()=>O0o(t,"default",this.answers)),(0,dO.concatMap)(()=>O0o(t,"choices",this.answers)),(0,dO.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,dO.defer)(()=>(0,dO.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,dO.defer)(()=>(0,dO.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&l3p.get(this.answers,t.name)!==void 0)return dO.EMPTY;if(t.when===!1)return dO.EMPTY;if(typeof t.when!="function")return(0,dO.of)(t);let{answers:r}=this;return(0,dO.defer)(()=>(0,dO.from)((0,f3p.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,dO.filter)(i=>i!=null)))}};function d3p(e){let t=function(r,i){let n;try{n=new oTn(t.prompts,e)}catch(o){return Promise.reject(o)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",Qga),this.registerPrompt("input",xHi),this.registerPrompt("number",Uga),this.registerPrompt("confirm",Lga),this.registerPrompt("rawlist",Vga),this.registerPrompt("expand",Wga),this.registerPrompt("checkbox",xga),this.registerPrompt("password",Gga),this.registerPrompt("editor",kga)},t.restoreDefaultPrompts(),t}var YGs=d3p();function zgS(e,t){YGs.registerPrompt(e,t)}function NgS(){YGs.restoreDefaultPrompts()}var FgS={prompt:YGs,ui:{BottomBar:eOa,Prompt:oTn},createPromptModule:d3p,registerPrompt:zgS,restoreDefaultPrompts:NgS,Separator:w6},A0o=FgS;var gTn=require("path"),GLp=require("fs"),HLp=require("readline"),yLp="posthog-node";function fmS(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 c=a.tags[L0o.POSTHOG_ID_TAG];if(c===void 0)return a;let f=e.options.host??"https://us.i.posthog.com",s=new URL(`/project/${e.apiKey}/person/${c}`,f).toString();a.tags["PostHog Person URL"]=s;let u=a.exception?.values||[],l=u.map(_=>({..._,stacktrace:_.stacktrace?{..._.stacktrace,type:"raw",frames:(_.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),p={$exception_message:u[0]?.value||a.message,$exception_type:u[0]?.type,$exception_personURL:s,$exception_level:a.level,$exception_list:l,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:u[0]?.value||a.message,$sentry_exception_type:u[0]?.type,$sentry_tags:a.tags};return t&&r&&(p.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:c,properties:p}),a}}var L0o=class{constructor(t,r,i,n){this.name=yLp,this.name=yLp,this.setupOnce=function(a,o){let c=o()?.getClient()?.getDsn()?.projectId;a(fmS(t,{organization:r,projectId:c,prefix:i,severityAllowList:n}))}}};L0o.POSTHOG_ID_TAG="posthog_distinct_id";var z0o="0123456789abcdef",V0o=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+=z0o.charAt(this.bytes[r]>>>4),t+=z0o.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+=z0o.charAt(this.bytes[r]>>>4),t+=z0o.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}},T7s=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??dmS()}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 V0o.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,V0o.ofInner(t)}},dmS=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),bLp,R7s=()=>pmS().toString(),pmS=()=>(bLp||(bLp=new T7s)).generate();function _mS(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t())},{_posthogErrorHandler:!0})}function hmS(e,t){global.process.on("uncaughtException",_mS(e,t))}function ymS(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var N0o,vLp,F0o;function bmS(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return F0o&&r.length===vLp||(vLp=r.length,F0o=r.reduce((i,n)=>{N0o||(N0o={});let a=N0o[n];if(a)i[a[0]]=a[1];else{let o=e(n);for(let c=o.length-1;c>=0;c--){let s=o[c]?.filename,u=t[n];if(s&&u){i[s]=u,N0o[n]=[s,u];break}}}return i},{})),F0o}function vmS(e){return typeof Event<"u"&&KLp(e,Event)}function gmS(e){return JLp(e,"Object")}function W7s(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return KLp(e,Error)}}function KLp(e,t){try{return e instanceof t}catch{return!1}}function OmS(e){return JLp(e,"ErrorEvent")}function JLp(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function AmS(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},o=$Lp(a,r,i);return{$exception_list:await Promise.all(o.map(async s=>{let u=await MmS(e,t,s);return u.value=u.value||"",u.type=u.type||"Error",u.mechanism=a,u}))}}function $Lp(e,t,r){let i=mmS(e,t,r);return i.cause?[i,...$Lp(e,i.cause,r)]:[i]}function mmS(e,t,r){if(W7s(t))return t;if(e.synthetic=!0,gmS(t)){let n=PmS(t);if(n)return n;let a=jmS(t),o=r?.syntheticException||new Error(a);return o.message=a,o}let i=r?.syntheticException||new Error(t);return i.message=`${t}`,i}function PmS(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(W7s(r))return r}}function jmS(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=EmS(e);if(OmS(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=wmS(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function wmS(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function EmS(e,t=40){let r=Object.keys(SmS(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return gLp(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:gLp(a,t)}return""}function gLp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function SmS(e){return W7s(e)?{message:e.message,name:e.name,stack:e.stack,...OLp(e)}:vmS(e)?{type:e.type,target:ALp(e.target),currentTarget:ALp(e.currentTarget),...OLp(e)}:e}function OLp(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 ALp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function MmS(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=DmS(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function DmS(e,t){return BmS(e(t.stack||"",1),e)}function BmS(e,t){let r=bmS(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var ImS=2e3,yTn=class e{static async captureException(t,r,i,n,a){let o={...a};n||(o.$process_person_profile=!1);let c=await AmS(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||R7s(),properties:{...c,...o}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(hmS(this.onException.bind(this),this.onFatalError.bind(this)),ymS(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(ImS)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function CmS(e=process.argv[1]?(0,gTn.dirname)(process.argv[1]):process.cwd(),t=gTn.sep==="\\"){let r=t?mLp(e):e;return i=>{if(!i)return;let n=t?mLp(i):i,{dir:a,base:o,ext:c}=gTn.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,c.length*-1));let f=decodeURIComponent(o);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${f}`;if(a.startsWith(r)){let u=a.slice(r.length+1).replace(/\//g,".");return u?`${u}:${f}`:f}return f}}function mLp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var W0o=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)}}},U0o=new W0o(25),YLp=new W0o(20),x7s=7,qmS=1e3,TmS=1e4;async function RmS(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||QmS(o)||UmS(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(YLp.get(n))continue;let a=t[n];if(!a)continue;a.sort((f,s)=>f-s);let o=VmS(a);if(o.every(f=>LmS(n,f)))continue;let c=WmS(U0o,n,{});i.push(zmS(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&NmS(e,U0o),U0o.reduce(),e}function zmS(e,t,r){return new Promise(i=>{let n=(0,GLp.createReadStream)(e),a=(0,HLp.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,f=0,s=t[f];if(s===void 0){o();return}let u=s[0],l=s[1];function p(){YLp.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=xmS(_,0),c>=l)){if(f===t.length-1){a.close(),a.removeAllListeners();return}f++;let h=t[f];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],l=h[1]}})})}function NmS(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;FmS(r.lineno,r,i)}}function FmS(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=XLp(e);n<e;n++){let a=r[n];if(a===void 0){PLp(t);return}t.pre_context.push(a)}if(r[e]===void 0){PLp(t);return}t.context_line=r[e];let i=ZLp(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 PLp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function QmS(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function UmS(e){return e.lineno!==void 0&&e.lineno>TmS||e.colno!==void 0&&e.colno>qmS}function LmS(e,t){let r=U0o.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 VmS(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=jLp(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+x7s:(n.push(i),i=jLp(a)),t++}return n}function jLp(e){return[XLp(e),ZLp(e)]}function XLp(e){return Math.max(1,e-x7s)}function ZLp(e){return e+x7s}function WmS(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function xmS(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 GmS="4.18.0",B6;(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"})(B6||(B6={}));var wLp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(wLp||(wLp={}));var ELp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(ELp||(ELp={}));var SLp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(SLp||(SLp={}));var MLp;(function(e){e.Html="html",e.Text="text"})(MLp||(MLp={}));var DLp;(function(e){e.Number="number",e.Emoji="emoji"})(DLp||(DLp={}));var BLp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(BLp||(BLp={}));var ILp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(ILp||(ILp={}));var CLp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(CLp||(CLp={}));var qLp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(qLp||(qLp={}));var HmS=e=>{if("flags"in e){let t=JmS(e.flags),r=$mS(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,kLp(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,KmS(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function KmS(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 JmS=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,G7s(r)]).filter(([,t])=>t!==void 0)),$mS=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?kLp(i):void 0]}))},G7s=e=>e===void 0?void 0:e.variant??e.enabled,kLp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},YmS=1,XmS=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"]),ZmS="utf8";function kmS(e,t){if(!e||typeof e!="string"||e0S(e))throw new Error(t)}function e0S(e){return e.trim().length===0}function t0S(e){return e?.replace(/\/+$/,"")}async function r0S(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 TLp(){return new Date().getTime()}function C7s(){return new Date().toISOString()}function x0o(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function i0S(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function n0S(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 a0S(e,t=0,r){let i=n0S(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function RLp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var lOa=String.fromCharCode,zLp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Q0o={};function o0S(e,t){if(!Q0o[e]){Q0o[e]={};for(let r=0;r<e.length;r++)Q0o[e][e.charAt(r)]=r}return Q0o[e][t]}var _Tn={compressToBase64:function(e){if(e==null)return"";let t=_Tn._compress(e,6,function(r){return zLp.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:_Tn._decompress(e.length,32,function(t){return o0S(zLp,e.charAt(t))})},compress:function(e){return _Tn._compress(e,16,function(t){return lOa(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],o,c,f="",s="",u="",l=2,p=3,_=2,h=0,y=0,b;for(b=0;b<e.length;b+=1)if(f=e.charAt(b),Object.prototype.hasOwnProperty.call(i,f)||(i[f]=p++,n[f]=!0),s=u+f,Object.prototype.hasOwnProperty.call(i,s))u=s;else{if(Object.prototype.hasOwnProperty.call(n,u)){if(u.charCodeAt(0)<256){for(o=0;o<_;o++)h=h<<1,y==t-1?(y=0,a.push(r(h)),h=0):y++;for(c=u.charCodeAt(0),o=0;o<8;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}else{for(c=1,o=0;o<_;o++)h=h<<1|c,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=0;for(c=u.charCodeAt(0),o=0;o<16;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}l--,l==0&&(l=Math.pow(2,_),_++),delete n[u]}else for(c=i[u],o=0;o<_;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1;l--,l==0&&(l=Math.pow(2,_),_++),i[s]=p++,u=String(f)}if(u!==""){if(Object.prototype.hasOwnProperty.call(n,u)){if(u.charCodeAt(0)<256){for(o=0;o<_;o++)h=h<<1,y==t-1?(y=0,a.push(r(h)),h=0):y++;for(c=u.charCodeAt(0),o=0;o<8;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}else{for(c=1,o=0;o<_;o++)h=h<<1|c,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=0;for(c=u.charCodeAt(0),o=0;o<16;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}l--,l==0&&(l=Math.pow(2,_),_++),delete n[u]}else for(c=i[u],o=0;o<_;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1;l--,l==0&&(l=Math.pow(2,_),_++)}for(c=2,o=0;o<_;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1;for(;;)if(h=h<<1,y==t-1){a.push(r(h));break}else y++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:_Tn._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},o=4,c=4,f=3,s="",u,l,p,_,h,y,b;for(u=0;u<3;u+=1)i[u]=u;for(p=0,h=Math.pow(2,2),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;switch(p){case 0:for(p=0,h=Math.pow(2,8),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;b=lOa(p);break;case 1:for(p=0,h=Math.pow(2,16),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;b=lOa(p);break;case 2:return""}for(i[3]=b,l=b,n.push(b);;){if(a.index>e)return"";for(p=0,h=Math.pow(2,f),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;switch(b=p){case 0:for(p=0,h=Math.pow(2,8),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;i[c++]=lOa(p),b=c-1,o--;break;case 1:for(p=0,h=Math.pow(2,16),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;i[c++]=lOa(p),b=c-1,o--;break;case 2:return n.join("")}if(o==0&&(o=Math.pow(2,f),f++),i[b])s=i[b];else if(b===c)s=l+l.charAt(0);else return null;n.push(s),i[c++]=l+s.charAt(0),o--,l=s,o==0&&(o=Math.pow(2,f),f++)}}},z7s=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)}},bTn=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()}},fOa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function NLp(e){if(e instanceof bTn){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 q7s(e){return typeof e=="object"&&(e instanceof bTn||e instanceof fOa)}function FLp(e){return typeof e=="object"&&e instanceof bTn&&e.status===413}var N7s;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(N7s||(N7s={}));var F7s=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new z7s,this._isInitialized=!1,kmS(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=t0S(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:q7s},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(B6.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(B6.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(B6.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=R7s();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,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...o||{}}});this.enqueue("capture",c,n)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this.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 c=a0S(this.apiKey,YmS,XmS)?`${this.host}/flags/?v=2`:`${this.host}/decide/?v=4`,f={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",c)),this.fetchWithRetry(c,f,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>HmS(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let f=G7s(c.response);return f===void 0&&(f=!1),{response:f,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,o,[t]);if(!c)return;let f=c[t];return f===void 0?null:f}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,o);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),o&&(c.flag_keys_to_evaluate=o);let f=await this.getDecide(t,r,i,n,c);if(f!==void 0)return f.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"),f.quotaLimited?.includes(N7s.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:f?.requestId}):f}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 o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this.logMsgIfDebug(()=>console.error(c)),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",a)),this._events.emit("error",a)}))?.surveys;return n&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(n))),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(B6.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(B6.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(B6.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(B6.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(B6.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=x0o(()=>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:C7s()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${TLp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,c=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(_Tn.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(o,c)}catch(f){this._events.emit("error",f)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:C7s(),uuid:i?.uuid?i.uuid:R7s()};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 NLp(t)})}async flush(){let t=RLp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),RLp([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(B6.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(p=>p.message),o=()=>{let _=(this.getPersistedProperty(B6.Queue)||[]).slice(n.length);this.setPersistedProperty(B6.Queue,_),t=_},c={api_key:this.apiKey,batch:a,sent_at:C7s()};this.historicalMigration&&(c.historical_migration=!0);let f=JSON.stringify(c),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${TLp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,u=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(_Tn.compressToBase64(f))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:f},l={retryCheck:p=>FLp(p)?!1:q7s(p)};try{await this.fetchWithRetry(s,u,l)}catch(p){if(FLp(p)&&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 p instanceof fOa||o(),this._events.emit("error",p),p}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){var a;(a=AbortSignal).timeout??(a.timeout=function(s){let u=new AbortController;return setTimeout(()=>u.abort(),s),u.signal});let o=r.body?r.body:"",c=-1;try{c=Buffer.byteLength(o,ZmS)}catch{c=new TextEncoder().encode(o).length}return await r0S(async()=>{let f=null;try{f=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(u){throw new fOa(u)}if(!(r.mode==="no-cors")&&(f.status<200||f.status>=400))throw new bTn(f,c);return f},{...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(B6.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!q7s(n))throw n;await NLp(n)}};return Promise.race([new Promise((n,a)=>{x0o(()=>{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}},Q7s=i0S();if(!Q7s){let e=hLp();Q7s=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 e8p=Q7s,G0o=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()}},t8p=new G0o(async()=>{try{return await import("crypto")}catch{return}});async function u0S(){return await t8p.getValue()}var s0S=new G0o(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await t8p.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function c0S(){return await s0S.getValue()}async function l0S(e){let t=await u0S();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await c0S();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 f0S=60*1e3,d0S=1152921504606847e3,p0S=["is_not"],hTn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},g1=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},U7s=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||e8p,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;for(let f of this.featureFlags)if(t===f.key){c=f;break}if(c!==void 0)try{o=await this.computeFlagLocally(c,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(f){f instanceof g1?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${f}`)):f instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${f}`))}return o}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={},o={},c=this.featureFlags.length==0;return await Promise.all(this.featureFlags.map(async f=>{try{let s=await this.computeFlagLocally(f,t,r,i,n);a[f.key]=s;let u=await this.computeFeatureFlagPayloadLocally(f.key,s);u&&(o[f.key]=u)}catch(s){s instanceof g1||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${s}`)),c=!0}})),{response:a,payloads:o,fallbackToDecide:c}}async computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new g1("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let f=this.groupTypeMapping[String(c)];if(!f)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new g1("Flag has unknown group type index");if(!(f 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[f];return await this.matchFeatureFlagProperties(t,i[f],s)}else return await this.matchFeatureFlagProperties(t,r,n)}async matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],o=!1,c,f=[...a].sort((s,u)=>{let l=!!s.variant,p=!!u.variant;return l&&p?0:l?-1:p?1:0});for(let s of f)try{if(await this.isConditionMatch(t,r,s,i)){let u=s.variant,l=n.multivariate?.variants||[];u&&l.some(p=>p.key===u)?c=u:c=await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof g1)o=!0;else throw u}if(c!==void 0)return c;if(o)throw new g1("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,o=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((i.properties||[]).length>0){for(let c of i.properties){let f=c.type,s=!1;if(f==="cohort"?s=i8p(c,n,this.cohorts,this.debugMode):s=r8p(c,n,o),!s)return!1}if(a==null)return!0}return!(a!=null&&await QLp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await QLp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}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(f0S,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 hTn(`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 hTn(`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 hTn(`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 hTn&&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=x0o(()=>{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=x0o(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function QLp(e,t,r=""){let i=await l0S(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/d0S}function r8p(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 g1("Operator is_not_set is not supported")}else throw new g1(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!p0S.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(l=>String(l).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function f(s,u,l){if(l==="gt")return s>u;if(l==="gte")return s>=u;if(l==="lt")return s<u;if(l==="lte")return s<=u;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return ULp(String(n))&&String(o).match(String(n))!==null;case"not_regex":return ULp(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&o!=null?typeof o=="string"?f(o,String(n),a):f(o,s,a):f(String(o),String(n),a)}case"is_date_after":case"is_date_before":{let s=_0S(String(n));if(s==null&&(s=LLp(n)),s==null)throw new g1(`Invalid date: ${n}`);let u=LLp(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new g1(`Unknown operator: ${a}`)}}function i8p(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new g1("can't match cohort without a given cohort property value");let a=r[n];return n8p(a,t,r,i)}function n8p(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let f=n8p(c,t,r,i);if(n==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof g1)i&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new g1("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let c of a)try{let f;c.type==="cohort"?f=i8p(c,t,r,i):f=r8p(c,t);let s=c.negation||!1;if(n==="AND"){if(!f&&!s||f&&s)return!1}else if(f&&!s||!f&&s)return!0}catch(f){if(f instanceof g1)i&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new g1("can't match cohort without a given cohort property value");return n==="AND"}}function ULp(e){try{return new RegExp(e),!0}catch{return!1}}function LLp(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 g1(`${e} is in an invalid date format`)}else throw new g1(`The date provided ${e} must be a string, number, or date object`)}function _0S(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 L7s=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},h0S=100,VLp=30*1e3,y0S=50*1e3,V7s=class extends F7s{constructor(t,r={}){if(super(t,r),this._memoryStorage=new L7s,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,h0S):VLp,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 U7s({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 yTn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||y0S}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):e8p(t,r)}getLibraryVersion(){return GmS}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:o,timestamp:c,disableGeoip:f,uuid:s}=t,u=_=>{super.captureStateless(r,i,_,{timestamp:c,disableGeoip:f,uuid:s})},l=async(_,h,y)=>(await super.getFeatureFlagsStateless(_,h,void 0,void 0,y)).flags,p=Promise.resolve().then(async()=>{if(o)return await l(r,a,f);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let _={};for(let[h,y]of Object.entries(a||{}))_[h]=String(y);return await this.getAllFlags(r,{groups:_,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(_=>{let h={};if(_)for(let[b,v]of Object.entries(_))h[`$feature/${b}`]=v;let y=Object.keys(_||{}).filter(b=>_?.[b]!==!1).sort();return y.length>0&&(h.$active_feature_flags=y),h}).catch(()=>({})).then(_=>{u({..._,...n,$groups:a})});this.addPendingPromise(p)}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:o,timestamp:c,disableGeoip:f,uuid:s}=t,u=_=>super.captureStatelessImmediate(r,i,_,{timestamp:c,disableGeoip:f,uuid:s}),l=async(_,h,y)=>(await super.getFeatureFlagsStateless(_,h,void 0,void 0,y)).flags;await Promise.resolve().then(async()=>{if(o)return await l(r,a,f);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let _={};for(let[h,y]of Object.entries(a||{}))_[h]=String(y);return await this.getAllFlags(r,{groups:_,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(_=>{let h={};if(_)for(let[b,v]of Object.entries(_))h[`$feature/${b}`]=v;let y=Object.keys(_||{}).filter(b=>_?.[b]!==!1).sort();return y.length>0&&(h.$active_feature_flags=y),h}).catch(()=>({})).then(_=>{u({..._,...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=VLp){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:f,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,f,s);f=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,f,s),p=l!==void 0,_,h;if(!p&&!o){let b=await super.getFeatureFlagDetailStateless(t,r,n,f,s,a);if(b===void 0)return;h=b.response,l=G7s(h),_=b?.requestId}let y=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(y))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(y):this.distinctIdHasSentFlagCalls[r]=[y],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:h?.metadata?.id,$feature_flag_version:h?.metadata?.version,$feature_flag_reason:h?.reason?.description??h?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:l,$feature_flag_request_id:_},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,sendFeatureFlagEvents:f,personProperties:s,groupProperties:u}=n||{},l=this.addLocalPersonAndGroupProperties(r,a,s,u);s=l.allPersonProperties,u=l.allGroupProperties;let p;return this.featureFlagsPoller!==void 0&&(i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),i&&(p=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i))),c==null&&(c=!1),f==null&&(f=!0),c==null&&(c=!1),!(p!==void 0)&&!c&&(p=await super.getFeatureFlagPayloadStateless(t,r,a,s,u,o)),p}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:o,groupProperties:c}=r||{},f=this.addLocalPersonAndGroupProperties(t,i,o,c);o=f.allPersonProperties,c=f.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,o,c),u={},l={},p=!0;if(s&&(u=s.response,l=s.payloads,p=s.fallbackToDecide),p&&!a){let _=await super.getFeatureFlagsAndPayloadsStateless(t,i,o,c,n);u={...u,..._.flags||{}},l={...l,..._.payloads||{}}}return{featureFlags:u,featureFlagPayloads:l}}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||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");yTn.captureException(this,t,{syntheticException:n},r,i)}},WLp=/\(error: (.*)\)/,a8p=50,o8p="?";function b0S(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return i=>{let n=i.match(r);if(n){let a,o,c,f,s;if(n[1]){c=n[1];let p=c.lastIndexOf(".");if(c[p-1]==="."&&p--,p>0){a=c.slice(0,p),o=c.slice(p+1);let _=a.indexOf(".Module");_>0&&(c=c.slice(_+1),a=a.slice(0,_))}f=void 0}o&&(f=a,s=o),o==="<anonymous>"&&(s=void 0,c=void 0),c===void 0&&(s=s||o8p,c=f?`${f}.${s}`:s);let u=n[2]?.startsWith("file://")?n[2].slice(7):n[2],l=n[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&n[5]&&!l&&(u=n[5]),{filename:u?decodeURI(u):void 0,module:e?e(u):void 0,function:c,lineno:xLp(n[3]),colno:xLp(n[4]),in_app:v0S(u||"",l),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function v0S(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 xLp(e){return parseInt(e||"",10)||void 0}function g0S(e){return[90,b0S(e)]}function O0S(e){let r=[g0S(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],o=i.split(`
|
|
1155
|
-
`);for(let c=n;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let s=WLp.test(f)?f.replace(WLp,"$1"):f;if(!s.match(/\S*Error: /)){for(let u of r){let l=u(s);if(l){a.push(l);break}}if(a.length>=a8p)break}}return A0S(a)}}function A0S(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,a8p).map(r=>({...r,filename:r.filename||m0S(t).filename,function:r.function||o8p}))}function m0S(e){return e[e.length-1]||{}}yTn.stackParser=O0S(CmS());yTn.frameModifiers=[RmS];var vTn=class extends V7s{getLibraryId(){return"posthog-node"}};var H0o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new vTn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"2.15.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var dOa=class{async sendEvent(){}async identify(){}async flush(){}};var OTn=require("fs/promises"),l8p=require("os"),f8p=require("path");var u8p=ae(require("crypto")),J0o=new Uint8Array(256),K0o=J0o.length;function H7s(){return K0o>J0o.length-16&&(u8p.default.randomFillSync(J0o),K0o=0),J0o.slice(K0o,K0o+=16)}var RQ=[];for(let e=0;e<256;++e)RQ.push((e+256).toString(16).slice(1));function s8p(e,t=0){return RQ[e[t+0]]+RQ[e[t+1]]+RQ[e[t+2]]+RQ[e[t+3]]+"-"+RQ[e[t+4]]+RQ[e[t+5]]+"-"+RQ[e[t+6]]+RQ[e[t+7]]+"-"+RQ[e[t+8]]+RQ[e[t+9]]+"-"+RQ[e[t+10]]+RQ[e[t+11]]+RQ[e[t+12]]+RQ[e[t+13]]+RQ[e[t+14]]+RQ[e[t+15]]}var c8p=ae(require("crypto")),K7s={randomUUID:c8p.default.randomUUID};function P0S(e,t,r){if(K7s.randomUUID&&!t&&!e)return K7s.randomUUID();e=e||{};let i=e.random||(e.rng||H7s)();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 s8p(i)}var ehe=P0S;var j0S="id",w0S=".fern",pOa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new vTn(r),this.userId=t==null?void 0:_8s(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:"2.15.1",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ft(Lr.of((0,l8p.homedir)()),Ze.of(w0S),Ze.of(j0S));await Ri(t)||(await(0,OTn.mkdir)((0,f8p.dirname)(t),{recursive:!0}),await(0,OTn.writeFile)(t,ehe())),this.persistedDistinctId=(await(0,OTn.readFile)(t)).toString()}return this.persistedDistinctId}};var J7s;async function ATn(){return J7s==null&&(J7s=await E0S()),J7s}async function E0S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new dOa;let r=await fbo();return r!=null?new pOa({token:r,posthogApiKey:e}):await jqn()!=null?new H0o({posthogApiKey:e}):new pOa({token:void 0,posthogApiKey:e})}catch{return new dOa}}function _Oa(e,t){return function(){return e.apply(t,arguments)}}var{toString:S0S}=Object.prototype,{getPrototypeOf:Y7s}=Object,{iterator:Y0o,toStringTag:p8p}=Symbol,X0o=(e=>t=>{let r=S0S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),zNt=e=>(e=e.toLowerCase(),t=>X0o(t)===e),Z0o=e=>t=>typeof t===e,{isArray:PTn}=Array,mTn=Z0o("undefined");function hOa(e){return e!==null&&!mTn(e)&&e.constructor!==null&&!mTn(e.constructor)&&I6(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var _8p=zNt("ArrayBuffer");function M0S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&_8p(e.buffer),t}var D0S=Z0o("string"),I6=Z0o("function"),h8p=Z0o("number"),yOa=e=>e!==null&&typeof e=="object",B0S=e=>e===!0||e===!1,$0o=e=>{if(X0o(e)!=="object")return!1;let t=Y7s(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(p8p in e)&&!(Y0o in e)},I0S=e=>{if(!yOa(e)||hOa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},C0S=zNt("Date"),q0S=zNt("File"),T0S=zNt("Blob"),R0S=zNt("FileList"),z0S=e=>yOa(e)&&I6(e.pipe),N0S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||I6(e.append)&&((t=X0o(e))==="formdata"||t==="object"&&I6(e.toString)&&e.toString()==="[object FormData]"))},F0S=zNt("URLSearchParams"),[Q0S,U0S,L0S,V0S]=["ReadableStream","Request","Response","Headers"].map(zNt),W0S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function bOa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),PTn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(hOa(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function y8p(e,t){if(hOa(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var t6i=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,b8p=e=>!mTn(e)&&e!==t6i;function $7s(){let{caseless:e,skipUndefined:t}=b8p(this)&&this||{},r={},i=(n,a)=>{let o=e&&y8p(r,a)||a;$0o(r[o])&&$0o(n)?r[o]=$7s(r[o],n):$0o(n)?r[o]=$7s({},n):PTn(n)?r[o]=n.slice():(!t||!mTn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&bOa(arguments[n],i);return r}var x0S=(e,t,r,{allOwnKeys:i}={})=>(bOa(t,(n,a)=>{r&&I6(n)?e[a]=_Oa(n,r):e[a]=n},{allOwnKeys:i}),e),G0S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),H0S=(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)},K0S=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&Y7s(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},J0S=(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},$0S=e=>{if(!e)return null;if(PTn(e))return e;let t=e.length;if(!h8p(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},Y0S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Y7s(Uint8Array)),X0S=(e,t)=>{let i=(e&&e[Y0o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},Z0S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},k0S=zNt("HTMLFormElement"),ePS=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),d8p=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),tPS=zNt("RegExp"),v8p=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};bOa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},rPS=e=>{v8p(e,(t,r)=>{if(I6(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(I6(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+"'")})}})},iPS=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return PTn(e)?i(e):i(String(e).split(t)),r},nPS=()=>{},aPS=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function oPS(e){return!!(e&&I6(e.append)&&e[p8p]==="FormData"&&e[Y0o])}var uPS=e=>{let t=new Array(10),r=(i,n)=>{if(yOa(i)){if(t.indexOf(i)>=0)return;if(hOa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=PTn(i)?[]:{};return bOa(i,(o,c)=>{let f=r(o,n+1);!mTn(f)&&(a[c]=f)}),t[n]=void 0,a}}return i};return r(e,0)},sPS=zNt("AsyncFunction"),cPS=e=>e&&(yOa(e)||I6(e))&&I6(e.then)&&I6(e.catch),g8p=((e,t)=>e?setImmediate:t?((r,i)=>(t6i.addEventListener("message",({source:n,data:a})=>{n===t6i&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),t6i.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",I6(t6i.postMessage)),lPS=typeof queueMicrotask<"u"?queueMicrotask.bind(t6i):typeof process<"u"&&process.nextTick||g8p,fPS=e=>e!=null&&I6(e[Y0o]),kt={isArray:PTn,isArrayBuffer:_8p,isBuffer:hOa,isFormData:N0S,isArrayBufferView:M0S,isString:D0S,isNumber:h8p,isBoolean:B0S,isObject:yOa,isPlainObject:$0o,isEmptyObject:I0S,isReadableStream:Q0S,isRequest:U0S,isResponse:L0S,isHeaders:V0S,isUndefined:mTn,isDate:C0S,isFile:q0S,isBlob:T0S,isRegExp:tPS,isFunction:I6,isStream:z0S,isURLSearchParams:F0S,isTypedArray:Y0S,isFileList:R0S,forEach:bOa,merge:$7s,extend:x0S,trim:W0S,stripBOM:G0S,inherits:H0S,toFlatObject:K0S,kindOf:X0o,kindOfTest:zNt,endsWith:J0S,toArray:$0S,forEachEntry:X0S,matchAll:Z0S,isHTMLForm:k0S,hasOwnProperty:d8p,hasOwnProp:d8p,reduceDescriptors:v8p,freezeMethods:rPS,toObjectSet:iPS,toCamelCase:ePS,noop:nPS,toFiniteNumber:aPS,findKey:y8p,global:t6i,isContextDefined:b8p,isSpecCompliantForm:oPS,toJSONObject:uPS,isAsyncFn:sPS,isThenable:cPS,setImmediate:g8p,asap:lPS,isIterable:fPS};function jTn(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)}kt.inherits(jTn,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:kt.toJSONObject(this.config),code:this.code,status:this.status}}});var O8p=jTn.prototype,A8p={};["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=>{A8p[e]={value:e}});Object.defineProperties(jTn,A8p);Object.defineProperty(O8p,"isAxiosError",{value:!0});jTn.from=(e,t,r,i,n,a)=>{let o=Object.create(O8p);kt.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",f=t==null&&e?e.code:t;return jTn.call(o,c,f,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var ya=jTn;var m8p=ae(Q7i(),1),k0o=m8p.default;function X7s(e){return kt.isPlainObject(e)||kt.isArray(e)}function j8p(e){return kt.endsWith(e,"[]")?e.slice(0,-2):e}function P8p(e,t,r){return e?e.concat(t).map(function(n,a){return n=j8p(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function dPS(e){return kt.isArray(e)&&!e.some(X7s)}var pPS=kt.toFlatObject(kt,{},null,function(t){return/^is[A-Z]/.test(t)});function _PS(e,t,r){if(!kt.isObject(e))throw new TypeError("target must be an object");t=t||new(k0o||FormData),r=kt.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!kt.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&kt.isSpecCompliantForm(t);if(!kt.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(kt.isDate(h))return h.toISOString();if(kt.isBoolean(h))return h.toString();if(!f&&kt.isBlob(h))throw new ya("Blob is not supported. Use a Buffer instead.");return kt.isArrayBuffer(h)||kt.isTypedArray(h)?f&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(kt.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(kt.isArray(h)&&dPS(h)||(kt.isFileList(h)||kt.endsWith(y,"[]"))&&(v=kt.toArray(h)))return y=j8p(y),v.forEach(function(A,g){!(kt.isUndefined(A)||A===null)&&t.append(o===!0?P8p([y],g,a):o===null?y:y+"[]",s(A))}),!1}return X7s(h)?!0:(t.append(P8p(b,y,a),s(h)),!1)}let l=[],p=Object.assign(pPS,{defaultVisitor:u,convertValue:s,isVisitable:X7s});function _(h,y){if(!kt.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),kt.forEach(h,function(v,O){(!(kt.isUndefined(v)||v===null)&&n.call(t,v,kt.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),l.pop()}}if(!kt.isObject(e))throw new TypeError("data must be an object");return _(e),t}var NBi=_PS;function w8p(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function E8p(e,t){this._pairs=[],e&&NBi(e,this,t)}var S8p=E8p.prototype;S8p.append=function(t,r){this._pairs.push([t,r])};S8p.toString=function(t){let r=t?function(i){return t.call(this,i,w8p)}:w8p;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var M8p=E8p;function hPS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function r6i(e,t,r){if(!t)return e;let i=r&&r.encode||hPS;kt.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=kt.isURLSearchParams(t)?t.toString():new M8p(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Z7s=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){kt.forEach(this.handlers,function(i){i!==null&&t(i)})}},k7s=Z7s;var wTn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var C8p=ae(require("crypto"),1);var D8p=ae(require("url"),1),B8p=D8p.default.URLSearchParams;var eHs="abcdefghijklmnopqrstuvwxyz",I8p="0123456789",q8p={DIGIT:I8p,ALPHA:eHs,ALPHA_DIGIT:eHs+eHs.toUpperCase()+I8p},yPS=(e=16,t=q8p.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);C8p.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},T8p={isNode:!0,classes:{URLSearchParams:B8p,FormData:k0o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:q8p,generateString:yPS,protocols:["http","https","file","data"]};var iHs={};Kt(iHs,{hasBrowserEnv:()=>rHs,hasStandardBrowserEnv:()=>bPS,hasStandardBrowserWebWorkerEnv:()=>vPS,navigator:()=>tHs,origin:()=>gPS});var rHs=typeof window<"u"&&typeof document<"u",tHs=typeof navigator=="object"&&navigator||void 0,bPS=rHs&&(!tHs||["ReactNative","NativeScript","NS"].indexOf(tHs.product)<0),vPS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",gPS=rHs&&window.location.href||"http://localhost";var OA={...iHs,...T8p};function nHs(e,t){return NBi(e,new OA.classes.URLSearchParams,{visitor:function(r,i,n,a){return OA.isNode&&kt.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function OPS(e){return kt.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function APS(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 mPS(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),f=a>=r.length;return o=!o&&kt.isArray(n)?n.length:o,f?(kt.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!kt.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&kt.isArray(n[o])&&(n[o]=APS(n[o])),!c)}if(kt.isFormData(e)&&kt.isFunction(e.entries)){let r={};return kt.forEachEntry(e,(i,n)=>{t(OPS(i),n,r,0)}),r}return null}var ePo=mPS;function PPS(e,t,r){if(kt.isString(e))try{return(t||JSON.parse)(e),kt.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var aHs={transitional:wTn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=kt.isObject(t);if(a&&kt.isHTMLForm(t)&&(t=new FormData(t)),kt.isFormData(t))return n?JSON.stringify(ePo(t)):t;if(kt.isArrayBuffer(t)||kt.isBuffer(t)||kt.isStream(t)||kt.isFile(t)||kt.isBlob(t)||kt.isReadableStream(t))return t;if(kt.isArrayBufferView(t))return t.buffer;if(kt.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return nHs(t,this.formSerializer).toString();if((c=kt.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return NBi(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),PPS(t)):t}],transformResponse:[function(t){let r=this.transitional||aHs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(kt.isResponse(t)||kt.isReadableStream(t))return t;if(t&&kt.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?ya.from(c,ya.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData: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}}};kt.forEach(["delete","get","head","post","put","patch"],e=>{aHs.headers[e]={}});var ETn=aHs;var jPS=kt.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"]),R8p=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1155
|
+
`);for(let c=n;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let s=WLp.test(f)?f.replace(WLp,"$1"):f;if(!s.match(/\S*Error: /)){for(let u of r){let l=u(s);if(l){a.push(l);break}}if(a.length>=a8p)break}}return A0S(a)}}function A0S(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,a8p).map(r=>({...r,filename:r.filename||m0S(t).filename,function:r.function||o8p}))}function m0S(e){return e[e.length-1]||{}}yTn.stackParser=O0S(CmS());yTn.frameModifiers=[RmS];var vTn=class extends V7s{getLibraryId(){return"posthog-node"}};var H0o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new vTn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"2.15.2",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var dOa=class{async sendEvent(){}async identify(){}async flush(){}};var OTn=require("fs/promises"),l8p=require("os"),f8p=require("path");var u8p=ae(require("crypto")),J0o=new Uint8Array(256),K0o=J0o.length;function H7s(){return K0o>J0o.length-16&&(u8p.default.randomFillSync(J0o),K0o=0),J0o.slice(K0o,K0o+=16)}var RQ=[];for(let e=0;e<256;++e)RQ.push((e+256).toString(16).slice(1));function s8p(e,t=0){return RQ[e[t+0]]+RQ[e[t+1]]+RQ[e[t+2]]+RQ[e[t+3]]+"-"+RQ[e[t+4]]+RQ[e[t+5]]+"-"+RQ[e[t+6]]+RQ[e[t+7]]+"-"+RQ[e[t+8]]+RQ[e[t+9]]+"-"+RQ[e[t+10]]+RQ[e[t+11]]+RQ[e[t+12]]+RQ[e[t+13]]+RQ[e[t+14]]+RQ[e[t+15]]}var c8p=ae(require("crypto")),K7s={randomUUID:c8p.default.randomUUID};function P0S(e,t,r){if(K7s.randomUUID&&!t&&!e)return K7s.randomUUID();e=e||{};let i=e.random||(e.rng||H7s)();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 s8p(i)}var ehe=P0S;var j0S="id",w0S=".fern",pOa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new vTn(r),this.userId=t==null?void 0:_8s(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:"2.15.2",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ft(Lr.of((0,l8p.homedir)()),Ze.of(w0S),Ze.of(j0S));await Ri(t)||(await(0,OTn.mkdir)((0,f8p.dirname)(t),{recursive:!0}),await(0,OTn.writeFile)(t,ehe())),this.persistedDistinctId=(await(0,OTn.readFile)(t)).toString()}return this.persistedDistinctId}};var J7s;async function ATn(){return J7s==null&&(J7s=await E0S()),J7s}async function E0S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new dOa;let r=await fbo();return r!=null?new pOa({token:r,posthogApiKey:e}):await jqn()!=null?new H0o({posthogApiKey:e}):new pOa({token:void 0,posthogApiKey:e})}catch{return new dOa}}function _Oa(e,t){return function(){return e.apply(t,arguments)}}var{toString:S0S}=Object.prototype,{getPrototypeOf:Y7s}=Object,{iterator:Y0o,toStringTag:p8p}=Symbol,X0o=(e=>t=>{let r=S0S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),zNt=e=>(e=e.toLowerCase(),t=>X0o(t)===e),Z0o=e=>t=>typeof t===e,{isArray:PTn}=Array,mTn=Z0o("undefined");function hOa(e){return e!==null&&!mTn(e)&&e.constructor!==null&&!mTn(e.constructor)&&I6(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var _8p=zNt("ArrayBuffer");function M0S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&_8p(e.buffer),t}var D0S=Z0o("string"),I6=Z0o("function"),h8p=Z0o("number"),yOa=e=>e!==null&&typeof e=="object",B0S=e=>e===!0||e===!1,$0o=e=>{if(X0o(e)!=="object")return!1;let t=Y7s(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(p8p in e)&&!(Y0o in e)},I0S=e=>{if(!yOa(e)||hOa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},C0S=zNt("Date"),q0S=zNt("File"),T0S=zNt("Blob"),R0S=zNt("FileList"),z0S=e=>yOa(e)&&I6(e.pipe),N0S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||I6(e.append)&&((t=X0o(e))==="formdata"||t==="object"&&I6(e.toString)&&e.toString()==="[object FormData]"))},F0S=zNt("URLSearchParams"),[Q0S,U0S,L0S,V0S]=["ReadableStream","Request","Response","Headers"].map(zNt),W0S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function bOa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),PTn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(hOa(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function y8p(e,t){if(hOa(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var t6i=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,b8p=e=>!mTn(e)&&e!==t6i;function $7s(){let{caseless:e,skipUndefined:t}=b8p(this)&&this||{},r={},i=(n,a)=>{let o=e&&y8p(r,a)||a;$0o(r[o])&&$0o(n)?r[o]=$7s(r[o],n):$0o(n)?r[o]=$7s({},n):PTn(n)?r[o]=n.slice():(!t||!mTn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&bOa(arguments[n],i);return r}var x0S=(e,t,r,{allOwnKeys:i}={})=>(bOa(t,(n,a)=>{r&&I6(n)?e[a]=_Oa(n,r):e[a]=n},{allOwnKeys:i}),e),G0S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),H0S=(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)},K0S=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&Y7s(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},J0S=(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},$0S=e=>{if(!e)return null;if(PTn(e))return e;let t=e.length;if(!h8p(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},Y0S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Y7s(Uint8Array)),X0S=(e,t)=>{let i=(e&&e[Y0o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},Z0S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},k0S=zNt("HTMLFormElement"),ePS=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),d8p=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),tPS=zNt("RegExp"),v8p=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};bOa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},rPS=e=>{v8p(e,(t,r)=>{if(I6(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(I6(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+"'")})}})},iPS=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return PTn(e)?i(e):i(String(e).split(t)),r},nPS=()=>{},aPS=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function oPS(e){return!!(e&&I6(e.append)&&e[p8p]==="FormData"&&e[Y0o])}var uPS=e=>{let t=new Array(10),r=(i,n)=>{if(yOa(i)){if(t.indexOf(i)>=0)return;if(hOa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=PTn(i)?[]:{};return bOa(i,(o,c)=>{let f=r(o,n+1);!mTn(f)&&(a[c]=f)}),t[n]=void 0,a}}return i};return r(e,0)},sPS=zNt("AsyncFunction"),cPS=e=>e&&(yOa(e)||I6(e))&&I6(e.then)&&I6(e.catch),g8p=((e,t)=>e?setImmediate:t?((r,i)=>(t6i.addEventListener("message",({source:n,data:a})=>{n===t6i&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),t6i.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",I6(t6i.postMessage)),lPS=typeof queueMicrotask<"u"?queueMicrotask.bind(t6i):typeof process<"u"&&process.nextTick||g8p,fPS=e=>e!=null&&I6(e[Y0o]),kt={isArray:PTn,isArrayBuffer:_8p,isBuffer:hOa,isFormData:N0S,isArrayBufferView:M0S,isString:D0S,isNumber:h8p,isBoolean:B0S,isObject:yOa,isPlainObject:$0o,isEmptyObject:I0S,isReadableStream:Q0S,isRequest:U0S,isResponse:L0S,isHeaders:V0S,isUndefined:mTn,isDate:C0S,isFile:q0S,isBlob:T0S,isRegExp:tPS,isFunction:I6,isStream:z0S,isURLSearchParams:F0S,isTypedArray:Y0S,isFileList:R0S,forEach:bOa,merge:$7s,extend:x0S,trim:W0S,stripBOM:G0S,inherits:H0S,toFlatObject:K0S,kindOf:X0o,kindOfTest:zNt,endsWith:J0S,toArray:$0S,forEachEntry:X0S,matchAll:Z0S,isHTMLForm:k0S,hasOwnProperty:d8p,hasOwnProp:d8p,reduceDescriptors:v8p,freezeMethods:rPS,toObjectSet:iPS,toCamelCase:ePS,noop:nPS,toFiniteNumber:aPS,findKey:y8p,global:t6i,isContextDefined:b8p,isSpecCompliantForm:oPS,toJSONObject:uPS,isAsyncFn:sPS,isThenable:cPS,setImmediate:g8p,asap:lPS,isIterable:fPS};function jTn(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)}kt.inherits(jTn,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:kt.toJSONObject(this.config),code:this.code,status:this.status}}});var O8p=jTn.prototype,A8p={};["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=>{A8p[e]={value:e}});Object.defineProperties(jTn,A8p);Object.defineProperty(O8p,"isAxiosError",{value:!0});jTn.from=(e,t,r,i,n,a)=>{let o=Object.create(O8p);kt.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",f=t==null&&e?e.code:t;return jTn.call(o,c,f,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var ya=jTn;var m8p=ae(Q7i(),1),k0o=m8p.default;function X7s(e){return kt.isPlainObject(e)||kt.isArray(e)}function j8p(e){return kt.endsWith(e,"[]")?e.slice(0,-2):e}function P8p(e,t,r){return e?e.concat(t).map(function(n,a){return n=j8p(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function dPS(e){return kt.isArray(e)&&!e.some(X7s)}var pPS=kt.toFlatObject(kt,{},null,function(t){return/^is[A-Z]/.test(t)});function _PS(e,t,r){if(!kt.isObject(e))throw new TypeError("target must be an object");t=t||new(k0o||FormData),r=kt.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!kt.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&kt.isSpecCompliantForm(t);if(!kt.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(kt.isDate(h))return h.toISOString();if(kt.isBoolean(h))return h.toString();if(!f&&kt.isBlob(h))throw new ya("Blob is not supported. Use a Buffer instead.");return kt.isArrayBuffer(h)||kt.isTypedArray(h)?f&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(kt.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(kt.isArray(h)&&dPS(h)||(kt.isFileList(h)||kt.endsWith(y,"[]"))&&(v=kt.toArray(h)))return y=j8p(y),v.forEach(function(A,g){!(kt.isUndefined(A)||A===null)&&t.append(o===!0?P8p([y],g,a):o===null?y:y+"[]",s(A))}),!1}return X7s(h)?!0:(t.append(P8p(b,y,a),s(h)),!1)}let l=[],p=Object.assign(pPS,{defaultVisitor:u,convertValue:s,isVisitable:X7s});function _(h,y){if(!kt.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),kt.forEach(h,function(v,O){(!(kt.isUndefined(v)||v===null)&&n.call(t,v,kt.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),l.pop()}}if(!kt.isObject(e))throw new TypeError("data must be an object");return _(e),t}var NBi=_PS;function w8p(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function E8p(e,t){this._pairs=[],e&&NBi(e,this,t)}var S8p=E8p.prototype;S8p.append=function(t,r){this._pairs.push([t,r])};S8p.toString=function(t){let r=t?function(i){return t.call(this,i,w8p)}:w8p;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var M8p=E8p;function hPS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function r6i(e,t,r){if(!t)return e;let i=r&&r.encode||hPS;kt.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=kt.isURLSearchParams(t)?t.toString():new M8p(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Z7s=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){kt.forEach(this.handlers,function(i){i!==null&&t(i)})}},k7s=Z7s;var wTn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var C8p=ae(require("crypto"),1);var D8p=ae(require("url"),1),B8p=D8p.default.URLSearchParams;var eHs="abcdefghijklmnopqrstuvwxyz",I8p="0123456789",q8p={DIGIT:I8p,ALPHA:eHs,ALPHA_DIGIT:eHs+eHs.toUpperCase()+I8p},yPS=(e=16,t=q8p.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);C8p.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},T8p={isNode:!0,classes:{URLSearchParams:B8p,FormData:k0o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:q8p,generateString:yPS,protocols:["http","https","file","data"]};var iHs={};Kt(iHs,{hasBrowserEnv:()=>rHs,hasStandardBrowserEnv:()=>bPS,hasStandardBrowserWebWorkerEnv:()=>vPS,navigator:()=>tHs,origin:()=>gPS});var rHs=typeof window<"u"&&typeof document<"u",tHs=typeof navigator=="object"&&navigator||void 0,bPS=rHs&&(!tHs||["ReactNative","NativeScript","NS"].indexOf(tHs.product)<0),vPS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",gPS=rHs&&window.location.href||"http://localhost";var OA={...iHs,...T8p};function nHs(e,t){return NBi(e,new OA.classes.URLSearchParams,{visitor:function(r,i,n,a){return OA.isNode&&kt.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function OPS(e){return kt.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function APS(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 mPS(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),f=a>=r.length;return o=!o&&kt.isArray(n)?n.length:o,f?(kt.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!kt.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&kt.isArray(n[o])&&(n[o]=APS(n[o])),!c)}if(kt.isFormData(e)&&kt.isFunction(e.entries)){let r={};return kt.forEachEntry(e,(i,n)=>{t(OPS(i),n,r,0)}),r}return null}var ePo=mPS;function PPS(e,t,r){if(kt.isString(e))try{return(t||JSON.parse)(e),kt.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var aHs={transitional:wTn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=kt.isObject(t);if(a&&kt.isHTMLForm(t)&&(t=new FormData(t)),kt.isFormData(t))return n?JSON.stringify(ePo(t)):t;if(kt.isArrayBuffer(t)||kt.isBuffer(t)||kt.isStream(t)||kt.isFile(t)||kt.isBlob(t)||kt.isReadableStream(t))return t;if(kt.isArrayBufferView(t))return t.buffer;if(kt.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return nHs(t,this.formSerializer).toString();if((c=kt.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return NBi(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),PPS(t)):t}],transformResponse:[function(t){let r=this.transitional||aHs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(kt.isResponse(t)||kt.isReadableStream(t))return t;if(t&&kt.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?ya.from(c,ya.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData: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}}};kt.forEach(["delete","get","head","post","put","patch"],e=>{aHs.headers[e]={}});var ETn=aHs;var jPS=kt.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"]),R8p=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1156
1156
|
`).forEach(function(o){n=o.indexOf(":"),r=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim(),!(!r||t[r]&&jPS[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var z8p=Symbol("internals");function vOa(e){return e&&String(e).trim().toLowerCase()}function tPo(e){return e===!1||e==null?e:kt.isArray(e)?e.map(tPo):String(e)}function wPS(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 EPS=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function oHs(e,t,r,i,n){if(kt.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!kt.isString(t)){if(kt.isString(i))return t.indexOf(i)!==-1;if(kt.isRegExp(i))return i.test(t)}}function SPS(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function MPS(e,t){let r=kt.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,o){return this[i].call(this,t,n,a,o)},configurable:!0})})}var STn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,f,s){let u=vOa(f);if(!u)throw new Error("header name must be a non-empty string");let l=kt.findKey(n,u);(!l||n[l]===void 0||s===!0||s===void 0&&n[l]!==!1)&&(n[l||f]=tPo(c))}let o=(c,f)=>kt.forEach(c,(s,u)=>a(s,u,f));if(kt.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(kt.isString(t)&&(t=t.trim())&&!EPS(t))o(R8p(t),r);else if(kt.isObject(t)&&kt.isIterable(t)){let c={},f,s;for(let u of t){if(!kt.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(f=c[s])?kt.isArray(f)?[...f,u[1]]:[f,u[1]]:u[1]}o(c,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=vOa(t),t){let i=kt.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return wPS(n);if(kt.isFunction(r))return r.call(this,n,i);if(kt.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=vOa(t),t){let i=kt.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||oHs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(o){if(o=vOa(o),o){let c=kt.findKey(i,o);c&&(!r||oHs(i,i[c],c,r))&&(delete i[c],n=!0)}}return kt.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||oHs(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return kt.forEach(this,(n,a)=>{let o=kt.findKey(i,a);if(o){r[o]=tPo(n),delete r[a];return}let c=t?SPS(a):String(a).trim();c!==a&&delete r[a],r[c]=tPo(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return kt.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&kt.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(`
|
|
1157
1157
|
`)}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[z8p]=this[z8p]={accessors:{}}).accessors,n=this.prototype;function a(o){let c=vOa(o);i[c]||(MPS(n,o),i[c]=!0)}return kt.isArray(t)?t.forEach(a):a(t),this}};STn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);kt.reduceDescriptors(STn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});kt.freezeMethods(STn);var US=STn;function gOa(e,t){let r=this||ETn,i=t||r,n=US.from(i.headers),a=i.data;return kt.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function OOa(e){return!!(e&&e.__CANCEL__)}function N8p(e,t,r){ya.call(this,e??"canceled",ya.ERR_CANCELED,t,r),this.name="CanceledError"}kt.inherits(N8p,ya,{__CANCEL__:!0});var the=N8p;function o9t(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new ya("Request failed with status code "+r.status,[ya.ERR_BAD_REQUEST,ya.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function uHs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function sHs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function i6i(e,t,r){let i=!uHs(t);return e&&(i||r==!1)?sHs(e,t):t}var k8p=ae(m0o(),1),eVp=ae(require("http"),1),tVp=ae(require("https"),1),rVp=ae(require("util"),1),iVp=ae(c7s(),1),Gbi=ae(require("zlib"),1);var n6i="1.12.2";function AOa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var DPS=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function cHs(e,t,r){let i=r&&r.Blob||OA.classes.Blob,n=AOa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=DPS.exec(e);if(!a)throw new ya("Invalid URL",ya.ERR_INVALID_URL);let o=a[1],c=a[2],f=a[3],s=Buffer.from(decodeURIComponent(f),c?"base64":"utf8");if(t){if(!i)throw new ya("Blob is not supported",ya.ERR_NOT_SUPPORT);return new i([s],{type:o})}return s}throw new ya("Unsupported protocol "+n,ya.ERR_NOT_SUPPORT)}var o6i=ae(require("stream"),1);var F8p=ae(require("stream"),1);var lHs=Symbol("internals"),fHs=class extends F8p.default.Transform{constructor(t){t=kt.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!kt.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[lHs]={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[lHs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[lHs],a=n.maxRate,o=this.readableHighWaterMark,c=n.timeWindow,f=1e3/c,s=a/f,u=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,l=(_,h)=>{let y=Buffer.byteLength(_);n.bytesSeen+=y,n.bytes+=y,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(_)?process.nextTick(h):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(h)}},p=(_,h)=>{let y=Buffer.byteLength(_),b=null,v=o,O,A=0;if(a){let g=Date.now();(!n.ts||(A=g-n.ts)>=c)&&(n.ts=g,O=s-n.bytes,n.bytes=O<0?-O:0,A=0),O=s-n.bytes}if(a){if(O<=0)return setTimeout(()=>{h(null,_)},c-A);O<v&&(v=O)}v&&y>v&&y-v>u&&(b=_.subarray(v),_=_.subarray(0,v)),l(_,b?()=>{process.nextTick(h,null,b)}:h)};p(t,function _(h,y){if(h)return i(h);y?p(y,_):i(null)})}},dHs=fHs;var nVp=require("events");var U8p=ae(require("util"),1),L8p=require("stream");var{asyncIterator:Q8p}=Symbol,BPS=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[Q8p]?yield*e[Q8p]():yield e},rPo=BPS;var IPS=OA.ALPHABET.ALPHA_DIGIT+"-_",mOa=typeof TextEncoder=="function"?new TextEncoder:new U8p.default.TextEncoder,a6i=`\r
|
|
1158
1158
|
`,CPS=mOa.encode(a6i),qPS=2,pHs=class{constructor(t,r){let{escapeName:i}=this.constructor,n=kt.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${a6i}`;n?r=mOa.encode(String(r).replace(/\r?\n|\r\n?/g,a6i)):a+=`Content-Type: ${r.type||"application/octet-stream"}${a6i}`,this.headers=mOa.encode(a+a6i),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+qPS,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;kt.isTypedArray(t)?yield t:yield*rPo(t),yield CPS}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},TPS=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+OA.generateString(n,IPS)}=r||{};if(!kt.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let o=mOa.encode("--"+a+a6i),c=mOa.encode("--"+a+"--"+a6i),f=c.byteLength,s=Array.from(e.entries()).map(([l,p])=>{let _=new pHs(l,p);return f+=_.size,_});f+=o.byteLength*s.length,f=kt.toFiniteNumber(f);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(f)&&(u["Content-Length"]=f),t&&t(u),L8p.Readable.from((async function*(){for(let l of s)yield o,yield*l.encode();yield c})())},V8p=TPS;var W8p=ae(require("stream"),1),_Hs=class extends W8p.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)}},x8p=_Hs;var RPS=(e,t)=>kt.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,G8p=RPS;function zPS(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,o;return t=t!==void 0?t:1e3,function(f){let s=Date.now(),u=i[a];o||(o=s),r[n]=f,i[n]=s;let l=a,p=0;for(;l!==n;)p+=r[l++],l=l%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-o<t)return;let _=u&&s-u;return _?Math.round(p*1e3/_):void 0}}var H8p=zPS;function NPS(e,t){let r=0,i=1e3/t,n,a,o=(s,u=Date.now())=>{r=u,n=null,a&&(clearTimeout(a),a=null),e(...s)};return[(...s)=>{let u=Date.now(),l=u-r;l>=i?o(s,u):(n=s,a||(a=setTimeout(()=>{a=null,o(n)},i-l)))},()=>n&&o(n)]}var K8p=NPS;var xbi=(e,t,r=3)=>{let i=0,n=H8p(50,250);return K8p(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,f=o-i,s=n(f),u=o<=c;i=o;let l={loaded:o,total:c,progress:c?o/c:void 0,bytes:f,rate:s||void 0,estimated:s&&c&&u?(c-o)/s:void 0,event:a,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(l)},r)},MTn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},DTn=e=>(...t)=>kt.asap(()=>e(...t));function hHs(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;let t=e.indexOf(",");if(t<0)return 0;let r=e.slice(5,t),i=e.slice(t+1);if(/;base64/i.test(r)){let a=i.length,o=i.length;for(let p=0;p<o;p++)if(i.charCodeAt(p)===37&&p+2<o){let _=i.charCodeAt(p+1),h=i.charCodeAt(p+2);(_>=48&&_<=57||_>=65&&_<=70||_>=97&&_<=102)&&(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102)&&(a-=2,p+=2)}let c=0,f=o-1,s=p=>p>=2&&i.charCodeAt(p-2)===37&&i.charCodeAt(p-1)===51&&(i.charCodeAt(p)===68||i.charCodeAt(p)===100);f>=0&&(i.charCodeAt(f)===61?(c++,f--):s(f)&&(c++,f-=3)),c===1&&f>=0&&(i.charCodeAt(f)===61||s(f))&&c++;let l=Math.floor(a/4)*3-(c||0);return l>0?l:0}return Buffer.byteLength(i,"utf8")}var J8p={flush:Gbi.default.constants.Z_SYNC_FLUSH,finishFlush:Gbi.default.constants.Z_SYNC_FLUSH},FPS={flush:Gbi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:Gbi.default.constants.BROTLI_OPERATION_FLUSH},$8p=kt.isFunction(Gbi.default.createBrotliDecompress),{http:QPS,https:UPS}=iVp.default,LPS=/https:?/,Y8p=OA.protocols.map(e=>e+":"),X8p=(e,[t,r])=>(e.on("end",r).on("error",r),t);function VPS(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function aVp(e,t,r){let i=t;if(!i&&i!==!1){let n=k8p.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){aVp(a,t,a.href)}}var WPS=typeof process<"u"&&kt.kindOf(process)==="process",xPS=e=>new Promise((t,r)=>{let i,n,a=(f,s)=>{n||(n=!0,i&&i(f,s))},o=f=>{a(f),t(f)},c=f=>{a(f,!0),r(f)};e(o,c,f=>i=f).catch(c)}),GPS=({address:e,family:t})=>{if(!kt.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},Z8p=(e,t)=>GPS(kt.isObject(e)?e:{address:e,family:t}),oVp=WPS&&function(t){return xPS(async function(i,n,a){let{data:o,lookup:c,family:f}=t,{responseType:s,responseEncoding:u}=t,l=t.method.toUpperCase(),p,_=!1,h;if(c){let H=G8p(c,ue=>kt.isArray(ue)?ue:[ue]);c=(ue,se,x)=>{H(ue,se,(G,Pe,ne)=>{if(G)return x(G);let Ee=kt.isArray(Pe)?Pe.map(Qe=>Z8p(Qe)):[Z8p(Pe,ne)];se.all?x(G,Ee):x(G,Ee[0].address,Ee[0].family)})}}let y=new nVp.EventEmitter,b=()=>{t.cancelToken&&t.cancelToken.unsubscribe(v),t.signal&&t.signal.removeEventListener("abort",v),y.removeAllListeners()};a((H,ue)=>{p=!0,ue&&(_=!0,b())});function v(H){y.emit("abort",!H||H.type?new the(null,t,h):H)}y.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(v),t.signal&&(t.signal.aborted?v():t.signal.addEventListener("abort",v)));let O=i6i(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(O,OA.hasBrowserEnv?OA.origin:void 0),g=A.protocol||Y8p[0];if(g==="data:"){if(t.maxContentLength>-1){let ue=String(t.url||O||"");if(hHs(ue)>t.maxContentLength)return n(new ya("maxContentLength size of "+t.maxContentLength+" exceeded",ya.ERR_BAD_RESPONSE,t))}let H;if(l!=="GET")return o9t(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{H=cHs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(ue){throw ya.from(ue,ya.ERR_BAD_REQUEST,t)}return s==="text"?(H=H.toString(u),(!u||u==="utf8")&&(H=kt.stripBOM(H))):s==="stream"&&(H=o6i.default.Readable.from(H)),o9t(i,n,{data:H,status:200,statusText:"OK",headers:new US,config:t})}if(Y8p.indexOf(g)===-1)return n(new ya("Unsupported protocol "+g,ya.ERR_BAD_REQUEST,t));let m=US.from(t.headers).normalize();m.set("User-Agent","axios/"+n6i,!1);let{onUploadProgress:j,onDownloadProgress:M}=t,E=t.maxRate,D,B;if(kt.isSpecCompliantForm(o)){let H=m.getContentType(/boundary=([-_\w\d]{10,70})/i);o=V8p(o,ue=>{m.set(ue)},{tag:`axios-${n6i}-boundary`,boundary:H&&H[1]||void 0})}else if(kt.isFormData(o)&&kt.isFunction(o.getHeaders)){if(m.set(o.getHeaders()),!m.hasContentLength())try{let H=await rVp.default.promisify(o.getLength).call(o);Number.isFinite(H)&&H>=0&&m.setContentLength(H)}catch{}}else if(kt.isBlob(o)||kt.isFile(o))o.size&&m.setContentType(o.type||"application/octet-stream"),m.setContentLength(o.size||0),o=o6i.default.Readable.from(rPo(o));else if(o&&!kt.isStream(o)){if(!Buffer.isBuffer(o))if(kt.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(kt.isString(o))o=Buffer.from(o,"utf-8");else return n(new ya("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",ya.ERR_BAD_REQUEST,t));if(m.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return n(new ya("Request body larger than maxBodyLength limit",ya.ERR_BAD_REQUEST,t))}let F=kt.toFiniteNumber(m.getContentLength());kt.isArray(E)?(D=E[0],B=E[1]):D=B=E,o&&(j||D)&&(kt.isStream(o)||(o=o6i.default.Readable.from(o,{objectMode:!1})),o=o6i.default.pipeline([o,new dHs({maxRate:kt.toFiniteNumber(D)})],kt.noop),j&&o.on("progress",X8p(o,MTn(F,xbi(DTn(j),!1,3)))));let N;if(t.auth){let H=t.auth.username||"",ue=t.auth.password||"";N=H+":"+ue}if(!N&&A.username){let H=A.username,ue=A.password;N=H+":"+ue}N&&m.delete("authorization");let T;try{T=r6i(A.pathname+A.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(H){let ue=new Error(H.message);return ue.config=t,ue.url=t.url,ue.exists=!0,n(ue)}m.set("Accept-Encoding","gzip, compress, deflate"+($8p?", br":""),!1);let R={path:T,method:l,headers:m.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:N,protocol:g,family:f,beforeRedirect:VPS,beforeRedirects:{}};!kt.isUndefined(c)&&(R.lookup=c),t.socketPath?R.socketPath=t.socketPath:(R.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,R.port=A.port,aVp(R,t.proxy,g+"//"+A.hostname+(A.port?":"+A.port:"")+R.path));let Q,U=LPS.test(R.protocol);if(R.agent=U?t.httpsAgent:t.httpAgent,t.transport?Q=t.transport:t.maxRedirects===0?Q=U?tVp.default:eVp.default:(t.maxRedirects&&(R.maxRedirects=t.maxRedirects),t.beforeRedirect&&(R.beforeRedirects.config=t.beforeRedirect),Q=U?UPS:QPS),t.maxBodyLength>-1?R.maxBodyLength=t.maxBodyLength:R.maxBodyLength=1/0,t.insecureHTTPParser&&(R.insecureHTTPParser=t.insecureHTTPParser),h=Q.request(R,function(ue){if(h.destroyed)return;let se=[ue],x=+ue.headers["content-length"];if(M||B){let Qe=new dHs({maxRate:kt.toFiniteNumber(B)});M&&Qe.on("progress",X8p(Qe,MTn(x,xbi(DTn(M),!0,3)))),se.push(Qe)}let G=ue,Pe=ue.req||h;if(t.decompress!==!1&&ue.headers["content-encoding"])switch((l==="HEAD"||ue.statusCode===204)&&delete ue.headers["content-encoding"],(ue.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":se.push(Gbi.default.createUnzip(J8p)),delete ue.headers["content-encoding"];break;case"deflate":se.push(new x8p),se.push(Gbi.default.createUnzip(J8p)),delete ue.headers["content-encoding"];break;case"br":$8p&&(se.push(Gbi.default.createBrotliDecompress(FPS)),delete ue.headers["content-encoding"])}G=se.length>1?o6i.default.pipeline(se,kt.noop):se[0];let ne=o6i.default.finished(G,()=>{ne(),b()}),Ee={status:ue.statusCode,statusText:ue.statusMessage,headers:new US(ue.headers),config:t,request:Pe};if(s==="stream")Ee.data=G,o9t(i,n,Ee);else{let Qe=[],re=0;G.on("data",function(Ve){Qe.push(Ve),re+=Ve.length,t.maxContentLength>-1&&re>t.maxContentLength&&(_=!0,G.destroy(),n(new ya("maxContentLength size of "+t.maxContentLength+" exceeded",ya.ERR_BAD_RESPONSE,t,Pe)))}),G.on("aborted",function(){if(_)return;let Ve=new ya("stream has been aborted",ya.ERR_BAD_RESPONSE,t,Pe);G.destroy(Ve),n(Ve)}),G.on("error",function(Ve){h.destroyed||n(ya.from(Ve,null,t,Pe))}),G.on("end",function(){try{let Ve=Qe.length===1?Qe[0]:Buffer.concat(Qe);s!=="arraybuffer"&&(Ve=Ve.toString(u),(!u||u==="utf8")&&(Ve=kt.stripBOM(Ve))),Ee.data=Ve}catch(Ve){return n(ya.from(Ve,null,t,Ee.request,Ee))}o9t(i,n,Ee)})}y.once("abort",Qe=>{G.destroyed||(G.emit("error",Qe),G.destroy())})}),y.once("abort",H=>{n(H),h.destroy(H)}),h.on("error",function(ue){n(ya.from(ue,null,t,h))}),h.on("socket",function(ue){ue.setKeepAlive(!0,1e3*60)}),t.timeout){let H=parseInt(t.timeout,10);if(Number.isNaN(H)){n(new ya("error trying to parse `config.timeout` to int",ya.ERR_BAD_OPTION_VALUE,t,h));return}h.setTimeout(H,function(){if(p)return;let se=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",x=t.transitional||wTn;t.timeoutErrorMessage&&(se=t.timeoutErrorMessage),n(new ya(se,x.clarifyTimeoutError?ya.ETIMEDOUT:ya.ECONNABORTED,t,h)),v()})}if(kt.isStream(o)){let H=!1,ue=!1;o.on("end",()=>{H=!0}),o.once("error",se=>{ue=!0,h.destroy(se)}),o.on("close",()=>{!H&&!ue&&v(new the("Request stream has been aborted",t,h))}),o.pipe(h)}else h.end(o)})};var uVp=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 sVp=OA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let o=[e+"="+encodeURIComponent(t)];kt.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),kt.isString(i)&&o.push("path="+i),kt.isString(n)&&o.push("domain="+n),a===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var cVp=e=>e instanceof US?{...e}:e;function NNt(e,t){t=t||{};let r={};function i(s,u,l,p){return kt.isPlainObject(s)&&kt.isPlainObject(u)?kt.merge.call({caseless:p},s,u):kt.isPlainObject(u)?kt.merge({},u):kt.isArray(u)?u.slice():u}function n(s,u,l,p){if(kt.isUndefined(u)){if(!kt.isUndefined(s))return i(void 0,s,l,p)}else return i(s,u,l,p)}function a(s,u){if(!kt.isUndefined(u))return i(void 0,u)}function o(s,u){if(kt.isUndefined(u)){if(!kt.isUndefined(s))return i(void 0,s)}else return i(void 0,u)}function c(s,u,l){if(l in t)return i(s,u);if(l in e)return i(void 0,s)}let f={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(s,u,l)=>n(cVp(s),cVp(u),l,!0)};return kt.forEach(Object.keys({...e,...t}),function(u){let l=f[u]||n,p=l(e[u],t[u],u);kt.isUndefined(p)&&l!==c||(r[u]=p)}),r}var iPo=e=>{let t=NNt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=US.from(o),t.url=r6i(i6i(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),kt.isFormData(r)){if(OA.hasStandardBrowserEnv||OA.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(kt.isFunction(r.getHeaders)){let f=r.getHeaders(),s=["content-type","content-length"];Object.entries(f).forEach(([u,l])=>{s.includes(u.toLowerCase())&&o.set(u,l)})}}if(OA.hasStandardBrowserEnv&&(i&&kt.isFunction(i)&&(i=i(t)),i||i!==!1&&uVp(t.url))){let f=n&&a&&sVp.read(a);f&&o.set(n,f)}return t};var HPS=typeof XMLHttpRequest<"u",lVp=HPS&&function(e){return new Promise(function(r,i){let n=iPo(e),a=n.data,o=US.from(n.headers).normalize(),{responseType:c,onUploadProgress:f,onDownloadProgress:s}=n,u,l,p,_,h;function y(){_&&_(),h&&h(),n.cancelToken&&n.cancelToken.unsubscribe(u),n.signal&&n.signal.removeEventListener("abort",u)}let b=new XMLHttpRequest;b.open(n.method.toUpperCase(),n.url,!0),b.timeout=n.timeout;function v(){if(!b)return;let A=US.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),m={data:!c||c==="text"||c==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:A,config:e,request:b};o9t(function(M){r(M),y()},function(M){i(M),y()},m),b=null}"onloadend"in b?b.onloadend=v:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(v)},b.onabort=function(){b&&(i(new ya("Request aborted",ya.ECONNABORTED,e,b)),b=null)},b.onerror=function(g){let m=g&&g.message?g.message:"Network Error",j=new ya(m,ya.ERR_NETWORK,e,b);j.event=g||null,i(j),b=null},b.ontimeout=function(){let g=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",m=n.transitional||wTn;n.timeoutErrorMessage&&(g=n.timeoutErrorMessage),i(new ya(g,m.clarifyTimeoutError?ya.ETIMEDOUT:ya.ECONNABORTED,e,b)),b=null},a===void 0&&o.setContentType(null),"setRequestHeader"in b&&kt.forEach(o.toJSON(),function(g,m){b.setRequestHeader(m,g)}),kt.isUndefined(n.withCredentials)||(b.withCredentials=!!n.withCredentials),c&&c!=="json"&&(b.responseType=n.responseType),s&&([p,h]=xbi(s,!0),b.addEventListener("progress",p)),f&&b.upload&&([l,_]=xbi(f),b.upload.addEventListener("progress",l),b.upload.addEventListener("loadend",_)),(n.cancelToken||n.signal)&&(u=A=>{b&&(i(!A||A.type?new the(null,e,b):A),b.abort(),b=null)},n.cancelToken&&n.cancelToken.subscribe(u),n.signal&&(n.signal.aborted?u():n.signal.addEventListener("abort",u)));let O=AOa(n.url);if(O&&OA.protocols.indexOf(O)===-1){i(new ya("Unsupported protocol "+O+":",ya.ERR_BAD_REQUEST,e));return}b.send(a||null)})};var KPS=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,c();let u=s instanceof Error?s:this.reason;i.abort(u instanceof ya?u:new the(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new ya(`timeout ${t} of ms exceeded`,ya.ETIMEDOUT))},t),c=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:f}=i;return f.unsubscribe=()=>kt.asap(c),f}},fVp=KPS;var JPS=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},$PS=async function*(e,t){for await(let r of YPS(e))yield*JPS(r,t)},YPS=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()}},yHs=(e,t,r,i)=>{let n=$PS(e,t),a=0,o,c=f=>{o||(o=!0,i&&i(f))};return new ReadableStream({async pull(f){try{let{done:s,value:u}=await n.next();if(s){c(),f.close();return}let l=u.byteLength;if(r){let p=a+=l;r(p)}f.enqueue(new Uint8Array(u))}catch(s){throw c(s),s}},cancel(f){return c(f),n.return()}},{highWaterMark:2})};var dVp=64*1024,{isFunction:nPo}=kt,XPS=(({Request:e,Response:t})=>({Request:e,Response:t}))(kt.global),{ReadableStream:pVp,TextEncoder:_Vp}=kt.global,hVp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},ZPS=e=>{e=kt.merge.call({skipUndefined:!0},XPS,e);let{fetch:t,Request:r,Response:i}=e,n=t?nPo(t):typeof fetch=="function",a=nPo(r),o=nPo(i);if(!n)return!1;let c=n&&nPo(pVp),f=n&&(typeof _Vp=="function"?(h=>y=>h.encode(y))(new _Vp):async h=>new Uint8Array(await new r(h).arrayBuffer())),s=a&&c&&hVp(()=>{let h=!1,y=new r(OA.origin,{body:new pVp,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!y}),u=o&&c&&hVp(()=>kt.isReadableStream(new i("").body)),l={stream:u&&(h=>h.body)};n&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!l[h]&&(l[h]=(y,b)=>{let v=y&&y[h];if(v)return v.call(y);throw new ya(`Response type '${h}' is not supported`,ya.ERR_NOT_SUPPORT,b)})});let p=async h=>{if(h==null)return 0;if(kt.isBlob(h))return h.size;if(kt.isSpecCompliantForm(h))return(await new r(OA.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(kt.isArrayBufferView(h)||kt.isArrayBuffer(h))return h.byteLength;if(kt.isURLSearchParams(h)&&(h=h+""),kt.isString(h))return(await f(h)).byteLength},_=async(h,y)=>{let b=kt.toFiniteNumber(h.getContentLength());return b??p(y)};return async h=>{let{url:y,method:b,data:v,signal:O,cancelToken:A,timeout:g,onDownloadProgress:m,onUploadProgress:j,responseType:M,headers:E,withCredentials:D="same-origin",fetchOptions:B}=iPo(h),F=t||fetch;M=M?(M+"").toLowerCase():"text";let N=fVp([O,A&&A.toAbortSignal()],g),T=null,R=N&&N.unsubscribe&&(()=>{N.unsubscribe()}),Q;try{if(j&&s&&b!=="get"&&b!=="head"&&(Q=await _(E,v))!==0){let G=new r(y,{method:"POST",body:v,duplex:"half"}),Pe;if(kt.isFormData(v)&&(Pe=G.headers.get("content-type"))&&E.setContentType(Pe),G.body){let[ne,Ee]=MTn(Q,xbi(DTn(j)));v=yHs(G.body,dVp,ne,Ee)}}kt.isString(D)||(D=D?"include":"omit");let U=a&&"credentials"in r.prototype,H={...B,signal:N,method:b.toUpperCase(),headers:E.normalize().toJSON(),body:v,duplex:"half",credentials:U?D:void 0};T=a&&new r(y,H);let ue=await(a?F(T,B):F(y,H)),se=u&&(M==="stream"||M==="response");if(u&&(m||se&&R)){let G={};["status","statusText","headers"].forEach(Qe=>{G[Qe]=ue[Qe]});let Pe=kt.toFiniteNumber(ue.headers.get("content-length")),[ne,Ee]=m&&MTn(Pe,xbi(DTn(m),!0))||[];ue=new i(yHs(ue.body,dVp,ne,()=>{Ee&&Ee(),R&&R()}),G)}M=M||"text";let x=await l[kt.findKey(l,M)||"text"](ue,h);return!se&&R&&R(),await new Promise((G,Pe)=>{o9t(G,Pe,{data:x,headers:US.from(ue.headers),status:ue.status,statusText:ue.statusText,config:h,request:T})})}catch(U){throw R&&R(),U&&U.name==="TypeError"&&/Load failed|fetch/i.test(U.message)?Object.assign(new ya("Network Error",ya.ERR_NETWORK,h,T),{cause:U.cause||U}):ya.from(U,U&&U.code,h,T)}}},kPS=new Map,bHs=e=>{let t=e?e.env:{},{fetch:r,Request:i,Response:n}=t,a=[i,n,r],o=a.length,c=o,f,s,u=kPS;for(;c--;)f=a[c],s=u.get(f),s===void 0&&u.set(f,s=c?new Map:ZPS(t)),u=s;return s},eg5=bHs();var vHs={http:oVp,xhr:lVp,fetch:{get:bHs}};kt.forEach(vHs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var yVp=e=>`- ${e}`,tjS=e=>kt.isFunction(e)||e===null||e===!1,aPo={getAdapter:(e,t)=>{e=kt.isArray(e)?e:[e];let{length:r}=e,i,n,a={};for(let o=0;o<r;o++){i=e[o];let c;if(n=i,!tjS(i)&&(n=vHs[(c=String(i)).toLowerCase()],n===void 0))throw new ya(`Unknown adapter '${c}'`);if(n&&(kt.isFunction(n)||(n=n.get(t))))break;a[c||"#"+o]=n}if(!n){let o=Object.entries(a).map(([f,s])=>`adapter ${f} `+(s===!1?"is not supported by the environment":"is not available in the build")),c=r?o.length>1?`since :
|
|
@@ -1396,7 +1396,7 @@ ${g}${O}${m}${AQn}`});function $Qo({message:e,error:t,logger:r,logLevel:i=$s.Err
|
|
|
1396
1396
|
Run ${Lt.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
1397
1397
|
Run ${Lt.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),UBi(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function euc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!sd_(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,f)=>c.generatorName.localeCompare(f.generatorName)||c.currentVersion.localeCompare(f.currentVersion));for(let c of o)n+=`
|
|
1398
1398
|
${await QZS(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Lt.dim(c.currentVersion)+Lt.reset(" \u2192 ")+Lt.green(c.latestVersion);return n+=`
|
|
1399
|
-
`,i?UBi(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function QZS(e){let r=await new ud_.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 UZS({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await ld_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=FMi(u.name,l),_=await dNt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:l});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await ld_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,f,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][f]==null&&(o.versions[c][f]={});let l=FMi(s.name,u),p=await dNt({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][f][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function ld_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await $_e({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(!(c==null||c.groups==null)){for(let f of c.groups)if(!(n!=null&&f.groupName!==n))for(let s of f.generators)i!=null&&s.name!==i||await r(a.workspaceName,f.groupName,s,o)}})}))}function fd_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let f=k6(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:f,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function kQo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await UZS({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[f,s]of Object.entries(c.versions))o.push(...fd_(s,f,t.logger));else o.push(...fd_(c.versions,void 0,t.logger))}return o}var zPa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var wQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var tuc=(()=>{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})(),dd_=typeof globalThis.AbortController=="function",pd_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",_d_=typeof globalThis.ReadableStream=="function",hd_=typeof globalThis.FormData=="function",eUo=["get","post","put","patch","head","delete"],LZS=()=>{};LZS();var yd_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},tUo=2147483647,bd_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,rUo=Symbol("stop"),vd_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},gd_={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 VZS=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=bd_,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},Od_=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},Ad_=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(Od_(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},md_=(e,t,r)=>{if(!e.body)return e;let i=VZS(r??e.body);return new Request(e,{duplex:"half",body:Od_(e.body,i,t)})};var EQn=e=>e!==null&&typeof e=="object";var NPa=(...e)=>{for(let t of e)if((!EQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return nuc({},...e)},ruc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function iUo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:nuc(e[r]??[],t[r]??[])}var iuc=(e={},t={})=>({beforeRequest:iUo(e,t,"beforeRequest"),beforeRetry:iUo(e,t,"beforeRetry"),afterResponse:iUo(e,t,"afterResponse"),beforeError:iUo(e,t,"beforeError")}),nuc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(EQn(n)){for(let[a,o]of Object.entries(n))EQn(o)&&a in t&&(o=nuc(t[a],o)),t={...t,[a]:o};EQn(n.hooks)&&(i=iuc(i,n.hooks),t.hooks=i),EQn(n.headers)&&(r=ruc(r,n.headers),t.headers=r)}return t};var jd_=e=>eUo.includes(e)?e.toUpperCase():e,WZS=["get","put","head","delete","options","trace"],xZS=[408,413,429,500,502,503,504],GZS=[413,429,503],Pd_={limit:2,methods:WZS,statusCodes:xZS,afterStatusCodes:GZS,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},wd_=(e={})=>{if(typeof e=="number")return{...Pd_,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{...Pd_,...e}};async function auc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new wQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ouc(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 Ed_=(e,t)=>{let r={};for(let i in t)!(i in gd_)&&!(i in vd_)&&!(i in e)&&(r[i]=t[i]);return r},Sd_=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var FPa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>tUo)throw new RangeError(`The \`timeout\` option cannot be greater than ${tUo}`);await Promise.resolve();let c=await i._fetch();for(let f of i._options.hooks.afterResponse){let s=await f(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let f=new zPa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)f=await s(f);throw f}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!_d_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return Ad_(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,f=[];c&&!c.bodyUsed&&f.push(c.body?.cancel()),i.request.bodyUsed||f.push(i.request.body?.cancel()),await Promise.all(f)});for(let[c,f]of Object.entries(yd_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||f);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:ruc(this._input.headers,r.headers),hooks:iuc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:jd_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:wd_(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(dd_&&pd_){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(tuc&&(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),Sd_(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(hd_&&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(!tuc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=md_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof wQn)throw t;if(t instanceof zPa){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),tUo);if(this._retryCount<1)throw r;await ouc(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})===rUo)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=Ed_(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):auc(this._originalRequest,t,this.abortController,this._options)}};var uuc=e=>{let t=(r,i)=>FPa.create(r,NPa(e,i));for(let r of eUo)t[r]=(i,n)=>FPa.create(i,NPa(e,n,{method:r}));return t.create=r=>uuc(NPa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),uuc(NPa(e,r))),t.stop=rUo,t},HZS=uuc(),Md_=HZS;var Xd_=ae(Yd_(),1);function duc(e){let t=(0,Xd_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Gp_=ae(xp_(),1),Hp_=ae(A_e(),1),wuc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Euc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Suc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??duc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,Gp_.default)(a.toString(),{recursive:!0}),f={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete f.accept,c&&(f.authorization=`${c.type} ${c.token}`);let s;try{s=await Md_(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new wuc(e):l}if(t.allVersions)return s;let u=new Euc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!l){let _=Object.keys(s.versions);if(r=Hp_.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function xPa(e,t){let{version:r}=await Suc(e.toLowerCase(),t);return r}async function qCi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:xPa(e.packageName,{version:t?"prerelease":"latest"})}var Kp_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],hUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=$s.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new ZQo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"2.15.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Lt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new qE}failWithoutThrowing(t,r){this.didSucceed=!1,$Qo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await ATn()).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 cd_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1399
|
+
`,i?UBi(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function QZS(e){let r=await new ud_.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 UZS({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await ld_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=FMi(u.name,l),_=await dNt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:l});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await ld_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,f,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][f]==null&&(o.versions[c][f]={});let l=FMi(s.name,u),p=await dNt({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][f][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function ld_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await $_e({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(!(c==null||c.groups==null)){for(let f of c.groups)if(!(n!=null&&f.groupName!==n))for(let s of f.generators)i!=null&&s.name!==i||await r(a.workspaceName,f.groupName,s,o)}})}))}function fd_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let f=k6(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:f,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function kQo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await UZS({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[f,s]of Object.entries(c.versions))o.push(...fd_(s,f,t.logger));else o.push(...fd_(c.versions,void 0,t.logger))}return o}var zPa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var wQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var tuc=(()=>{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})(),dd_=typeof globalThis.AbortController=="function",pd_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",_d_=typeof globalThis.ReadableStream=="function",hd_=typeof globalThis.FormData=="function",eUo=["get","post","put","patch","head","delete"],LZS=()=>{};LZS();var yd_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},tUo=2147483647,bd_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,rUo=Symbol("stop"),vd_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},gd_={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 VZS=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=bd_,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},Od_=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},Ad_=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(Od_(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},md_=(e,t,r)=>{if(!e.body)return e;let i=VZS(r??e.body);return new Request(e,{duplex:"half",body:Od_(e.body,i,t)})};var EQn=e=>e!==null&&typeof e=="object";var NPa=(...e)=>{for(let t of e)if((!EQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return nuc({},...e)},ruc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function iUo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:nuc(e[r]??[],t[r]??[])}var iuc=(e={},t={})=>({beforeRequest:iUo(e,t,"beforeRequest"),beforeRetry:iUo(e,t,"beforeRetry"),afterResponse:iUo(e,t,"afterResponse"),beforeError:iUo(e,t,"beforeError")}),nuc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(EQn(n)){for(let[a,o]of Object.entries(n))EQn(o)&&a in t&&(o=nuc(t[a],o)),t={...t,[a]:o};EQn(n.hooks)&&(i=iuc(i,n.hooks),t.hooks=i),EQn(n.headers)&&(r=ruc(r,n.headers),t.headers=r)}return t};var jd_=e=>eUo.includes(e)?e.toUpperCase():e,WZS=["get","put","head","delete","options","trace"],xZS=[408,413,429,500,502,503,504],GZS=[413,429,503],Pd_={limit:2,methods:WZS,statusCodes:xZS,afterStatusCodes:GZS,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},wd_=(e={})=>{if(typeof e=="number")return{...Pd_,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{...Pd_,...e}};async function auc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new wQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ouc(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 Ed_=(e,t)=>{let r={};for(let i in t)!(i in gd_)&&!(i in vd_)&&!(i in e)&&(r[i]=t[i]);return r},Sd_=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var FPa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>tUo)throw new RangeError(`The \`timeout\` option cannot be greater than ${tUo}`);await Promise.resolve();let c=await i._fetch();for(let f of i._options.hooks.afterResponse){let s=await f(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let f=new zPa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)f=await s(f);throw f}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!_d_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return Ad_(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,f=[];c&&!c.bodyUsed&&f.push(c.body?.cancel()),i.request.bodyUsed||f.push(i.request.body?.cancel()),await Promise.all(f)});for(let[c,f]of Object.entries(yd_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||f);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:ruc(this._input.headers,r.headers),hooks:iuc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:jd_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:wd_(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(dd_&&pd_){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(tuc&&(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),Sd_(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(hd_&&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(!tuc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=md_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof wQn)throw t;if(t instanceof zPa){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),tUo);if(this._retryCount<1)throw r;await ouc(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})===rUo)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=Ed_(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):auc(this._originalRequest,t,this.abortController,this._options)}};var uuc=e=>{let t=(r,i)=>FPa.create(r,NPa(e,i));for(let r of eUo)t[r]=(i,n)=>FPa.create(i,NPa(e,n,{method:r}));return t.create=r=>uuc(NPa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),uuc(NPa(e,r))),t.stop=rUo,t},HZS=uuc(),Md_=HZS;var Xd_=ae(Yd_(),1);function duc(e){let t=(0,Xd_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Gp_=ae(xp_(),1),Hp_=ae(A_e(),1),wuc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Euc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Suc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??duc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,Gp_.default)(a.toString(),{recursive:!0}),f={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete f.accept,c&&(f.authorization=`${c.type} ${c.token}`);let s;try{s=await Md_(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new wuc(e):l}if(t.allVersions)return s;let u=new Euc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!l){let _=Object.keys(s.versions);if(r=Hp_.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function xPa(e,t){let{version:r}=await Suc(e.toLowerCase(),t);return r}async function qCi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:xPa(e.packageName,{version:t?"prerelease":"latest"})}var Kp_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],hUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=$s.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new ZQo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"2.15.2"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Lt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new qE}failWithoutThrowing(t,r){this.didSucceed=!1,$Qo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await ATn()).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 cd_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1400
1400
|
`)||(r+=`
|
|
1401
1401
|
`),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=Aws(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 BPa(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 qE}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await ATn()).sendEvent(t)}logger=G8t((t,...r)=>this.log(t,...r));stderr=G8t((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=Jp_(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Jp_(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=Kp_[this.numTasks++%Kp_.length],o=Lt.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===gj.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=>sMi.indexOf(n.level)>=sMi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===$s.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 qCi({cliEnvironment:this.environment,includePreReleases:t}),i=k6(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await kQo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await Voc({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Lt.yellow("?"),style:{answer:n=>Lt.cyan(n),message:n=>Lt.bold(n),highlight:n=>Lt.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
|
|
1402
1402
|
Cancelled by user.`),new qE):i}}async getInput(t){return await Foc({message:t.message,default:t.default})}};function Jp_(e){return`[${e}]:`}var _Ft=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};function yUo(e,t,r,i){if(typeof r!="function")throw new Error("method for before hook must be a function");return i||(i={}),Array.isArray(t)?t.reverse().reduce((n,a)=>yUo.bind(null,e,a,n,i),r)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((n,a)=>a.hook.bind(null,n,i),r)():r(i))}function $p_(e,t,r,i){let n=i;e.registry[r]||(e.registry[r]=[]),t==="before"&&(i=(a,o)=>Promise.resolve().then(n.bind(null,o)).then(a.bind(null,o))),t==="after"&&(i=(a,o)=>{let c;return Promise.resolve().then(a.bind(null,o)).then(f=>(c=f,n(c,o))).then(()=>c)}),t==="error"&&(i=(a,o)=>Promise.resolve().then(a.bind(null,o)).catch(c=>n(c,o))),e.registry[r].push({hook:i,orig:n})}function Yp_(e,t,r){if(!e.registry[t])return;let i=e.registry[t].map(n=>n.orig).indexOf(r);i!==-1&&e.registry[t].splice(i,1)}var Xp_=Function.bind,Zp_=Xp_.bind(Xp_);function kp_(e,t,r){let i=Zp_(Yp_,null).apply(null,r?[t,r]:[t]);e.api={remove:i},e.remove=i,["before","error","after","wrap"].forEach(n=>{let a=r?[t,n,r]:[t,n];e[n]=e.api[n]=Zp_($p_,null).apply(null,a)})}function Z2S(){let e=Symbol("Singular"),t={registry:{}},r=yUo.bind(null,t,e);return kp_(r,t,e),r}function k2S(){let e={registry:{}},t=yUo.bind(null,e);return kp_(t,e),t}var e__={Singular:Z2S,Collection:k2S};var ekS="0.0.0-development",tkS=`octokit-endpoint.js/${ekS} ${TR()}`,rkS={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":tkS},mediaType:{format:""}};function ikS(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function nkS(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}function i__(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(i=>{nkS(t[i])?i in e?r[i]=i__(e[i],t[i]):Object.assign(r,{[i]:t[i]}):Object.assign(r,{[i]:t[i]})}),r}function t__(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function Duc(e,t,r){if(typeof t=="string"){let[n,a]=t.split(" ");r=Object.assign(a?{method:n,url:a}:{url:n},r)}else r=Object.assign({},t);r.headers=ikS(r.headers),t__(r),t__(r.headers);let i=i__(e||{},r);return r.url==="/graphql"&&(e&&e.mediaType.previews?.length&&(i.mediaType.previews=e.mediaType.previews.filter(n=>!i.mediaType.previews.includes(n)).concat(i.mediaType.previews)),i.mediaType.previews=(i.mediaType.previews||[]).map(n=>n.replace(/-preview/,""))),i}function akS(e,t){let r=/\?/.test(e)?"&":"?",i=Object.keys(t);return i.length===0?e:e+r+i.map(n=>n==="q"?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${n}=${encodeURIComponent(t[n])}`).join("&")}var okS=/\{[^{}}]+\}/g;function ukS(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function skS(e){let t=e.match(okS);return t?t.map(ukS).reduce((r,i)=>r.concat(i),[]):[]}function r__(e,t){let r={__proto__:null};for(let i of Object.keys(e))t.indexOf(i)===-1&&(r[i]=e[i]);return r}function n__(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(t){return/%[0-9A-Fa-f]/.test(t)||(t=encodeURI(t).replace(/%5B/g,"[").replace(/%5D/g,"]")),t}).join("")}function TQn(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function GPa(e,t,r){return t=e==="+"||e==="#"?n__(t):TQn(t),r?TQn(r)+"="+t:t}function qQn(e){return e!=null}function Muc(e){return e===";"||e==="&"||e==="?"}function ckS(e,t,r,i){var n=e[r],a=[];if(qQn(n)&&n!=="")if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")n=n.toString(),i&&i!=="*"&&(n=n.substring(0,parseInt(i,10))),a.push(GPa(t,n,Muc(t)?r:""));else if(i==="*")Array.isArray(n)?n.filter(qQn).forEach(function(o){a.push(GPa(t,o,Muc(t)?r:""))}):Object.keys(n).forEach(function(o){qQn(n[o])&&a.push(GPa(t,n[o],o))});else{let o=[];Array.isArray(n)?n.filter(qQn).forEach(function(c){o.push(GPa(t,c))}):Object.keys(n).forEach(function(c){qQn(n[c])&&(o.push(TQn(c)),o.push(GPa(t,n[c].toString())))}),Muc(t)?a.push(TQn(r)+"="+o.join(",")):o.length!==0&&a.push(o.join(","))}else t===";"?qQn(n)&&a.push(TQn(r)):n===""&&(t==="&"||t==="?")?a.push(TQn(r)+"="):n===""&&a.push("");return a}function lkS(e){return{expand:fkS.bind(null,e)}}function fkS(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(i,n,a){if(n){let c="",f=[];if(r.indexOf(n.charAt(0))!==-1&&(c=n.charAt(0),n=n.substr(1)),n.split(/,/g).forEach(function(s){var u=/([^:\*]*)(?::(\d+)|(\*))?/.exec(s);f.push(ckS(t,c,u[1],u[2]||u[3]))}),c&&c!=="+"){var o=",";return c==="?"?o="&":c!=="#"&&(o=c),(f.length!==0?c:"")+f.join(o)}else return f.join(",")}else return n__(a)}),e==="/"?e:e.replace(/\/$/,"")}function a__(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),i=Object.assign({},e.headers),n,a=r__(e,["method","baseUrl","url","headers","request","mediaType"]),o=skS(r);r=lkS(r).expand(a),/^http/.test(r)||(r=e.baseUrl+r);let c=Object.keys(e).filter(u=>o.includes(u)).concat("baseUrl"),f=r__(a,c);if(!/application\/octet-stream/i.test(i.accept)&&(e.mediaType.format&&(i.accept=i.accept.split(/,/).map(u=>u.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),r.endsWith("/graphql")&&e.mediaType.previews?.length)){let u=i.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];i.accept=u.concat(e.mediaType.previews).map(l=>{let p=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${l}-preview${p}`}).join(",")}return["GET","HEAD"].includes(t)?r=akS(r,f):"data"in f?n=f.data:Object.keys(f).length&&(n=f),!i["content-type"]&&typeof n<"u"&&(i["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(t)&&typeof n>"u"&&(n=""),Object.assign({method:t,url:r,headers:i},typeof n<"u"?{body:n}:null,e.request?{request:e.request}:null)}function dkS(e,t,r){return a__(Duc(e,t,r))}function o__(e,t){let r=Duc(e,t),i=dkS.bind(null,r);return Object.assign(i,{DEFAULTS:r,defaults:o__.bind(null,r),merge:Duc.bind(null,r),parse:a__})}var u__=o__(null,rkS);var p__=ae(f__(),1);var hFt=class extends Error{name;status;request;response;constructor(t,r,i){super(t),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0),"response"in i&&(this.response=i.response);let n=Object.assign({},i.request);i.request.headers.authorization&&(n.headers=Object.assign({},i.request.headers,{authorization:i.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),n.url=n.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=n}};var pkS="10.0.6",_kS={headers:{"user-agent":`octokit-request.js/${pkS} ${TR()}`}};function hkS(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}async function d__(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");let r=e.request?.log||console,i=e.request?.parseSuccessResponseBody!==!1,n=hkS(e.body)||Array.isArray(e.body)?JSON.stringify(e.body):e.body,a=Object.fromEntries(Object.entries(e.headers).map(([l,p])=>[l,String(p)])),o;try{o=await t(e.url,{method:e.method,body:n,redirect:e.request?.redirect,headers:a,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(l){let p="Unknown Error";if(l instanceof Error){if(l.name==="AbortError")throw l.status=500,l;p=l.message,l.name==="TypeError"&&"cause"in l&&(l.cause instanceof Error?p=l.cause.message:typeof l.cause=="string"&&(p=l.cause))}let _=new hFt(p,500,{request:e});throw _.cause=l,_}let c=o.status,f=o.url,s={};for(let[l,p]of o.headers)s[l]=p;let u={url:f,status:c,headers:s,data:""};if("deprecation"in s){let l=s.link&&s.link.match(/<([^<>]+)>; rel="deprecation"/),p=l&&l.pop();r.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${s.sunset}${p?`. See ${p}`:""}`)}if(c===204||c===205)return u;if(e.method==="HEAD"){if(c<400)return u;throw new hFt(o.statusText,c,{response:u,request:e})}if(c===304)throw u.data=await Buc(o),new hFt("Not modified",c,{response:u,request:e});if(c>=400)throw u.data=await Buc(o),new hFt(bkS(u.data),c,{response:u,request:e});return u.data=i?await Buc(o):o.body,u}async function Buc(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(()=>"");let r=(0,p__.safeParse)(t);if(ykS(r)){let i="";try{return i=await e.text(),JSON.parse(i)}catch{return i}}else return r.type.startsWith("text/")||r.parameters.charset?.toLowerCase()==="utf-8"?e.text().catch(()=>""):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function ykS(e){return e.type==="application/json"||e.type==="application/scim+json"}function bkS(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return"Unknown error";if("message"in e){let t="documentation_url"in e?` - ${e.documentation_url}`:"";return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(r=>JSON.stringify(r)).join(", ")}${t}`:`${e.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}function Iuc(e,t){let r=e.defaults(t);return Object.assign(function(n,a){let o=r.merge(n,a);if(!o.request||!o.request.hook)return d__(r.parse(o));let c=(f,s)=>d__(r.parse(r.merge(f,s)));return Object.assign(c,{endpoint:r,defaults:Iuc.bind(null,r)}),o.request.hook(c,o)},{endpoint:r,defaults:Iuc.bind(null,r)})}var WO=Iuc(u__,_kS);var vkS="0.0.0-development";function gkS(e){return`Request failed due to following response errors:
|
|
@@ -2028,7 +2028,7 @@ generators:
|
|
|
2028
2028
|
`)});return o}}})};function Cj8({endpoint:e,service:t,relativeFilepath:r,definitionFile:i,workspace:n}){let a={},o=(c,f)=>{(a[c]??=[]).push(f)};if(e.request!=null&&typeof e.request!="string"&&e.request.body!=null&&!$P(e.request.body)&&IGo({request:e.request,file:nf({relativeFilepath:r,definitionFile:i,casingsGenerator:oO,rootApiFile:n.definition.rootApiFile.contents}),typeResolver:new _b(n)})&&o(JEa,{type:"referenced-body",propertyName:JEa}),t.headers!=null)for(let[c,f]of Object.entries(t.headers))o(XGt({headerKey:c,header:f}).name,{type:"service-header",headerKey:c,header:f});if(e.request!=null&&typeof e.request!="string"){if(e.request.headers!=null)for(let[c,f]of Object.entries(e.request.headers))o(XGt({headerKey:c,header:f}).name,{type:"endpoint-header",headerKey:c,header:f});if(e.request["query-parameters"]!=null)for(let[c,f]of Object.entries(e.request["query-parameters"]))o(Vgi({queryParameterKey:c,queryParameter:f}).name,{type:"endpoint-query-parameter",queryParameterKey:c,queryParameter:f});if(e.request.body!=null&&$P(e.request.body)){let c=OPe({typeName:void 0,objectDeclaration:{extends:e.request.body.extends,properties:e.request.body.properties??{}},filepathOfDeclaration:r,definitionFile:i,workspace:n,typeResolver:new _b(n),smartCasing:!1});for(let f of c)o(f.name,{type:"inlined-body",property:f})}}return a}function qj8(e){switch(e.type){case"service-header":return`Service header "${e.headerKey}"`;case"endpoint-header":return`Endpoint header "${e.headerKey}"`;case"endpoint-query-parameter":return`Query Parameter "${e.queryParameterKey}"`;case"inlined-body":return`Body property: ${YEa({property:e.property,prefixBreadcrumbs:["<Request Body>"]})}`;case"referenced-body":return`Body property "${e.propertyName}"`;default:vt(e)}}var Cyd=ae(require("path"),1);var qyd={name:"no-duplicate-declarations",create:({workspace:e,logger:t})=>{let r=Tj8(e),i={},n=({declaredName:a,relativeFilepath:o})=>{let c=Cyd.default.dirname(o),f=r[c]?.[a];if(f==null)return t.error(`Could not find declarations for name: ${a}. This is an error in the Fern validator.`),[];let s=i[c]??=new Set;if(!s.has(a))return s.add(a),[];let u=f.indexOf(o);return f.filter((p,_)=>_!==u).map(p=>({severity:"fatal",message:`${a} is already declared in ${p===o?"this file":p}`}))};return{definitionFile:{typeName:(a,{relativeFilepath:o})=>n({declaredName:a,relativeFilepath:o}),errorDeclaration:({errorName:a},{relativeFilepath:o})=>n({declaredName:a,relativeFilepath:o}),httpEndpoint:({endpoint:a},{relativeFilepath:o})=>typeof a.request!="string"&&a.request?.name!=null?n({declaredName:a.request.name,relativeFilepath:o}):[]}}}};function Tj8(e){let t={};return TB(e,(r,i)=>{let n=Cyd.default.dirname(r),a=t[n]??={},o=c=>{(a[c]??=[]).push(r)};S3(i,{typeName:c=>{o(c)},errorDeclaration:({errorName:c})=>{o(c)},httpEndpoint:({endpoint:c})=>{typeof c.request!="string"&&c.request?.name!=null&&o(c.request.name)}})}),t}function deo(e){let t=new Set,r=new Set,i=[];for(let n of e)t.has(n)&&!r.has(n)&&(r.add(n),i.push(n)),t.add(n);return i}var Tyd={name:"no-duplicate-enum-values",create:()=>({definitionFile:{typeDeclaration:({declaration:e})=>aFt(e)?deo(e.enum.map(r=>typeof r=="string"?r:r.value)).map(r=>({severity:"fatal",message:`Duplicated enum value: ${Lt.bold(r)}.`})):[]}})};var Ryd={name:"no-duplicate-example-names",create:()=>({definitionFile:{typeDeclaration:({declaration:e})=>{if(typeof e=="string"||e.examples==null)return[];let t=e.examples.map(r=>r.name).filter(ps);return deo(t).map(r=>({severity:"fatal",message:`Duplicate example name: ${r}`}))},httpEndpoint:({endpoint:e})=>{if(e.examples==null)return[];let t=e.examples.map(r=>r.name).filter(ps);return deo(t).map(r=>({severity:"fatal",message:`Duplicate example name: ${r}`}))}}})};function SLj(e){if(!e.isInlined)return e.name;switch(e.location){case"inlinedRequest":return"<Inlined Request>";default:vt(e.location)}}var zyd={name:"no-duplicate-field-names",create:({workspace:e})=>{let t=new _b(e);return{definitionFile:{typeDeclaration:({typeName:r,declaration:i},{relativeFilepath:n,contents:a})=>{let o=[];return jB(i,{alias:JOe,enum:c=>{let f=MLj(c.enum,s=>M3n(s).name);for(let s of f)o.push({severity:"fatal",message:`Name "${s}" is used by multiple values.`})},object:c=>{let f=SLj(r),s=OPe({typeName:f,objectDeclaration:c,filepathOfDeclaration:n,definitionFile:a,workspace:e,typeResolver:t,smartCasing:!1}),u=bws(s,l=>l.name);for(let[l,p]of Object.entries(u))if(p.length>1){let _=[`Object has multiple properties named "${l}":`,...p.map(h=>` - ${YEa({property:h,prefixBreadcrumbs:[f]})}`)].join(`
|
|
2029
2029
|
`);o.push({severity:"fatal",message:_})}},undiscriminatedUnion:()=>[],discriminatedUnion:c=>{let f=MLj(Object.entries(c.union),([s,u])=>w3n({unionKey:s,rawSingleUnionType:u}).name);for(let s of f)o.push({severity:"fatal",message:`Name ${s} is used by multiple subtypes of this union.`})}}),o}}}}};function MLj(e,t){let r={};for(let i of e){let n=r[t(i)]??0;r[t(i)]=n+1}return Object.entries(r).reduce((i,[n,a])=>(a>1&&i.push(n),i),[])}var Nyd={name:"no-error-status-code-conflict",create:({workspace:e})=>{if(e.definition.rootApiFile.contents["error-discrimination"]?.strategy!=="status-code")return{};let t=Rj8(e);return{definitionFile:{httpEndpoint:({endpoint:r})=>{if(r.errors==null)return[];let i={};for(let a of r.errors){let o=typeof a=="string"?a:a.error,c=t[o];if(c==null)continue;let f=c["status-code"];f in i?i[f]?.push(o):i[f]=[o]}let n=[];for(let[a,o]of Object.entries(i))o.length>1&&n.push({severity:"fatal",message:`Multiple errors have status-code ${a}: ${o.join(", ")}`});return n}}}}};function Rj8(e){let t={};return TB(e,(r,i)=>{S3(i,{typeName:JOe,errorDeclaration:({errorName:n,declaration:a})=>{t[n]=a},httpService:JOe})}),t}var Fyd={name:"no-extensions-with-file-upload",create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>e.request==null?[]:VKi(e.request)?.extends==null?[]:[{severity:"fatal",message:"Request body extensions are not supported for file-upload requests."}]}})};var Qyd={name:"no-get-request-body",create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{let t=e.method;return(t==="GET"||t==="HEAD")&&aac(e)!=null?[{severity:"fatal",message:`Endpoint is a ${t}, so it cannot have a request body.`}]:[]}}})};var Uyd={name:"no-head-response-body",create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{let t=e.method;return t==="HEAD"&&oac(e)!=null?[{severity:"fatal",message:`Endpoint is a ${t}, so it cannot have a response body.`}]:[]}}})};var Lyd={name:"no-missing-auth",create:e=>{let t=e.workspace.definition.rootApiFile.contents.auth!=null;return{definitionFile:{httpService:r=>r.auth&&!t?[{severity:"fatal",message:"Service requires auth, but no auth is defined."}]:[],httpEndpoint:({endpoint:r})=>r.auth!=null&&r.auth&&!t?[{severity:"fatal",message:"Endpoint requires auth, but no auth is defined."}]:[]}}}};var Vyd={name:"no-missing-error-discriminant",create:({workspace:e})=>zj8(e)?{rootApiFile:{errorDiscrimination:t=>t!=null?[]:[{severity:"fatal",message:"error-discrimination is required because this API has declared errors."}]}}:{}};function zj8(e){for(let t of Object.values(Eqi(e.definition)))if(t.contents.errors!=null&&!vws(t.contents.errors))return!0;return!1}var Wyd={name:"no-missing-request-name",create:()=>({definitionFile:{httpEndpoint:({endpoint:e,service:t})=>{if(typeof e.request!="string"&&e.request?.name!=null)return[];if(e.request!=null&&typeof e.request!="string"){if(e.request.body!=null&&$P(e.request.body))return[{severity:"fatal",message:"Request name is required because request body is defined inline"}];if(e.request["query-parameters"]!=null&&WA(e.request["query-parameters"])>0)return[{severity:"fatal",message:"Request name is required because request has query parameters"}];if(WA(e.request.headers)>0)return[{severity:"fatal",message:"Request name is required because request has headers"}]}return WA(t.headers)>0?[{severity:"fatal",message:"Request name is required because service has headers"}]:[]}}})};var xyd={name:"no-object-single-property-key",create:({workspace:e})=>{let t=new _b(e);return{definitionFile:{typeDeclaration:({declaration:r},{relativeFilepath:i,contents:n})=>{let a=[];if(!ACi(r))return a;let o=({discriminantValue:c,singleUnionType:f})=>{let s=typeof f!="string"&&f.key!=null,u=typeof f=="string"?f:f.type;return typeof u!="string"||s?typeof u!="string"&&s?[{severity:"fatal",message:`Union variant ${c} has no type, so "key" cannot be defined`}]:[]:t.resolveType({type:u,file:nf({relativeFilepath:i,definitionFile:n,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents})})==null?[]:[]};for(let[c,f]of Object.entries(r.union))a.push(...o({discriminantValue:c,singleUnionType:f}));return a}}}}};var Gyd={name:"no-response-property",create:({workspace:e})=>{let t=new _b(e);return{definitionFile:{httpEndpoint:({endpoint:r},{relativeFilepath:i,contents:n})=>{let{response:a}=r;if(a==null)return[];let o=typeof a=="string"?a:a.type;if(o==null)return[];if(q0e(o)!=null)return[];if(aPa(o)!=null)return[];let c=typeof a!="string"?a.property:void 0;if(c==null)return[];let f=nf({relativeFilepath:i,definitionFile:n,rootApiFile:e.definition.rootApiFile.contents,casingsGenerator:oO}),s=typeof a!="string"?a.type:a;if(s==null)return[];let u=t.resolveTypeOrThrow({type:s,file:f}),l=DLj(u,c,f,t);return Nj8(l,c)}}}}},R_i;(function(e){e[e.ContainsProperty=0]="ContainsProperty",e[e.DoesNotContainProperty=1]="DoesNotContainProperty",e[e.IsNotObject=2]="IsNotObject"})(R_i||(R_i={}));function Nj8(e,t){switch(e){case R_i.ContainsProperty:return[];case R_i.DoesNotContainProperty:return[{severity:"fatal",message:`Response does not have a property named ${t}.`}];case R_i.IsNotObject:return[{severity:"fatal",message:"Response must be an object in order to return a property as a response."}]}}function DLj(e,t,r,i){switch(e._type){case"container":return e.container._type!=="optional"&&e.container._type!=="nullable"?R_i.IsNotObject:DLj(e.container.itemType,t,r,i);case"named":return ILj(e.declaration)?Fj8(e.declaration,t,r,i)?R_i.ContainsProperty:R_i.DoesNotContainProperty:R_i.IsNotObject;case"primitive":case"unknown":return R_i.IsNotObject;default:vt(e)}}function Fj8(e,t,r,i){return BLj(e,r,i).has(t)}function BLj(e,t,r){let i=[];typeof e.extends=="string"?i=[e.extends]:Array.isArray(e.extends)&&(i=e.extends);let n=new Set;for(let a of i)for(let o of Qj8(a,t,r))n.add(o);for(let a of Object.keys(e.properties??{}))n.add(a);return n}function Qj8(e,t,r){let i=r.resolveNamedTypeOrThrow({referenceToNamedType:e,file:t});return i._type==="named"&&ILj(i.declaration)?BLj(i.declaration,t,r):new Set}function ILj(e){return e.extends!=null||e.properties!=null}var Hyd={name:"no-undefined-error-reference",create:({workspace:e})=>{let t=Uj8(e);function r(n,a){let o=t[a];return o==null?!1:o.has(n)}let i=(n,a,o)=>{let c=Ghe({reference:n,referencedIn:a,imports:bn(o.imports??{},Ze.of)});return c!=null&&r(c.typeName,c.relativeFilepath)?[]:[{severity:"fatal",message:"Error is not defined."}]};return{rootApiFile:{errorReference:(n,{relativeFilepath:a,contents:o})=>i(n,a,o)},definitionFile:{errorReference:(n,{relativeFilepath:a,contents:o})=>i(n,a,o)}}}};function Uj8(e){let t={};return TB(e,(r,i)=>{let n=new Set;t[r]=n,S3(i,{errorDeclaration:({errorName:a})=>{n.add(a)}})}),t}var Kyd={name:"no-undefined-example-reference",create:({workspace:e})=>{let t=new Jhe(new _b(e));return{definitionFile:{exampleTypeReference:(r,{relativeFilepath:i,contents:n})=>t.parseExampleReference(r)==null?[{severity:"fatal",message:`Example ${Lt.bold(r)} is malformed. Examples should be formatted like ${Lt.bold("$YourType.ExampleName")}`}]:t.resolveExample({example:r,file:nf({relativeFilepath:i,definitionFile:n,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents})})!=null?[]:[{severity:"fatal",message:`Example ${Lt.bold(r)} is not defined.`}]}}}};var qLj=ae(Sv(),1),$yd={name:"no-undefined-path-parameters",create:()=>({rootApiFile:{file:e=>e["base-path"]==null?[]:Jyd({path:e["base-path"],pathParameters:e["path-parameters"]??{},pathType:"file"})},definitionFile:{httpService:e=>Jyd({path:e["base-path"],pathParameters:e["path-parameters"]??{},pathType:"service"}),httpEndpoint:({endpoint:e})=>Jyd({path:e["base-path"]!=null?(0,qLj.default)(e["base-path"],e.path):e.path,pathParameters:FFt(e),pathType:"endpoint"})}})};function Jyd({path:e,pathParameters:t,pathType:r}){let i=[],n=new Set;mD(e).parts.forEach(s=>{n.has(s.pathParameter)&&i.push({severity:"fatal",message:`${Kfa(r)} has duplicate path parameter: ${Lt.bold(s.pathParameter)}.`}),n.add(s.pathParameter)});let o=new Set(Object.keys(t));return CLj(n,o).forEach(s=>{i.push({severity:"fatal",message:`${Kfa(r)} has missing path-parameter: ${Lt.bold(s)}.`})}),CLj(o,n).forEach(s=>{i.push({severity:"fatal",message:`Path parameter is unreferenced in ${r}: ${Lt.bold(s)}.`})}),i}function CLj(e,t){return new Set([...e].filter(r=>!t.has(r)))}var Yyd={name:"no-undefined-type-reference",create:({workspace:e})=>{let t=Lj8(e);function r(n){if(n.parsed==null)return!1;let a=t[n.parsed.relativeFilepath];if(a==null)return!1;let o=GS(n.parsed.typeName);return o!=null?o.name?a.has(o.name):!1:a.has(n.parsed.typeName)}function i(n,a){if(a!=null){let o=[...a];for(;o.length>0;){let c=o.pop(),f=c?typeof c=="string"?GS(c):GS(c.key):void 0;if(f!=null)return n.parsed?.typeName&&f.arguments?.includes(n.parsed?.typeName)}}return!1}return{definitionFile:{typeReference:({typeReference:n,location:a,nodePath:o},{relativeFilepath:c,contents:f})=>{let s=q0e(n);if(s!=null){if(a===GF.InlinedRequestProperty)return[];if(a===GF.Response)return s.isOptional?[{severity:"fatal",message:"File response cannot be optional"}]:[]}return nGt(n)!=null?a===GF.RequestReference||a===GF.Response?[]:[{severity:"fatal",message:"The bytes type can only be used as a request"}]:$Fn(n)?a===GF.StreamingResponse?[]:a===GF.Response?[]:[{severity:"fatal",message:"The text type can only be used as a response or response-stream."}]:Vj8({type:n,relativeFilepath:c,imports:bn(f.imports??{},Ze.of)}).reduce((p,_)=>(_.parsed?.typeName!=null&&q0e(_.parsed.typeName)!=null?p.push({severity:"fatal",message:"The file type can only be used as properties in inlined requests."}):_.parsed?.typeName!=null&&$Fn(_.parsed.typeName)?p.push({severity:"fatal",message:"The text type can only be used as a response-stream or response."}):!r(_)&&!i(_,o)&&p.push({severity:"fatal",message:`Type ${Lt.bold(_.parsed?.typeName??_.fullyQualifiedName)} is not defined.`}),p),[])}}}}};function Lj8(e){let t={};return TB(e,(r,i)=>{let n=new Set;t[r]=n,S3(i,{typeDeclaration:({typeName:a})=>{if(!a.isInlined){let o=GS(a.name);o!=null&&o.name&&n.add(o.name),n.add(a.name)}}})}),t}function Vj8({type:e,relativeFilepath:t,imports:r}){return PB({type:e,_default:void 0,validation:void 0,visitor:{primitive:()=>[],unknown:()=>[],map:({keyType:i,valueType:n})=>[...i,...n],list:i=>i,set:i=>i,optional:i=>i,nullable:i=>i,literal:()=>[],named:i=>{let n=Ghe({reference:i,referencedIn:t,imports:r});return[{fullyQualifiedName:i,parsed:n!=null?{typeName:n.typeName,relativeFilepath:n.relativeFilepath}:void 0}]}}})}var Xyd={name:"no-undefined-variable-reference",create:({workspace:e})=>{let t=new QFt,r=(i,n)=>i.startsWith(QFt.VARIABLE_PREFIX)?t.getDeclaration(i,n)?[]:[{severity:"fatal",message:`Variable ${i} is not defined.`}]:[{severity:"fatal",message:`Variable reference must start with ${QFt.VARIABLE_PREFIX}`}];return{rootApiFile:{variableReference:i=>r(i,Lgi({casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents}))},definitionFile:{variableReference:(i,{relativeFilepath:n,contents:a})=>r(i,nf({casingsGenerator:oO,relativeFilepath:n,definitionFile:a,rootApiFile:e.definition.rootApiFile.contents}))}}}};var Zyd={name:"no-unused-generic",create:({workspace:e})=>{let t=new Set;return TB(e,(r,i)=>{S3(i,{typeDeclaration:n=>{jB(n.declaration,{alias:a=>{let o=GS(typeof a=="string"?a:a.type);if(o!=null&&o.name){let[c,f,...s]=o.name.split("."),u=f??c;u&&t.add(u)}},enum:()=>{},object:()=>{},discriminatedUnion:()=>{},undiscriminatedUnion:()=>{}})}})}),{definitionFile:{typeName:r=>{let i=GS(r);return i==null?[]:i.name&&t.has(i.name)?[]:[{severity:"fatal",message:`Generic "${r}" is declared but never used.`}]}}}}};var kyd={name:"only-object-extensions",create:({workspace:e})=>{let t=new _b(e);return{definitionFile:{extension:(r,{relativeFilepath:i,contents:n})=>{let a=t.resolveNamedType({referenceToNamedType:r,file:nf({relativeFilepath:i,definitionFile:n,rootApiFile:e.definition.rootApiFile.contents,casingsGenerator:oO})});return a==null?[]:a._type==="named"&&pb(a.declaration)?[]:[{severity:"fatal",message:`Objects can only extend other objects, and ${r} is not an object.`}]}}}}};var ebd={name:"valid-base-path",create:()=>({rootApiFile:{file:e=>e["base-path"]!=null?TLj(e["base-path"]):[]},definitionFile:{httpService:e=>TLj(e["base-path"])}})};function TLj(e){if(e==="/"||e.length===0)return[];let t=[];return e.startsWith("/")||t.push({severity:"fatal",message:"base-path must be empty or start with a slash."}),t}var tbd={name:"valid-default-environment",create:({workspace:e})=>{let t=e.definition.rootApiFile.contents.environments;return{rootApiFile:{defaultEnvironment:r=>r!=null&&(t==null||!Object.keys(t).includes(r))?[{severity:"fatal",message:`The default-environment ${r} is not listed as an environment`}]:[]}}}};var rbd={name:"valid-endpoint-path",create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.path==="")return[];let t=[];return e.path.startsWith("/")||t.push({severity:"fatal",message:"Path must start with a slash."}),t}}})};function GAs({allDeclarations:e={},examples:t,parameterDisplayName:r,typeResolver:i,exampleResolver:n,workspace:a,getRawType:o,breadcrumbs:c}){let f=[],s=Object.entries(e).reduce((u,[l,p])=>{let _=o(p);if(_!=null){let h=i.resolveType({type:_.rawType,file:_.file});h!=null&&h._type==="container"&&(h.container._type==="optional"||h.container._type==="nullable")||h?._type==="unknown"||u.push(l)}return u},[]);for(let u of s)t?.[u]==null&&f.push({severity:"fatal",message:`Example is missing required ${r} "${u}"`});if(t!=null)for(let[u,l]of Object.entries(t)){let p=e[u];if(p==null)f.push({severity:"fatal",message:`Unexpected ${r} "${u}"`});else{let _=o(p);_!=null&&f.push(...s8.validateTypeReferenceExample({rawTypeReference:_.rawType,example:l,file:_.file,workspace:a,typeResolver:i,exampleResolver:n,breadcrumbs:c,depth:0}).map(h=>({severity:h.severity??"fatal",message:h.message})))}}return f}function RLj({example:e,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let o=[],c=typeof t.request!="string"?t.request?.body:t.request;return c==null?e!=null&&o.push({severity:"fatal",message:"Unexpected request in example."}):$P(c)?o.push(...s8.validateObjectExample({typeName:void 0,typeNameForBreadcrumb:"<Inlined Request>",rawObject:{"extra-properties":c["extra-properties"],extends:c.extends,properties:c.properties??{}},file:n,typeResolver:r,exampleResolver:i,workspace:a,example:e,breadcrumbs:["request"],depth:0}).map(f=>({severity:f.severity??"fatal",message:f.message}))):o.push(...s8.validateTypeReferenceExample({rawTypeReference:typeof c=="string"?c:c.type,example:e,file:n,workspace:a,typeResolver:r,exampleResolver:i,breadcrumbs:["response","body"],depth:0}).map(f=>({severity:f.severity??"fatal",message:f.message}))),o}function NLj({example:e,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,errorResolver:o}){return e==null?zLj({example:{},endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,errorResolver:o}):WKi(t,e,{body:c=>zLj({example:c,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,errorResolver:o}),stream:c=>Wj8({example:c,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}),events:c=>xj8({example:c,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a})})}function zLj({example:e,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,errorResolver:o}){let c=[];if(e.error==null)if(t.response!=null){let f=typeof t.response!="string"?t.response.type:t.response;if(f==null)return c;c.push(...s8.validateTypeReferenceExample({rawTypeReference:f,example:e.body,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:["response","body"],depth:0}).map(s=>({severity:s.severity??"fatal",message:s.message})))}else e.body!=null&&c.push({severity:"fatal",message:`Unexpected response in example. If you're adding an example of an error response, set the "error" property to the error's name`});else{let f=o.getDeclaration(e.error,n);f!=null&&(t.errors!=null&&t.errors.some(u=>(typeof u!="string"?u.error:u)===e.error)||c.push({severity:"fatal",message:`${Lt.bold(e.error)} is not specified as an allowed error for this endpoint. Add ${Lt.bold(e.error)} to the endpoint's "errors" list.`}),f.declaration.type!=null?c.push(...s8.validateTypeReferenceExample({rawTypeReference:f.declaration.type,example:e.body,typeResolver:r,exampleResolver:i,file:f.file,workspace:a,breadcrumbs:["response","body"],depth:0}).map(u=>({severity:u.severity??"fatal",message:u.message}))):e.body!=null&&c.push({severity:"fatal",message:`Unexpected response in example. ${Lt.bold(e.error)} does not have a body.`}))}return c}function Wj8({example:e,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let o=[];if(t["response-stream"]==null)o.push({severity:"fatal",message:"Unexpected streaming response in example. Endpoint's schema is missing `response-stream` key."});else if(typeof t["response-stream"]=="string"||t["response-stream"].format==null||t["response-stream"].format==="json")for(let c of e.stream)o.push(...s8.validateTypeReferenceExample({rawTypeReference:typeof t["response-stream"]!="string"?t["response-stream"].type:t["response-stream"],example:c,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:["response","body"],depth:0}).map(f=>({severity:f.severity??"fatal",message:f.message})));else o.push({severity:"fatal",message:"Endpoint response expects server-sent events (`response-stream.format: sse`), but the provided example is a regular stream. Use the `events` key to provide an list of server-sent event examples."});return o}function xj8({example:e,endpoint:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let o=[];if(t["response-stream"]==null)o.push({severity:"fatal",message:"Unexpected streaming response in example. Endpoint's schema is missing `response-stream` key."});else if(typeof t["response-stream"]!="string"&&t["response-stream"].format==="sse")for(let c of e.stream)o.push(...s8.validateTypeReferenceExample({rawTypeReference:typeof t["response-stream"]!="string"?t["response-stream"].type:t["response-stream"],example:c.data,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:["response","body"],depth:0}).map(f=>({severity:f.severity??"fatal",message:f.message})));else o.push({severity:"fatal",message:"Endpoint response expects a regular stream, but the provided example is a server-sent event. Use the `stream` key to provide a list of stream examples."});return o}var ibd={name:"valid-example-endpoint-call",create:({workspace:e})=>{let t=new _b(e),r=new x$i(e),i=new Jhe(t),n=new QFt;return{definitionFile:{exampleHeaders:({service:a,endpoint:o,examples:c},{relativeFilepath:f,contents:s})=>GAs({allDeclarations:{...e.definition.rootApiFile.contents.headers,...a.headers,...typeof o.request!="string"?o.request?.headers:void 0},examples:c,parameterDisplayName:"header",typeResolver:t,exampleResolver:i,workspace:e,getRawType:u=>({file:nf({relativeFilepath:f,definitionFile:s,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents}),rawType:typeof u=="string"?u:u.type}),breadcrumbs:["headers"]}),examplePathParameters:({service:a,endpoint:o,examples:c},{relativeFilepath:f,contents:s})=>GAs({allDeclarations:Gj8({workspace:e,service:a,endpoint:o}),examples:c,parameterDisplayName:"path parameter",typeResolver:t,exampleResolver:i,workspace:e,getRawType:u=>FGo({parameter:u,variableResolver:n,file:nf({relativeFilepath:f,definitionFile:s,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents})}),breadcrumbs:["path-parameters"]}),exampleQueryParameters:({endpoint:a,examples:o},{relativeFilepath:c,contents:f})=>GAs({allDeclarations:typeof a.request!="string"?a.request?.["query-parameters"]:void 0,examples:o,parameterDisplayName:"query parameter",typeResolver:t,exampleResolver:i,workspace:e,getRawType:s=>({file:nf({relativeFilepath:c,definitionFile:f,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents}),rawType:typeof s=="string"?s:s.type}),breadcrumbs:["query-parameters"]}),exampleRequest:({endpoint:a,example:o},{relativeFilepath:c,contents:f})=>RLj({example:o,endpoint:a,typeResolver:t,exampleResolver:i,file:nf({relativeFilepath:c,definitionFile:f,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents}),workspace:e}),exampleResponse:({endpoint:a,example:o},{relativeFilepath:c,contents:f})=>NLj({example:o,endpoint:a,typeResolver:t,exampleResolver:i,file:nf({relativeFilepath:c,definitionFile:f,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents}),workspace:e,errorResolver:r})}}}};function Gj8({workspace:e,service:t,endpoint:r}){let i=FFt(r);return r["base-path"]!=null?{...i}:{...e.definition.rootApiFile.contents["path-parameters"],...t["path-parameters"],...i}}var nbd={name:"valid-example-error",create:({workspace:e})=>{let t=new _b(e),r=new Jhe(t);return{definitionFile:{exampleError:({errorName:i,declaration:n,example:a},{relativeFilepath:o,contents:c})=>n.type==null?[]:s8.validateTypeReferenceExample({rawTypeReference:n.type,example:a.value,file:nf({relativeFilepath:o,definitionFile:c,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents}),workspace:e,typeResolver:t,exampleResolver:r,breadcrumbs:["response","body"],depth:0}).map(s=>({severity:"fatal",message:s.message}))}}}};var abd={name:"valid-example-type",create:({workspace:e})=>{let t=new _b(e),r=new Jhe(t);return{definitionFile:{exampleType:({typeName:i,typeDeclaration:n,example:a},{relativeFilepath:o,contents:c})=>s8.validateTypeExample({typeName:i,typeDeclaration:n,example:a.value,file:nf({relativeFilepath:o,definitionFile:c,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents}),typeResolver:t,exampleResolver:r,workspace:e,breadcrumbs:[],depth:0}).map(s=>({severity:"fatal",message:s.message}))}}}};function FLj(e){let t=[];return e.enum.forEach(r=>{let i=M3n(r);LAs.test(i.name)||(i.wasExplicitlySet?t.push({severity:"fatal",message:`Enum name ${Lt.bold(i.name)} is not suitable for code generation. It must start with a letter and only contain letters, numbers, and underscores.`}):t.push({severity:"fatal",message:`Enum value ${Lt.bold(i.name)} is not suitable for code generation. Add a "name" property that starts with a letter and contains only letters, numbers, and underscores.`}))}),t}function QLj(e){let t=[],r=j3n(e);return LAs.test(r.name)||(r.wasExplicitlySet?t.push({severity:"fatal",message:`Discriminant name ${Lt.bold(r.name)} is not suitable for code generation. It must start with a letter and only contain letters, numbers, and underscores.`}):t.push({severity:"fatal",message:`Discriminant value ${Lt.bold(r.name)} is not suitable for code generation. Add a "name" property that starts with a letter and contains only letters, numbers, and underscores.`})),t}var obd={name:"valid-field-names",create:()=>({definitionFile:{typeDeclaration:({declaration:e})=>jB(e,{alias:()=>[],enum:FLj,object:()=>[],undiscriminatedUnion:()=>[],discriminatedUnion:QLj})}})};var ubd={name:"valid-generic",create:({workspace:e})=>{let t=Hj8(e),r={object:[],discriminatedUnion:[]};return{definitionFile:{typeDeclaration:({typeName:i,declaration:n,nodePath:a})=>{let o=[];return i.isInlined||GS(i.name)!=null&&(jB(n,{alias:()=>!1,enum:()=>!1,object:()=>!0,discriminatedUnion:()=>!1,undiscriminatedUnion:()=>!1})||o.push({severity:"fatal",message:"Generics are only supported for object declarations"})),jB(n,{alias:c=>{let f=typeof c=="string"?c:c.type,s=GS(f);if(s!=null){let[u,l,...p]=s.name.split("."),_=l??u;_&&_ in t&&t[_]!==s.arguments.length&&o.push({severity:"fatal",message:`Generic ${_} expects ${t[_]} arguments, but received ${s.arguments.length} <${s.arguments.join(",")}>`})}else f in t&&o.push({severity:"fatal",message:`Generic ${f} expects ${t[f]} arguments, but received none`})},enum:c=>{typeof c!="string"&&c.enum.forEach(f=>{let s=typeof f=="string"?f:f.value;C0e(s)&&o.push({severity:"fatal",message:`Cannot reference generic ${s} from enum`})})},object:c=>{Object.entries(c?.properties??{}).forEach(([f,s])=>{if(C0e(typeof s=="string"?s:s.type))if(a)(r.object??=[]).push({key:f,nodePath:a});else{let u=typeof s=="string"?s:JSON.stringify(s);o.push({severity:"fatal",message:`Cannot reference generic ${u} from object property ${f}`})}})},discriminatedUnion:c=>{Object.entries(c.union).forEach(([f,s])=>{let u=typeof s=="string"?s:typeof s.type=="string"?s.type:void 0;if(u&&C0e(u))if(a)(r.discriminatedUnion??=[]).push({key:f,nodePath:a});else{let l=typeof s=="string"?s:JSON.stringify(s);o.push({severity:"fatal",message:`Cannot reference generic ${l} from union property ${f}`})}})},undiscriminatedUnion:c=>{c.union.forEach(f=>{let s=typeof f=="string"?f:f.type;C0e(s)&&o.push({severity:"fatal",message:`Cannot reference generic ${s} from union`})})}}),o},typeReference:({typeReference:i,nodePath:n})=>{let a=[];if(n)for(let o of Object.keys(r))for(let{key:c,nodePath:f}of r[o])f.length>0&&n.join(",").startsWith(f.join(","))&&n.includes(c)&&a.push({severity:"fatal",message:`Cannot reference generic ${i} from ${o.toLowerCase().includes("union")?"union":o}`});return a}}}}};function Hj8(e){let t={};return TB(e,(r,i)=>{S3(i,{typeDeclaration:({typeName:n,declaration:a})=>{if(!n.isInlined){let o=GS(n.name);o!=null&&jB(a,{alias:()=>{},enum:()=>{},object:()=>{o.name&&o.arguments&&(t[o.name]=o.arguments.length)},discriminatedUnion:()=>{},undiscriminatedUnion:()=>{}})}}})}),t}var ULj=ae(require("path"),1),sbd={name:"valid-navigation",create:({workspace:e})=>{let t=XRt(_gi(e.definition)),i=XRt(Eqi(e.definition)).reduce((n,a)=>((n[hn(a)]??=new Set).add(ULj.default.basename(a)),n),{});return{packageMarker:{navigation:(n,{relativeFilepath:a})=>{if(n==null)return[];if(typeof n=="string"){let s=Ev(e.definition.absoluteFilePath,Ft(e.definition.absoluteFilePath,hn(a),Ze.of(n)));return t.some(u=>u.startsWith(s))?[]:[{severity:"fatal",message:`${n} does not exist.`}]}let o=i[hn(a)];if(o==null)throw new Error(`Could not find expected contents of ${a}`);let c=[],f=new Set;for(let s of n)s===ob?c.push({severity:"fatal",message:`${ob} cannot be specified in navigation.`}):o.has(s)?f.has(s)&&c.push({severity:"fatal",message:`${s} is specified more than once.`}):c.push({severity:"fatal",message:`Unexpected item: ${s}`}),f.add(s);for(let s of o)f.has(s)||c.push({severity:"fatal",message:`Missing ${s}`});return c}}}}};var peo="$request.",cbd="$response.";function _la({typeResolver:e,file:t,endpoint:r,propertyComponents:i,validate:n}){if(r.request==null)return!1;if(typeof r.request=="string"){let a=e.resolveType({type:r.request,file:t});return n8t({typeResolver:e,file:Zq(a)??t,resolvedType:a,propertyComponents:i,validate:n})}return Kj8({typeResolver:e,file:t,requestType:r.request,propertyComponents:i,validate:n})}function Kj8({typeResolver:e,file:t,requestType:r,propertyComponents:i,validate:n}){if(Jj8({typeResolver:e,file:t,requestType:r,propertyComponents:i,validate:n}))return!0;if(r.body==null)return!1;if(typeof r.body=="string"){let o=e.resolveType({type:r.body,file:t});return n8t({typeResolver:e,file:Zq(o)??t,resolvedType:o,propertyComponents:i,validate:n})}if($P(r.body))return LLj({typeResolver:e,file:t,objectSchema:r.body,propertyComponents:i,validate:n});let a=e.resolveType({type:r.body.type,file:t});return n8t({typeResolver:e,file:Zq(a)??t,resolvedType:e.resolveType({type:r.body.type,file:t}),propertyComponents:i,validate:n})}function Jj8({typeResolver:e,file:t,requestType:r,propertyComponents:i,validate:n}){if(i.length!==1||typeof r=="string"||r["query-parameters"]==null)return!1;let a=r["query-parameters"][i[0]??""];if(a==null)return!1;let o=e.resolveType({type:typeof a!="string"?a.type:a,file:t});return n({resolvedType:o})}function n8t({typeResolver:e,file:t,resolvedType:r,propertyComponents:i,validate:n}){if(i.length===0)return n({resolvedType:r});let a=WLj(r);return a==null?!1:LLj({typeResolver:e,file:t,objectSchema:a,propertyComponents:i,validate:n})}function z_i({endpoint:e,typeResolver:t,file:r}){let i=typeof e.response!="string"?e.response?.type:e.response;if(i!=null)return t.resolveType({type:i,file:r})}function a8t(e){if(e?._type==="primitive")return e.primitive.v1;if(e?._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return a8t(e.container.itemType)}function Zq(e){if(e!=null){if(e._type==="named")return e.file;if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return Zq(e.container.itemType)}}function hla(e){return xLj(e,peo)?.split(".")}function HAs(e){return xLj(e,cbd)?.split(".")}function LLj({typeResolver:e,file:t,objectSchema:r,propertyComponents:i,validate:n}){let a=$j8({typeResolver:e,file:t,objectSchema:r,property:i[0]??""});if(a==null)return!1;let o=e.resolveType({type:a,file:t});return n8t({typeResolver:e,file:Zq(o)??t,resolvedType:o,propertyComponents:i.slice(1),validate:n})}function $j8({typeResolver:e,file:t,objectSchema:r,property:i}){return VLj({typeResolver:e,file:t,objectSchema:r})[i]}function VLj({typeResolver:e,file:t,objectSchema:r}){let i=[];typeof r.extends=="string"?i=[r.extends]:Array.isArray(r.extends)&&(i=r.extends);let n={};for(let a of i){let o=Yj8({typeResolver:e,file:t,extendedType:a});Object.entries(o).map(([c,f])=>{n[c]=f})}return r.properties!=null&&Object.entries(r.properties).map(([a,o])=>{n[a]=typeof o=="string"?o:o.type}),n}function Yj8({typeResolver:e,file:t,extendedType:r}){let i=e.resolveNamedTypeOrThrow({referenceToNamedType:r,file:t});return i._type==="named"&&pb(i.declaration)?VLj({typeResolver:e,file:Zq(i)??t,objectSchema:i.declaration}):{}}function WLj(e){if(e!=null){if(e._type==="named"&&pb(e.declaration))return e.declaration;if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return WLj(e.container.itemType)}}function xLj(e,t){return e.startsWith(t)?e.substring(t.length):null}var lbd=`${peo}client_id`,fbd=`${peo}client_secret`,yla=`${cbd}access_token`,dbd=`${peo}refresh_token`;function pbd({endpointId:e,endpoint:t,typeResolver:r,file:i,clientIdProperty:n}){return $As({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:{propertyID:"client-id",validate:_eo}})}function _bd({endpointId:e,endpoint:t,typeResolver:r,file:i,clientSecretProperty:n}){return $As({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:{propertyID:"client-secret",validate:_eo}})}function GLj({endpointId:e,endpoint:t,typeResolver:r,file:i,scopesProperty:n}){return $As({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:{propertyID:"scopes",validate:_eo}})}function hbd({endpointId:e,endpoint:t,typeResolver:r,file:i,refreshTokenProperty:n}){return $As({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:{propertyID:"refresh-token",validate:_eo}})}function bla({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,accessTokenProperty:n}){return ybd({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:{propertyID:"access-token",validate:HLj}})}function KAs({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,refreshTokenProperty:n}){return ybd({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:{propertyID:"refresh-token",validate:HLj}})}function JAs({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,expiresInProperty:n}){return ybd({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:{propertyID:"expires-in",validate:Xj8}})}function Xj8({typeResolver:e,file:t,resolvedType:r,propertyComponents:i}){return n8t({typeResolver:e,file:t,resolvedType:r,propertyComponents:i,validate:Zj8})}function HLj({typeResolver:e,file:t,resolvedType:r,propertyComponents:i}){return n8t({typeResolver:e,file:t,resolvedType:r,propertyComponents:i,validate:_eo})}function $As({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:a}){let o=[],c=hla(n);return c==null?(o.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} must define a dot-delimited '${a.propertyID}' property starting with $request (e.g. $request.${a.propertyID}).`}),o):c.length>1?(o.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} cannot reference nested $request properties like '${n}'; expected '$request.${a.propertyID}' instead.`}),o):(_la({typeResolver:r,file:i,endpoint:t,propertyComponents:c,validate:a.validate})||o.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} specifies '${a.propertyID}' ${n}, which is not a valid '${a.propertyID}' type.`}),o)}function ybd({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:a}){let o=[],c=HAs(n);return c==null&&o.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} must define a dot-delimited '${a.propertyID}' property starting with $response (e.g. $response.${a.propertyID}).`}),c!=null&&!a.validate({typeResolver:t,file:r,resolvedType:i,propertyComponents:c})&&o.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} specifies '${a.propertyID}' ${n}, which is not a valid '${a.propertyID}' type.`}),o}function Zj8({resolvedType:e}){return a8t(e)==="INTEGER"}function _eo({resolvedType:e}){return a8t(e)==="STRING"}function KLj({endpointId:e,endpoint:t,typeResolver:r,file:i,refreshEndpoint:n}){let a=[],o=n["request-properties"]?.["refresh-token"];o!=null?a.push(...hbd({endpointId:e,endpoint:t,typeResolver:r,file:i,refreshTokenProperty:o})):hbd({endpointId:e,endpoint:t,typeResolver:r,file:i,refreshTokenProperty:dbd}).length>0&&a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} is missing a valid refresh-token, such as '${dbd}'.`});let c=z_i({endpoint:t,typeResolver:r,file:i});if(c==null)return a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} must define a response type.`}),a;let f=n["response-properties"]?.["access-token"];f!=null?a.push(...bla({endpointId:e,typeResolver:r,file:i,resolvedResponseType:c,accessTokenProperty:f})):bla({endpointId:e,typeResolver:r,file:i,resolvedResponseType:c,accessTokenProperty:yla}).length>0&&a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} is missing a valid access-token, such as '${yla}'.`});let s=n?.["response-properties"]?.["expires-in"];s!=null&&a.push(...JAs({endpointId:e,typeResolver:r,file:Zq(c)??i,resolvedResponseType:c,expiresInProperty:s}));let u=n?.["response-properties"]?.["refresh-token"];return u!=null&&a.push(...KAs({endpointId:e,typeResolver:r,file:Zq(c)??i,resolvedResponseType:c,refreshTokenProperty:u})),a}function JLj({endpointId:e,endpoint:t,typeResolver:r,file:i,tokenEndpoint:n}){let a=[],o=n["request-properties"]?.["client-id"];o!=null?a.push(...pbd({endpointId:e,endpoint:t,typeResolver:r,file:i,clientIdProperty:o})):pbd({endpointId:e,endpoint:t,typeResolver:r,file:i,clientIdProperty:lbd}).length>0&&a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} is missing a valid client-id, such as '${lbd}'.`});let c=n["request-properties"]?.["client-secret"];c!=null?a.push(..._bd({endpointId:e,endpoint:t,typeResolver:r,file:i,clientSecretProperty:c})):_bd({endpointId:e,endpoint:t,typeResolver:r,file:i,clientSecretProperty:fbd}).length>0&&a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} is missing a valid client-secret, such as '${fbd}'.`});let f=n?.["request-properties"]?.scopes;f!=null&&a.push(...GLj({endpointId:e,endpoint:t,typeResolver:r,file:i,scopesProperty:f}));let s=z_i({endpoint:t,typeResolver:r,file:i});if(s==null)return a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} must define a response type.`}),a;let u=n["response-properties"]?.["access-token"];u!=null?a.push(...bla({endpointId:e,typeResolver:r,file:i,resolvedResponseType:s,accessTokenProperty:u})):bla({endpointId:e,typeResolver:r,file:i,resolvedResponseType:s,accessTokenProperty:yla}).length>0&&a.push({severity:"fatal",message:`OAuth configuration for endpoint ${Lt.bold(e)} is missing a valid access-token, such as '${yla}'.`});let l=n?.["response-properties"]?.["expires-in"];l!=null&&a.push(...JAs({endpointId:e,typeResolver:r,file:Zq(s)??i,resolvedResponseType:s,expiresInProperty:l}));let p=n?.["response-properties"]?.["refresh-token"];return p!=null&&a.push(...KAs({endpointId:e,typeResolver:r,file:Zq(s)??i,resolvedResponseType:s,refreshTokenProperty:p})),a}var bbd={name:"valid-oauth",create:({workspace:e})=>{let t=new _b(e),r=new W$i(e),i=Lgi({casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents});return{rootApiFile:{oauth:({name:n,oauth:a},{relativeFilepath:o})=>{let c=[],f=a["get-token"].endpoint,s=r.resolveEndpoint({endpoint:f,file:i});s==null?c.push({severity:"fatal",message:`Failed to resolve endpoint ${f}`}):c.push(...JLj({endpointId:s.endpointId,endpoint:s.endpoint,typeResolver:t,file:s.file,tokenEndpoint:a["get-token"]}));let u=a["refresh-token"]?.endpoint;if(a["refresh-token"]!=null&&u!=null){let l=r.resolveEndpoint({endpoint:u,file:i});l==null?c.push({severity:"fatal",message:`Failed to resolve endpoint ${f}`}):c.push(...KLj({endpointId:l.endpointId,endpoint:l.endpoint,typeResolver:t,file:l.file,refreshEndpoint:a["refresh-token"]}))}return c}}}}};function vla({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,resultsProperty:n}){return vbd({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:{propertyID:"results",validate:kj8}})}function heo({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n,propertyValidator:a}){let o=[],c=hla(n);return c==null?(o.push({severity:"fatal",message:`Pagination configuration for endpoint ${Lt.bold(e)} must define a dot-delimited '${a.propertyID}' property starting with $request (e.g. $request.${a.propertyID}).`}),o):(_la({typeResolver:r,file:i,endpoint:t,propertyComponents:c,validate:a.validate})||o.push({severity:"fatal",message:`Pagination configuration for endpoint ${Lt.bold(e)} specifies '${a.propertyID}' ${n}, which is not a valid '${a.propertyID}' type.`}),o)}function vbd({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:a}){let o=[],c=HAs(n);return c==null&&o.push({severity:"fatal",message:`Pagination configuration for endpoint ${Lt.bold(e)} must define a dot-delimited '${a.propertyID}' property starting with $response (e.g. $response.${a.propertyID}).`}),c!=null&&!a.validate({typeResolver:t,file:r,resolvedType:i,propertyComponents:c})&&o.push({severity:"fatal",message:`Pagination configuration for endpoint ${Lt.bold(e)} specifies '${a.propertyID}' ${n}, which is not a valid '${a.propertyID}' type.`}),o}function kj8({typeResolver:e,file:t,resolvedType:r,propertyComponents:i}){return n8t({typeResolver:e,file:t,resolvedType:r,propertyComponents:i,validate:ew8})}function ew8({resolvedType:e}){return!0}function $Lj({endpointId:e,endpoint:t,typeResolver:r,file:i,cursorPagination:n}){let a=[];a.push(...tw8({endpointId:e,endpoint:t,typeResolver:r,file:i,cursorPagination:n}));let o=z_i({endpoint:t,typeResolver:r,file:i});return o==null?(a.push({severity:"fatal",message:`Pagination configuration for endpoint ${Lt.bold(e)} must define a response type.`}),a):(a.push(...rw8({endpointId:e,typeResolver:r,file:Zq(o)??i,resolvedResponseType:o,nextProperty:n.next_cursor})),a.push(...vla({endpointId:e,typeResolver:r,file:Zq(o)??i,resolvedResponseType:o,resultsProperty:n.results})),a)}function tw8({endpointId:e,endpoint:t,typeResolver:r,file:i,cursorPagination:n}){return heo({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n.cursor,propertyValidator:{propertyID:"cursor",validate:YLj}})}function rw8({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,nextProperty:n}){return vbd({endpointId:e,typeResolver:t,file:r,resolvedResponseType:i,responseProperty:n,propertyValidator:{propertyID:"next_cursor",validate:iw8}})}function iw8({typeResolver:e,file:t,resolvedType:r,propertyComponents:i}){return n8t({typeResolver:e,file:t,resolvedType:r,propertyComponents:i,validate:YLj})}function YLj({resolvedType:e}){let t=a8t(e);return t==null?!1:t!=="BOOLEAN"}function XLj({endpointId:e,endpoint:t,typeResolver:r,file:i,customPagination:n}){let a=[],o=z_i({endpoint:t,typeResolver:r,file:i});return o==null?(a.push({severity:"fatal",message:`Pagination configuration for endpoint ${Lt.bold(e)} must define a response type.`}),a):(a.push(...vla({endpointId:e,typeResolver:r,file:Zq(o)??i,resolvedResponseType:o,resultsProperty:n.results})),a)}function ZLj(e){return e.split(".").slice(1)}function kLj({path:e,typeResolver:t,file:r,resolvedType:i,validate:n}){let a=i;for(let o of e){if(a==null)return n({resolvedType:void 0});let c=r8j(a);if(c==null)return n({resolvedType:void 0});let s=e8j({typeResolver:t,file:r,objectSchema:c})[o];if(s==null)return n({resolvedType:void 0});a=t.resolveType({type:s,file:r})}return n({resolvedType:a})}function e8j({typeResolver:e,file:t,objectSchema:r}){let i=[];typeof r.extends=="string"?i=[r.extends]:Array.isArray(r.extends)&&(i=r.extends);let n={};for(let a of i){let o=nw8({typeResolver:e,file:t,extendedType:a});Object.entries(o).map(([c,f])=>{n[c]=f})}return r.properties!=null&&Object.entries(r.properties).map(([a,o])=>{n[a]=typeof o=="string"?o:o.type}),n}function nw8({typeResolver:e,file:t,extendedType:r}){let i=e.resolveNamedTypeOrThrow({referenceToNamedType:r,file:t});return i._type==="named"&&pb(i.declaration)?e8j({typeResolver:e,file:t8j(i)??t,objectSchema:i.declaration}):{}}function t8j(e){if(e!=null){if(e._type==="named")return e.file;if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return t8j(e.container.itemType)}}function r8j(e){if(e!=null){if(e._type==="named"&&pb(e.declaration))return e.declaration;if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return r8j(e.container.itemType)}}function i8j({endpointId:e,endpoint:t,typeResolver:r,file:i,offsetPagination:n}){let a=[];a.push(...aw8({endpointId:e,endpoint:t,typeResolver:r,file:i,offsetPagination:n})),a.push(...ow8({endpointId:e,endpoint:t,typeResolver:r,file:i,offsetPagination:n}));let o=z_i({endpoint:t,typeResolver:r,file:i});return o==null?(a.push({severity:"fatal",message:`Pagination configuration for endpoint ${Lt.bold(e)} must define a response type.`}),a):(a.push(...vla({endpointId:e,typeResolver:r,file:Zq(o)??i,resolvedResponseType:o,resultsProperty:n.results})),a.push(...uw8({endpointId:e,resolvedResponseType:o,typeResolver:r,file:Zq(o)??i,offsetPagination:n})),a)}function aw8({endpointId:e,endpoint:t,typeResolver:r,file:i,offsetPagination:n}){return heo({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n.offset,propertyValidator:{propertyID:"offset",validate:n8j}})}function ow8({endpointId:e,endpoint:t,typeResolver:r,file:i,offsetPagination:n}){return n.step==null?[]:heo({endpointId:e,endpoint:t,typeResolver:r,file:i,requestProperty:n.step,propertyValidator:{propertyID:"step",validate:n8j}})}function n8j({resolvedType:e}){let t=a8t(e);return t==null?!1:t==="INTEGER"||t==="LONG"||t==="DOUBLE"}function uw8({resolvedResponseType:e,typeResolver:t,file:r,offsetPagination:i}){return i["has-next-page"]==null?[]:kLj({typeResolver:t,file:r,path:ZLj(i["has-next-page"]),resolvedType:e,validate:({resolvedType:n})=>a8t(n)!=="BOOLEAN"?[{message:`"has-next-page" selector, ${i["has-next-page"]}, does not point to a boolean property`,severity:"fatal"}]:[]})}var gbd={name:"valid-pagination",create:({workspace:e})=>{let t=new _b(e),r=e.definition.rootApiFile.contents.pagination;return{definitionFile:{httpEndpoint:({endpointId:i,endpoint:n},{relativeFilepath:a,contents:o})=>{let c=typeof n.pagination=="boolean"?r:n.pagination;if(!c)return[];let f=nf({relativeFilepath:a,definitionFile:o,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents});if(cw8(c))return $Lj({endpointId:i,endpoint:n,typeResolver:t,file:f,cursorPagination:c});if(sw8(c))return i8j({endpointId:i,endpoint:n,typeResolver:t,file:f,offsetPagination:c});if(lw8(c))return XLj({endpointId:i,endpoint:n,typeResolver:t,file:f,customPagination:c});throw new Error("Invalid pagination schema")}}}}};function sw8(e){return e.offset!=null}function cw8(e){return e.cursor!=null&&e.next_cursor!=null&&e.results!=null}function lw8(e){return"type"in e&&e.type==="custom"}var Obd={name:"valid-path-parameters-configuration",create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>e["path-parameters"]!=null&&typeof e.request!="string"&&e?.request?.["path-parameters"]!=null?[{severity:"fatal",message:"path-parameters cannot be defined in both endpoint and request."}]:[]}})};var Abd={name:"valid-service-urls",create:({workspace:e})=>{let t=VAs(e),r=i=>t.includes(i)?[]:t.length===0&&e.definition.rootApiFile.contents?.["default-url"]!=null?[]:t.length===0?[{severity:"fatal",message:`"url" cannot be configured unless you specify multiple URLs for each environment in ${n1}`}]:[{severity:"fatal",message:[`URL ${Lt.bold(i)} is not recognized. Please add it to your environments in ${n1} or specify one of the configured environment URLs:`,...t.map(n=>` - ${n}`)].join(`
|
|
2030
2030
|
`)}];return{definitionFile:{serviceBaseUrl:i=>i==null?[]:r(i),endpointBaseUrl:({baseUrl:i,service:n})=>e.definition.rootApiFile.contents?.["default-url"]?[]:i==null?t.length===0||n.url!=null?[]:[{severity:"fatal",message:['"url" is missing. Please specify one of the configured environment URLs:',...t.map(a=>` - ${a}`)].join(`
|
|
2031
|
-
`)}]:r(i)}}}};var mbd={name:"valid-stream-condition",create:({workspace:e})=>({definitionFile:{streamCondition:({endpoint:t,streamCondition:r},{relativeFilepath:i,contents:n})=>{let a=new _b(e),o=nf({relativeFilepath:i,definitionFile:n,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents});return t.response==null||t["response-stream"]==null?r==null?[]:[{severity:"fatal",message:"stream-condition can only be used if both response and response-stream are specified."}]:r==null?[{severity:"fatal",message:"stream-condition must be specified when both response and response-stream are specified."}]:dw8({endpoint:t,typeResolver:a,file:o,requestProperty:r,propertyValidator:{propertyID:"stream-condition",validate:fw8}})}}})};function fw8({resolvedType:e}){let t=a8t(e);return t==null?!1:t==="BOOLEAN"}function dw8({endpoint:e,typeResolver:t,file:r,requestProperty:i,propertyValidator:n}){let a=[],o=hla(i);return o==null?[{severity:"fatal",message:"Please specify path to a valid property (e.g. $request.stream)"}]:_la({typeResolver:t,file:r,endpoint:e,propertyComponents:o,validate:n.validate})?a:[{severity:"fatal",message:`Property "${i}" does not exist on the request.`}]}var pw8=/^[a-z]/i,Pbd={name:"valid-type-name",create:()=>({definitionFile:{typeDeclaration:({typeName:e})=>!e.isInlined&&!pw8.test(e.name)?[{severity:"fatal",message:"Type name must begin with a letter"}]:[]}})};var wbd={name:"valid-type-reference-with-default-and-validation",create:({workspace:e})=>{let t=new _b(e);return{definitionFile:{typeDeclaration:({declaration:r})=>{if(!aFt(r))return[];let i=new Set(r.enum.map(n=>typeof n=="string"?n:n.value));return r.default!=null&&!i.has(r.default)?[{message:`Default value '${r.default}' is not a valid enum value`,severity:"fatal"}]:[]},typeReference:({typeReference:r,_default:i,validation:n,location:a},{relativeFilepath:o,contents:c})=>{let f=nf({relativeFilepath:o,definitionFile:c,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents}),s=t.resolveType({type:r,file:f});return s==null?[]:a8j({resolvedType:s,_default:i,validation:n})}}}}};function a8j({resolvedType:e,_default:t,validation:r}){let i=[];if(t==null&&r==null)return[];if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return a8j({resolvedType:e.container.itemType,_default:t,validation:r});let n=e._type;if(e._type==="primitive")switch(e.primitive.v1){case"STRING":return hw8({_default:t,validation:r});case"DOUBLE":return yw8({_default:t,validation:r});case"INTEGER":return bw8({_default:t,validation:r});case"BOOLEAN":return vw8({_default:t,validation:r});case"LONG":return gw8({_default:t,validation:r});case"BIG_INTEGER":return Ow8({_default:t,validation:r});case"DATE_TIME":n="datetime";break;case"UUID":n="uuid";break;case"BASE_64":n="base64";break;case"UINT":n="uint";break;case"UINT_64":n="uint64";break}return e._type==="named"&&aFt(e.declaration)?_w8({declaration:e.declaration,_default:t}):(t!=null&&i.push({message:`Default values are not supported for the ${n} type`,severity:"fatal"}),r!=null&&i.push({message:`Validation rules are not supported for the ${n} type`,severity:"fatal"}),i)}function _w8({declaration:e,_default:t}){if(t==null)return[];let r=new Set(e.enum.map(n=>typeof n=="string"?n:n.value)),i=[];return r.has(t)||i.push({message:`Default value '${t}' is not a valid enum value`,severity:"fatal"}),i}function hw8({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="string"&&r.push({message:`Default value '${e}' is not a valid string`,severity:"fatal"}),t!=null&&!Aw8(t)&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the string type`,severity:"fatal"}),r}function yw8({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="number"&&r.push({message:`Default value '${e}' is not a valid double`,severity:"fatal"}),t!=null&&!o8j(t)&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the double type`,severity:"fatal"}),r}function bw8({_default:e,validation:t}){let r=[];return e!=null&&!Number.isInteger(e)&&r.push({message:`Default value '${e}' is not a valid integer`,severity:"fatal"}),t!=null&&(o8j(t)?r.push(...jbd({name:"min",value:t.min}),...jbd({name:"max",value:t.max}),...jbd({name:"multipleOf",value:t.multipleOf})):r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the integer type`,severity:"fatal"})),r}function vw8({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="boolean"&&r.push({message:`Default value '${e}' is not a valid boolean`,severity:"fatal"}),t!=null&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the boolean type`,severity:"fatal"}),r}function gw8({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="number"&&r.push({message:`Default value '${e}' is not a valid long`,severity:"fatal"}),t!=null&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the long type`,severity:"fatal"}),r}function Ow8({_default:e,validation:t}){let r=[];if(e!=null)if(typeof e!="string")r.push({message:`Default value '${e}' is not a valid bigint`,severity:"fatal"});else try{BigInt(e)}catch{r.push({message:`Default value '${e}' is not a valid bigint`,severity:"fatal"})}return t!=null&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the bigint type`,severity:"fatal"}),r}function jbd({name:e,value:t}){return t!=null&&!Number.isInteger(t)?[{message:`Validation for '${e}' must be an integer, but found '${t}'`,severity:"fatal"}]:[]}function o8j(e){let t=e;return t.min!=null||t.max!=null||t.exclusiveMin!=null||t.exclusiveMax!=null||t.multipleOf!=null}function Aw8(e){let t=e;return t.minLength!=null||t.maxLength!=null||t.pattern!=null||t.format!=null}var Ebd={name:"valid-version",create:({workspace:e})=>{let t=new _b(e);return{rootApiFile:{file:r=>mw8({root:r,typeResolver:t})}}}};function mw8({root:e,typeResolver:t}){let r=[];return e.version==null||e.version.default==null?[]:(new Set(e.version.values.map(n=>typeof n=="string"?n:n.value)).has(e.version.default)||r.push({severity:"fatal",message:`Default version "${e.version.default}" not found in version values`}),r)}function Pw8(){return[Yyd,Tyd,$yd,jyd,qyd,Hyd,Eyd,obd,zyd,xyd,Qyd,Uyd,Syd,tbd,Vyd,abd,Nyd,Lyd,Wyd,Myd,Iyd,ibd,Ryd,Kyd,wyd,Abd,ebd,rbd,Byd,Pbd,Fyd,sbd,Xyd,kyd,Gyd,bbd,gbd,nbd,wbd,mbd,Ebd,Zyd,ubd,myd,Obd,Pyd]}function u8j(){return Pw8().filter(({DISABLE_RULE:e=!1})=>!e)}function Sbd(e,t){return jw8({workspace:e,rules:u8j(),logger:t})}function jw8({workspace:e,rules:t,logger:r}){let i=[],n=t.map(o=>o.create({workspace:e,logger:r})),a=Ew8({contents:e.definition.rootApiFile.contents,allRuleVisitors:n});return i.push(...a),TB(e,(o,c)=>{let f=ww8({relativeFilepath:o,contents:c,allRuleVisitors:n});i.push(...f)}),p$i(e,(o,c)=>{let f=Sw8({relativeFilepath:o,contents:c,allRuleVisitors:n});i.push(...f)}),i}function ww8({relativeFilepath:e,contents:t,allRuleVisitors:r}){let i=[],n=mLj({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:a=>{i.push(...a)}});return S3(t,n),i}function Ew8({contents:e,allRuleVisitors:t}){let r=[],i=jLj({relativeFilepath:Ze.of(n1),contents:e,allRuleVisitors:t,addViolations:n=>{r.push(...n)}});return Ayd(e,i),r}function Sw8({relativeFilepath:e,contents:t,allRuleVisitors:r}){let i=[],n=PLj({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:a=>{i.push(...a)}});return Oyd(t,n),i}async function s8j({groups:e,visitor:t,nodePath:r,cliVersion:i}){if(e!=null)for(let[n,a]of Object.entries(e))await Mw8({group:a,visitor:t,nodePath:[...r,n],cliVersion:i})}async function Mw8({group:e,visitor:t,nodePath:r,cliVersion:i}){await Promise.all(e.generators.map(async(n,a)=>await t.generatorInvocation?.({invocation:n,cliVersion:i},[...r,"generators",a.toString(),n.name])))}async function c8j(e,t,r){await r.file?.(e,[]),await P8t(e,{"auth-schemes":Et,api:Et,whitelabel:Et,metadata:Et,readme:Et,"default-group":Et,reviewers:Et,openapi:Et,"openapi-overrides":Et,"spec-origin":Et,"async-api":Et,"api-settings":Et,ai:Et,groups:async i=>{await s8j({groups:i,visitor:r,nodePath:["groups"],cliVersion:t})}})}function l8j({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let o=async(c,f)=>{for(let s of r){let u=s.generatorsYml?.[a];if(u!=null){let l=await u(c,{relativeFilepath:e,contents:t});i(l.map(p=>({severity:p.severity,relativeFilepath:e,nodePath:f,message:p.message})))}}};return{[a]:o}}return{...n("file"),...n("generatorInvocation")}}function Dw8(e,t,r){if(!k6(r,t))return[{severity:"fatal",message:`The generator ${e} requires CLI version ${t} or later (current version: ${r}). Please run \`fern upgrade\` to upgrade your CLI version and use this generator.`}]}function Bw8(e){return Number(e.replace("v",""))}var Mbd={name:"compatible-ir-version",create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e,cliVersion:t})=>{let r=Uyo({token:void 0});if(t==null)return[];let i=await r.generators.cli.getCliRelease(t);if(!i.ok)return[];let n=i.body.irVersion,a;if(e["ir-version"]!=null)a=Bw8(e["ir-version"]);else{let c=await cHi(e);if(c==null)return[];a=c}if(a<=n)return[];let o=await r.generators.cli.getMinCliForIr(a);return o.ok?Dw8(e.name,o.body.version,t)??[]:[]}}})};function f8j(){return[Mbd]}async function Dbd(e,t){return Iw8({workspace:e,rules:f8j(),logger:t})}async function Iw8({workspace:e,rules:t,logger:r}){let i=[],n=await Promise.all(t.map(a=>a.create({workspace:e,logger:r})));if(e.generatorsConfiguration?.rawConfiguration){let a=await Cw8({contents:e.generatorsConfiguration.rawConfiguration,allRuleVisitors:n,cliVersion:e.cliVersion});i.push(...a)}return i}async function Cw8({contents:e,allRuleVisitors:t,cliVersion:r}){let i=[],n=l8j({relativeFilepath:Ze.of(IS),contents:e,allRuleVisitors:t,addViolations:a=>{i.push(...a)}});return await c8j(e,r,n),i}var d8j=require("fs/promises"),Bbd={name:"no-duplicate-overrides",run:async({workspace:e,specs:t,context:r})=>{let i=[],n=new Map,a=new Set;for(let o of t){let c=(await(0,d8j.readFile)(o.absoluteFilepath)).toString();if(c.includes("openapi")||c.includes("swagger")){let f=await bEa({absolutePathToOpenAPI:o.absoluteFilepath,context:r,absolutePathToOpenAPIOverrides:o.absoluteFilepathToOverrides}),s=jwa(f)?await _Ea(f):f;for(let[u,l]of Object.entries(s.paths??{}))for(let[p,_]of Object.entries(l??{})){if(p==="parameters"||p==="$ref")continue;let h=_,y=h?.["x-fern-sdk-group-name"],b=Array.isArray(y)?y.join("."):y,v=h?.["x-fern-sdk-method-name"];if(b&&v){let O=h?.["x-fern-audiences"],A=O?Array.isArray(O)?O.map(j=>j.trim()).filter(j=>j.length>0):[O.trim()].filter(j=>j.length>0):[],g=`${b}:${v}`,m=n.get(g)||[];for(let j of m)if(qw8(A,j)){i.push({severity:"fatal",relativeFilepath:Ev(e.absoluteFilePath,o.source.file),nodePath:["paths",u,p],message:`SDK method ${b}.${v} already exists (x-fern-sdk-group-name: ${b}, x-fern-sdk-method-name: ${v})`});break}m.push(A),n.set(g,m)}}}}return i}};function qw8(e,t){return e.length===0||t.length===0?!0:e.some(r=>t.includes(r))}function p8j(){return[Bbd]}async function Ibd(e,t){return await Tw8({workspace:e,context:t,rules:p8j()})}async function Tw8({workspace:e,context:t,rules:r}){let i=await _Pe({context:t,specs:e.specs});return(await Promise.all(r.map(a=>a.run({workspace:e,specs:i,context:t})))).flat()}var y8j=ae(h8j(),1);async function Qw8({workspace:e,context:t,logWarnings:r,logSummary:i=!0,ossWorkspace:n}){let a=performance.now(),o=Sbd(e,t.logger),c=await Dbd(e,t.logger),f=[...o,...c];n&&f.push(...await Ibd(n,t));let s=performance.now()-a,{hasErrors:u}=ILn({violations:f,context:t,logWarnings:r,logSummary:i,elapsedMillis:s});return{hasErrors:u}}async function N_i({workspace:e,context:t,logWarnings:r,ossWorkspace:i}){(0,y8j.default)(e.definition.rootApiFile.contents.name).validForNewPackages||t.failAndThrow("API name is not valid.");let{hasErrors:n}=await Qw8({workspace:e,context:t,logWarnings:r,ossWorkspace:i});n&&t.failAndThrow()}async function v8j({organization:e,workspace:t,projectConfig:r,context:i,groupName:n,version:a,shouldLogS3Url:o,token:c,useLocalDocker:f,keepDocker:s,absolutePathToPreview:u,mode:l,runner:p,inspect:_,lfsOverride:h}){if(t.generatorsConfiguration==null){i.logger.warn("This workspaces has no generators.yml");return}if(t.generatorsConfiguration.groups.length===0){i.logger.warn(`This workspace has no groups specified in ${IS}`);return}let y=n??t.generatorsConfiguration.defaultGroup;if(y==null)return i.failAndThrow(`No group specified. Use the --${GK_} option, or set "${Rio}" in ${IS}`);let b=t.generatorsConfiguration.groups.find(O=>O.groupName===y);if(b==null)return i.failAndThrow(`Group '${y}' does not exist.`);let{ai:v}=t.generatorsConfiguration;if(h!=null&&(b=Uw8(b,h,i)),await N_i({workspace:await t.toFernWorkspace({context:i}),context:i,logWarnings:!1}),f)await _Lj({token:c,projectConfig:r,workspace:t,generatorGroup:b,version:a,keepDocker:s,context:i,runner:p,absolutePathToPreview:u,inspect:_,ai:v});else{if(!c)return i.failAndThrow("Please run fern login");await Ahd({projectConfig:r,organization:e,workspace:t,context:i,generatorGroup:b,version:a,shouldLogS3Url:o,token:c,whitelabel:t.generatorsConfiguration.whitelabel,absolutePathToPreview:u,mode:l})}}function Uw8(e,t,r){let i=Lr.of(_s(F0(),t)),n={},a=[];for(let o of e.generators){let c=o.language??Lw8(o.name),f;if(e.generators.length===1)f=i;else{let u=c||"unknown";n[u]==null&&(n[u]=0),n[u]++;let l=n[u]===1?u:`${u}-${n[u]}`;f=Ft(i,Ze.of(l))}let s={...o,outputMode:b8j.FernFiddle.remoteGen.OutputMode.downloadFiles({}),absolutePathToLocalOutput:f};a.push(s),r.logger.info(`Overriding output for generator '${o.name}' to local-file-system at: ${f}`)}return{...e,generators:a}}function Lw8(e){return e.includes("typescript")||e.includes("ts")?"typescript":e.includes("python")||e.includes("py")?"python":e.includes("java")?"java":e.includes("go")?"go":e.includes("ruby")?"ruby":e.includes("csharp")||e.includes("c#")?"csharp":e.includes("swift")?"swift":e.includes("php")?"php":e.includes("rust")?"rust":e.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}var g8j={PullRequest:"pull-request"};async function Cbd({project:e,cliContext:t,version:r,groupName:i,shouldLogS3Url:n,keepDocker:a,useLocalDocker:o,preview:c,mode:f,force:s,runner:u,inspect:l,lfsOverride:p}){let _;if(!o){let h=await t.runTask(async y=>Fme(y));h.type==="user"&&await t.runTask(async y=>{await ANt({organization:e.config.organization,token:h,context:y})}),_=h}for(let h of e.apiWorkspaces)for(let y of h.generatorsConfiguration?.groups.filter(b=>i==null||i===b.groupName).flatMap(b=>b.generators)??[]){let{shouldProceed:b}=await tJ_(y.absolutePathToLocalOutput,t,s);b||t.failAndThrow("Generation cancelled")}await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate",properties:{workspaces:e.apiWorkspaces.map(h=>({name:h.workspaceName,group:i,generators:h.generatorsConfiguration?.groups.filter(y=>i==null?!0:y.groupName===i).map(y=>y.generators.map(b=>({name:b.name,version:b.version,outputMode:b.outputMode.type,config:b.config})))}))}}),await Promise.all(e.apiWorkspaces.map(async h=>{await t.runTaskForWorkspace(h,async y=>{let b=c?Ft(h.absoluteFilePath,Ze.of(HK_)):void 0;b!=null&&y.logger.info(`Writing preview to ${b}`),await v8j({organization:e.config.organization,workspace:h,projectConfig:e.config,context:y,version:r,groupName:i,shouldLogS3Url:n,token:_,useLocalDocker:o,keepDocker:a,absolutePathToPreview:b,mode:f,runner:u,inspect:l,lfsOverride:p})})}))}function O8j(){return!!(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.CIRCLECI||process.env.TRAVIS||process.env.JENKINS_URL||process.env.JENKINS_HOME||process.env.TF_BUILD||process.env.BUILDKITE||process.env.CODEBUILD_BUILD_ID||process.env.TEAMCITY_VERSION||process.env.BITBUCKET_BUILD_NUMBER||process.env.DRONE||process.env.SEMAPHORE||process.env.APPVEYOR||process.env.BUDDY_WORKSPACE_ID||process.env.WERCKER_RUN_ID)}async function A8j({project:e,cliContext:t,instance:r,preview:i,brokenLinks:n,strictBrokenLinks:a,disableTemplates:o,noPrompt:c,skipUpload:f}){let s=e.docsWorkspaces;if(s==null){t.failAndThrow("No docs.yml file found. Please make sure your project has one.");return}let u=process.env.FERN_SELF_HOSTED==="true";if(!i&&!O8j()&&!c){let p=r??s.config.instances[0]?.url,_=p?` (${Lt.cyan(`https://${p}`)})`:"";if(!await t.confirmPrompt(`This will affect a production site${_}. Run with --preview to generate docs for a preview instance.
|
|
2031
|
+
`)}]:r(i)}}}};var mbd={name:"valid-stream-condition",create:({workspace:e})=>({definitionFile:{streamCondition:({endpoint:t,streamCondition:r},{relativeFilepath:i,contents:n})=>{let a=new _b(e),o=nf({relativeFilepath:i,definitionFile:n,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents});return t.response==null||t["response-stream"]==null?r==null?[]:[{severity:"fatal",message:"stream-condition can only be used if both response and response-stream are specified."}]:r==null?[{severity:"fatal",message:"stream-condition must be specified when both response and response-stream are specified."}]:dw8({endpoint:t,typeResolver:a,file:o,requestProperty:r,propertyValidator:{propertyID:"stream-condition",validate:fw8}})}}})};function fw8({resolvedType:e}){let t=a8t(e);return t==null?!1:t==="BOOLEAN"}function dw8({endpoint:e,typeResolver:t,file:r,requestProperty:i,propertyValidator:n}){let a=[],o=hla(i);return o==null?[{severity:"fatal",message:"Please specify path to a valid property (e.g. $request.stream)"}]:_la({typeResolver:t,file:r,endpoint:e,propertyComponents:o,validate:n.validate})?a:[{severity:"fatal",message:`Property "${i}" does not exist on the request.`}]}var pw8=/^[a-z]/i,Pbd={name:"valid-type-name",create:()=>({definitionFile:{typeDeclaration:({typeName:e})=>!e.isInlined&&!pw8.test(e.name)?[{severity:"fatal",message:"Type name must begin with a letter"}]:[]}})};var wbd={name:"valid-type-reference-with-default-and-validation",create:({workspace:e})=>{let t=new _b(e);return{definitionFile:{typeDeclaration:({declaration:r})=>{if(!aFt(r))return[];let i=new Set(r.enum.map(n=>typeof n=="string"?n:n.value));return r.default!=null&&!i.has(r.default)?[{message:`Default value '${r.default}' is not a valid enum value`,severity:"fatal"}]:[]},typeReference:({typeReference:r,_default:i,validation:n,location:a},{relativeFilepath:o,contents:c})=>{let f=nf({relativeFilepath:o,definitionFile:c,casingsGenerator:oO,rootApiFile:e.definition.rootApiFile.contents}),s=t.resolveType({type:r,file:f});return s==null?[]:a8j({resolvedType:s,_default:i,validation:n})}}}}};function a8j({resolvedType:e,_default:t,validation:r}){let i=[];if(t==null&&r==null)return[];if(e._type==="container"&&(e.container._type==="optional"||e.container._type==="nullable"))return a8j({resolvedType:e.container.itemType,_default:t,validation:r});let n=e._type;if(e._type==="primitive")switch(e.primitive.v1){case"STRING":return hw8({_default:t,validation:r});case"DOUBLE":return yw8({_default:t,validation:r});case"INTEGER":return bw8({_default:t,validation:r});case"BOOLEAN":return vw8({_default:t,validation:r});case"LONG":return gw8({_default:t,validation:r});case"BIG_INTEGER":return Ow8({_default:t,validation:r});case"DATE_TIME":n="datetime";break;case"UUID":n="uuid";break;case"BASE_64":n="base64";break;case"UINT":n="uint";break;case"UINT_64":n="uint64";break}return e._type==="named"&&aFt(e.declaration)?_w8({declaration:e.declaration,_default:t}):(t!=null&&i.push({message:`Default values are not supported for the ${n} type`,severity:"fatal"}),r!=null&&i.push({message:`Validation rules are not supported for the ${n} type`,severity:"fatal"}),i)}function _w8({declaration:e,_default:t}){if(t==null)return[];let r=new Set(e.enum.map(n=>typeof n=="string"?n:n.value)),i=[];return r.has(t)||i.push({message:`Default value '${t}' is not a valid enum value`,severity:"fatal"}),i}function hw8({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="string"&&r.push({message:`Default value '${e}' is not a valid string`,severity:"fatal"}),t!=null&&!Aw8(t)&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the string type`,severity:"fatal"}),r}function yw8({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="number"&&r.push({message:`Default value '${e}' is not a valid double`,severity:"fatal"}),t!=null&&!o8j(t)&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the double type`,severity:"fatal"}),r}function bw8({_default:e,validation:t}){let r=[];return e!=null&&!Number.isInteger(e)&&r.push({message:`Default value '${e}' is not a valid integer`,severity:"fatal"}),t!=null&&(o8j(t)?r.push(...jbd({name:"min",value:t.min}),...jbd({name:"max",value:t.max}),...jbd({name:"multipleOf",value:t.multipleOf})):r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the integer type`,severity:"fatal"})),r}function vw8({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="boolean"&&r.push({message:`Default value '${e}' is not a valid boolean`,severity:"fatal"}),t!=null&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the boolean type`,severity:"fatal"}),r}function gw8({_default:e,validation:t}){let r=[];return e!=null&&typeof e!="number"&&r.push({message:`Default value '${e}' is not a valid long`,severity:"fatal"}),t!=null&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the long type`,severity:"fatal"}),r}function Ow8({_default:e,validation:t}){let r=[];if(e!=null)if(typeof e!="string")r.push({message:`Default value '${e}' is not a valid bigint`,severity:"fatal"});else try{BigInt(e)}catch{r.push({message:`Default value '${e}' is not a valid bigint`,severity:"fatal"})}return t!=null&&r.push({message:`Validation rules '${JSON.stringify(t)}' are not compatible with the bigint type`,severity:"fatal"}),r}function jbd({name:e,value:t}){return t!=null&&!Number.isInteger(t)?[{message:`Validation for '${e}' must be an integer, but found '${t}'`,severity:"fatal"}]:[]}function o8j(e){let t=e;return t.min!=null||t.max!=null||t.exclusiveMin!=null||t.exclusiveMax!=null||t.multipleOf!=null}function Aw8(e){let t=e;return t.minLength!=null||t.maxLength!=null||t.pattern!=null||t.format!=null}var Ebd={name:"valid-version",create:({workspace:e})=>{let t=new _b(e);return{rootApiFile:{file:r=>mw8({root:r,typeResolver:t})}}}};function mw8({root:e,typeResolver:t}){let r=[];return e.version==null||e.version.default==null?[]:(new Set(e.version.values.map(n=>typeof n=="string"?n:n.value)).has(e.version.default)||r.push({severity:"fatal",message:`Default version "${e.version.default}" not found in version values`}),r)}function Pw8(){return[Yyd,Tyd,$yd,jyd,qyd,Hyd,Eyd,obd,zyd,xyd,Qyd,Uyd,Syd,tbd,Vyd,abd,Nyd,Lyd,Wyd,Myd,Iyd,ibd,Ryd,Kyd,wyd,Abd,ebd,rbd,Byd,Pbd,Fyd,sbd,Xyd,kyd,Gyd,bbd,gbd,nbd,wbd,mbd,Ebd,Zyd,ubd,myd,Obd,Pyd]}function u8j(){return Pw8().filter(({DISABLE_RULE:e=!1})=>!e)}function Sbd(e,t){return jw8({workspace:e,rules:u8j(),logger:t})}function jw8({workspace:e,rules:t,logger:r}){let i=[],n=t.map(o=>o.create({workspace:e,logger:r})),a=Ew8({contents:e.definition.rootApiFile.contents,allRuleVisitors:n});return i.push(...a),TB(e,(o,c)=>{let f=ww8({relativeFilepath:o,contents:c,allRuleVisitors:n});i.push(...f)}),p$i(e,(o,c)=>{let f=Sw8({relativeFilepath:o,contents:c,allRuleVisitors:n});i.push(...f)}),i}function ww8({relativeFilepath:e,contents:t,allRuleVisitors:r}){let i=[],n=mLj({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:a=>{i.push(...a)}});return S3(t,n),i}function Ew8({contents:e,allRuleVisitors:t}){let r=[],i=jLj({relativeFilepath:Ze.of(n1),contents:e,allRuleVisitors:t,addViolations:n=>{r.push(...n)}});return Ayd(e,i),r}function Sw8({relativeFilepath:e,contents:t,allRuleVisitors:r}){let i=[],n=PLj({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:a=>{i.push(...a)}});return Oyd(t,n),i}async function s8j({groups:e,visitor:t,nodePath:r,cliVersion:i}){if(e!=null)for(let[n,a]of Object.entries(e))await Mw8({group:a,visitor:t,nodePath:[...r,n],cliVersion:i})}async function Mw8({group:e,visitor:t,nodePath:r,cliVersion:i}){await Promise.all(e.generators.map(async(n,a)=>await t.generatorInvocation?.({invocation:n,cliVersion:i},[...r,"generators",a.toString(),n.name])))}async function c8j(e,t,r){await r.file?.(e,[]),await P8t(e,{"auth-schemes":Et,api:Et,whitelabel:Et,metadata:Et,readme:Et,"default-group":Et,reviewers:Et,openapi:Et,"openapi-overrides":Et,"spec-origin":Et,"async-api":Et,"api-settings":Et,ai:Et,groups:async i=>{await s8j({groups:i,visitor:r,nodePath:["groups"],cliVersion:t})}})}function l8j({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let o=async(c,f)=>{for(let s of r){let u=s.generatorsYml?.[a];if(u!=null){let l=await u(c,{relativeFilepath:e,contents:t});i(l.map(p=>({severity:p.severity,relativeFilepath:e,nodePath:f,message:p.message})))}}};return{[a]:o}}return{...n("file"),...n("generatorInvocation")}}function Dw8(e,t,r){if(!k6(r,t))return[{severity:"fatal",message:`The generator ${e} requires CLI version ${t} or later (current version: ${r}). Please run \`fern upgrade\` to upgrade your CLI version and use this generator.`}]}function Bw8(e){return Number(e.replace("v",""))}var Mbd={name:"compatible-ir-version",create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e,cliVersion:t})=>{let r=Uyo({token:void 0});if(t==null)return[];let i=await r.generators.cli.getCliRelease(t);if(!i.ok)return[];let n=i.body.irVersion,a;if(e["ir-version"]!=null)a=Bw8(e["ir-version"]);else{let c=await cHi(e);if(c==null)return[];a=c}if(a<=n)return[];let o=await r.generators.cli.getMinCliForIr(a);return o.ok?Dw8(e.name,o.body.version,t)??[]:[]}}})};function f8j(){return[Mbd]}async function Dbd(e,t){return Iw8({workspace:e,rules:f8j(),logger:t})}async function Iw8({workspace:e,rules:t,logger:r}){let i=[],n=await Promise.all(t.map(a=>a.create({workspace:e,logger:r})));if(e.generatorsConfiguration?.rawConfiguration){let a=await Cw8({contents:e.generatorsConfiguration.rawConfiguration,allRuleVisitors:n,cliVersion:e.cliVersion});i.push(...a)}return i}async function Cw8({contents:e,allRuleVisitors:t,cliVersion:r}){let i=[],n=l8j({relativeFilepath:Ze.of(IS),contents:e,allRuleVisitors:t,addViolations:a=>{i.push(...a)}});return await c8j(e,r,n),i}var d8j=require("fs/promises"),Bbd={name:"no-duplicate-overrides",run:async({workspace:e,specs:t,context:r})=>{let i=[],n=new Map;for(let a of t){let o=(await(0,d8j.readFile)(a.absoluteFilepath)).toString();if(o.includes("openapi")||o.includes("swagger")){let c=await bEa({absolutePathToOpenAPI:a.absoluteFilepath,context:r,absolutePathToOpenAPIOverrides:a.absoluteFilepathToOverrides}),f=jwa(c)?await _Ea(c):c;for(let[s,u]of Object.entries(f.paths??{}))for(let[l,p]of Object.entries(u??{})){if(l==="parameters"||l==="$ref")continue;let _=p,h=_?.["x-fern-sdk-group-name"],y=Array.isArray(h)?h.join("."):h,b=_?.["x-fern-sdk-method-name"];if(y&&b){let v=_?.["x-fern-audiences"],O=v?Array.isArray(v)?v.map(j=>j.trim()).filter(j=>j.length>0):[v.trim()].filter(j=>j.length>0):[],g=`${a.namespace??""}:${y}:${b}`,m=n.get(g)||[];for(let j of m)if(qw8(O,j)){let M=a.namespace!=null?`${a.namespace}.${y}`:y;i.push({severity:"fatal",relativeFilepath:Ev(e.absoluteFilePath,a.source.file),nodePath:["paths",s,l],message:`SDK method ${M}.${b} already exists (x-fern-sdk-group-name: ${y}, x-fern-sdk-method-name: ${b})`});break}m.push(O),n.set(g,m)}}}}return i}};function qw8(e,t){return e.length===0||t.length===0?!0:e.some(r=>t.includes(r))}function p8j(){return[Bbd]}async function Ibd(e,t){return await Tw8({workspace:e,context:t,rules:p8j()})}async function Tw8({workspace:e,context:t,rules:r}){let i=await _Pe({context:t,specs:e.specs});return(await Promise.all(r.map(a=>a.run({workspace:e,specs:i,context:t})))).flat()}var y8j=ae(h8j(),1);async function Qw8({workspace:e,context:t,logWarnings:r,logSummary:i=!0,ossWorkspace:n}){let a=performance.now(),o=Sbd(e,t.logger),c=await Dbd(e,t.logger),f=[...o,...c];n&&f.push(...await Ibd(n,t));let s=performance.now()-a,{hasErrors:u}=ILn({violations:f,context:t,logWarnings:r,logSummary:i,elapsedMillis:s});return{hasErrors:u}}async function N_i({workspace:e,context:t,logWarnings:r,ossWorkspace:i}){(0,y8j.default)(e.definition.rootApiFile.contents.name).validForNewPackages||t.failAndThrow("API name is not valid.");let{hasErrors:n}=await Qw8({workspace:e,context:t,logWarnings:r,ossWorkspace:i});n&&t.failAndThrow()}async function v8j({organization:e,workspace:t,projectConfig:r,context:i,groupName:n,version:a,shouldLogS3Url:o,token:c,useLocalDocker:f,keepDocker:s,absolutePathToPreview:u,mode:l,runner:p,inspect:_,lfsOverride:h}){if(t.generatorsConfiguration==null){i.logger.warn("This workspaces has no generators.yml");return}if(t.generatorsConfiguration.groups.length===0){i.logger.warn(`This workspace has no groups specified in ${IS}`);return}let y=n??t.generatorsConfiguration.defaultGroup;if(y==null)return i.failAndThrow(`No group specified. Use the --${GK_} option, or set "${Rio}" in ${IS}`);let b=t.generatorsConfiguration.groups.find(O=>O.groupName===y);if(b==null)return i.failAndThrow(`Group '${y}' does not exist.`);let{ai:v}=t.generatorsConfiguration;if(h!=null&&(b=Uw8(b,h,i)),await N_i({workspace:await t.toFernWorkspace({context:i}),context:i,logWarnings:!1}),f)await _Lj({token:c,projectConfig:r,workspace:t,generatorGroup:b,version:a,keepDocker:s,context:i,runner:p,absolutePathToPreview:u,inspect:_,ai:v});else{if(!c)return i.failAndThrow("Please run fern login");await Ahd({projectConfig:r,organization:e,workspace:t,context:i,generatorGroup:b,version:a,shouldLogS3Url:o,token:c,whitelabel:t.generatorsConfiguration.whitelabel,absolutePathToPreview:u,mode:l})}}function Uw8(e,t,r){let i=Lr.of(_s(F0(),t)),n={},a=[];for(let o of e.generators){let c=o.language??Lw8(o.name),f;if(e.generators.length===1)f=i;else{let u=c||"unknown";n[u]==null&&(n[u]=0),n[u]++;let l=n[u]===1?u:`${u}-${n[u]}`;f=Ft(i,Ze.of(l))}let s={...o,outputMode:b8j.FernFiddle.remoteGen.OutputMode.downloadFiles({}),absolutePathToLocalOutput:f};a.push(s),r.logger.info(`Overriding output for generator '${o.name}' to local-file-system at: ${f}`)}return{...e,generators:a}}function Lw8(e){return e.includes("typescript")||e.includes("ts")?"typescript":e.includes("python")||e.includes("py")?"python":e.includes("java")?"java":e.includes("go")?"go":e.includes("ruby")?"ruby":e.includes("csharp")||e.includes("c#")?"csharp":e.includes("swift")?"swift":e.includes("php")?"php":e.includes("rust")?"rust":e.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}var g8j={PullRequest:"pull-request"};async function Cbd({project:e,cliContext:t,version:r,groupName:i,shouldLogS3Url:n,keepDocker:a,useLocalDocker:o,preview:c,mode:f,force:s,runner:u,inspect:l,lfsOverride:p}){let _;if(!o){let h=await t.runTask(async y=>Fme(y));h.type==="user"&&await t.runTask(async y=>{await ANt({organization:e.config.organization,token:h,context:y})}),_=h}for(let h of e.apiWorkspaces)for(let y of h.generatorsConfiguration?.groups.filter(b=>i==null||i===b.groupName).flatMap(b=>b.generators)??[]){let{shouldProceed:b}=await tJ_(y.absolutePathToLocalOutput,t,s);b||t.failAndThrow("Generation cancelled")}await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate",properties:{workspaces:e.apiWorkspaces.map(h=>({name:h.workspaceName,group:i,generators:h.generatorsConfiguration?.groups.filter(y=>i==null?!0:y.groupName===i).map(y=>y.generators.map(b=>({name:b.name,version:b.version,outputMode:b.outputMode.type,config:b.config})))}))}}),await Promise.all(e.apiWorkspaces.map(async h=>{await t.runTaskForWorkspace(h,async y=>{let b=c?Ft(h.absoluteFilePath,Ze.of(HK_)):void 0;b!=null&&y.logger.info(`Writing preview to ${b}`),await v8j({organization:e.config.organization,workspace:h,projectConfig:e.config,context:y,version:r,groupName:i,shouldLogS3Url:n,token:_,useLocalDocker:o,keepDocker:a,absolutePathToPreview:b,mode:f,runner:u,inspect:l,lfsOverride:p})})}))}function O8j(){return!!(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.CIRCLECI||process.env.TRAVIS||process.env.JENKINS_URL||process.env.JENKINS_HOME||process.env.TF_BUILD||process.env.BUILDKITE||process.env.CODEBUILD_BUILD_ID||process.env.TEAMCITY_VERSION||process.env.BITBUCKET_BUILD_NUMBER||process.env.DRONE||process.env.SEMAPHORE||process.env.APPVEYOR||process.env.BUDDY_WORKSPACE_ID||process.env.WERCKER_RUN_ID)}async function A8j({project:e,cliContext:t,instance:r,preview:i,brokenLinks:n,strictBrokenLinks:a,disableTemplates:o,noPrompt:c,skipUpload:f}){let s=e.docsWorkspaces;if(s==null){t.failAndThrow("No docs.yml file found. Please make sure your project has one.");return}let u=process.env.FERN_SELF_HOSTED==="true";if(!i&&!O8j()&&!c){let p=r??s.config.instances[0]?.url,_=p?` (${Lt.cyan(`https://${p}`)})`:"";if(!await t.confirmPrompt(`This will affect a production site${_}. Run with --preview to generate docs for a preview instance.
|
|
2032
2032
|
${Lt.yellow("?")} Are you sure you want to continue?`,!1)){t.logger.info("Docs generation cancelled.");return}}let l=null;if(u){let p=process.env.FERN_TOKEN;if(!p){t.failAndThrow("No token found. Please set the FERN_TOKEN environment variable.");return}l={type:"organization",value:p}}else if(l=await t.runTask(async p=>Fme(p)),l.type==="user"){let p=l;await t.runTask(async _=>{await ANt({organization:e.config.organization,token:p,context:_})})}u||await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate --docs"}),await t.runTaskForWorkspace(s,async p=>{await ZKo({workspace:s,context:p,logWarnings:!1,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:await oU(e),errorOnBrokenLinks:a,excludeRules:Vw8(n,a,u)}),p.logger.info("Validation complete, starting remote docs generation...");let _=performance.now(),h=await oU(e),y=performance.now()-_;p.logger.debug(`Filtered OSS workspaces (${h.length} workspaces) in ${y.toFixed(0)}ms`);let b=performance.now();await tyd({organization:e.config.organization,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:h,docsWorkspace:s,context:p,token:l,instanceUrl:r,preview:i,disableTemplates:o,skipUpload:f});let v=performance.now()-b;p.logger.debug(`Remote docs generation completed in ${v.toFixed(0)}ms`)})}function Vw8(e,t,r){let i=[];return!e&&!t&&i.push(mMa.ValidMarkdownLinks.name),r&&i.push(mMa.ValidFileTypes.name),i}var m8j=ae(require("path"),1);async function gla({workspace:e,context:t,generationLanguage:r,keywords:i,smartCasing:n,disableExamples:a,audiences:o,readme:c,disableDynamicExamples:f}){return await N_i({workspace:e,context:t,logWarnings:!1}),kw({workspace:e,generationLanguage:r,keywords:i,smartCasing:n,exampleGeneration:{disabled:a},audiences:o,readme:c,version:void 0,packageName:void 0,context:t,sourceResolver:new Zw(t,e),disableDynamicExamples:f})}async function P8j({project:e,irFilepath:t,cliContext:r,generationLanguage:i,audiences:n,version:a,keywords:o,smartCasing:c,disableDynamicExamples:f}){await Promise.all(e.apiWorkspaces.map(async s=>{await r.runTaskForWorkspace(s,async u=>{r.logger.info(`Generating IR for workspace ${s.workspaceName??"api"}`);let l=await s.toFernWorkspace({context:u}),p=await gla({workspace:l,context:u,generationLanguage:i,keywords:o,smartCasing:c,disableExamples:!1,audiences:n,readme:void 0,disableDynamicExamples:f});if(p.dynamic==null)throw new Error("Internal error; dynamic IR was not generated");let _=m8j.default.resolve(t);await SW(Lr.of(_),p.dynamic),u.logger.info(`Wrote IR to ${_}`)})}))}var j8j=ae(require("path"),1);async function w8j({project:e,outputFilepath:t,cliContext:r,audiences:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await r.runTaskForWorkspace(n,async a=>{let o=await n.toFernWorkspace({context:a}),c=await gla({workspace:o,context:a,generationLanguage:void 0,audiences:i,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,disableDynamicExamples:!0}),f=qx({ir:c,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},context:a}),s=Lr.of(j8j.default.resolve(t));await SW(s,f,{pretty:!0}),a.logger.info(`Wrote FDR API definition to ${s}`)})}))}var E8j=ae(require("path"),1);async function S8j({project:e,irFilepath:t,cliContext:r,generationLanguage:i,audiences:n,version:a,keywords:o,smartCasing:c,readme:f,directFromOpenapi:s,disableExamples:u}){await Promise.all(e.apiWorkspaces.map(async l=>{await r.runTaskForWorkspace(l,async p=>{r.logger.info(`Generating IR for workspace ${l.workspaceName??"api"}`);let _=await Ww8({workspace:l,context:p,generationLanguage:i,keywords:o,smartCasing:c,disableExamples:u,audiences:n,version:a,readme:f,directFromOpenapi:s}),h=Lr.of(E8j.default.resolve(t));await SW(h,_,{pretty:!0}),p.logger.info(`Wrote IR to ${h}`)})}))}async function Ww8({workspace:e,context:t,generationLanguage:r,audiences:i,keywords:n,smartCasing:a,disableExamples:o,version:c,readme:f,directFromOpenapi:s}){let u;if(s&&e instanceof YS)u=await e.getIntermediateRepresentation({context:t,audiences:i,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});else{let l=await e.toFernWorkspace({context:t});u=await gla({workspace:l,context:t,generationLanguage:r,audiences:i,keywords:n,smartCasing:a,disableExamples:o,readme:f,disableDynamicExamples:!0})}return c==null?zn.IntermediateRepresentation.jsonOrThrow(u,{unrecognizedObjectKeys:"strip"}):Zka({intermediateRepresentation:u,version:c,context:t})}var M8j=ae(require("path"),1);async function qbd({project:e,outputFilepath:t,cliContext:r,directFromOpenapi:i,audiences:n}){await Promise.all(e.apiWorkspaces.map(async a=>{await r.runTaskForWorkspace(a,async o=>{let c=i?await wvc(a,o,n):await pgc(a,o),f=Lr.of(M8j.default.resolve(t));await SW(f,c,{pretty:!0}),o.logger.info(`Wrote FDR API definition to ${f}`)})}))}var D8j=ae(require("path"),1);async function B8j({project:e,irFilepath:t,cliContext:r,sdkLanguage:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await r.runTaskForWorkspace(n,async a=>{if(n instanceof QGt){a.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(n instanceof YS))return;let o=new CFt(n.absoluteFilePath),c=await _Pe({context:a,specs:n.specs}),f=UJi({context:a,documents:await o.loadDocuments({context:a,specs:c})}),s=Lr.of(D8j.default.resolve(t)),u=Ns.OpenApiIntermediateRepresentation.jsonOrThrow(f,{skipValidation:!0});await SW(s,u,{pretty:!0}),a.logger.info(`Wrote IR to ${s}`)})}))}var YAs=require("fs/promises");async function C8j({project:e,includeModels:t,cliContext:r}){await Promise.all(e.apiWorkspaces.map(async i=>{await r.runTaskForWorkspace(i,async n=>{i instanceof YS?await Gw8({workspace:i,context:n,includeModels:t}):n.logger.warn("Skipping fern workspace definition generation")})}))}async function xw8(e,t){let r=null;try{let i=(await(0,YAs.readFile)(e,"utf8")).toString();try{r=JSON.parse(i)}catch{r=Fi.load(i,{json:!0})}}catch{return t.failAndThrow(`Failed to read OpenAPI overrides from file ${e}`)}return r}async function Gw8({workspace:e,includeModels:t,context:r}){let i=new CFt(e.absoluteFilePath),n=await _Pe({context:r,specs:e.specs});for(let a of n){let o=UJi({context:r,documents:await i.loadDocuments({context:r,specs:[a]})}),c={};a.absoluteFilepathToOverrides!==void 0&&(c=await xw8(a.absoluteFilepathToOverrides,r));let f="path"in c?c.path:{};for(let _ of o.endpoints){let h=cja(_);_.path in f||(f[_.path]={});let y=f[_.path];if(y!=null&&y[_.method]==null){let b=h.file.split("/").map(O=>O.replace(".yml","")).filter(O=>O!=="__package__"),v={};b.length>0&&(v["x-fern-sdk-group-name"]=b),v["x-fern-sdk-method-name"]=h.endpointId,y[_.method.toLowerCase()]=v}else c==null&&r.logger.warn(`Endpoint ${_.path} ${_.method} is defined multiple times`)}let s="path"in c?c.path:{};if(t){I8j(s,o.groupedSchemas.rootSchemas);for(let[_,h]of Object.entries(o.groupedSchemas.namespacedSchemas))I8j(s,h)}let u={schemas:s},l=g9i(a.absoluteFilepath),p="openapi-overrides.yml";if(l!=null){let _=l.lastIndexOf(".");if(_>0){let h=l.substring(0,_),y=l.substring(_);p=`${h}-overrides${y}`}}await(0,YAs.writeFile)(Ft(hn(a.absoluteFilepath),Ze.of(p)),Fi.dump({paths:f,components:u}))}}function I8j(e,t){for(let[r,i]of Object.entries(t)){if(r in e)continue;let n={};n["x-fern-type-name"]="nameOverride"in i?i.nameOverride??r:r,e[r]=n}}function q8j({enum:e,context:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue)}}function T8j({container:e,context:t}){switch(e.type){case"list":return{type:"array",items:oH({typeReference:e.list,context:t})};case"map":return{type:"object",additionalProperties:oH({typeReference:e.valueType,context:t})};case"optional":return e.optional.type==="container"&&e.optional.container.type==="nullable"?{oneOf:[oH({typeReference:e.optional.container.nullable,context:t}),{type:"null"}]}:{oneOf:[oH({typeReference:e.optional,context:t}),{type:"null"}]};case"nullable":return{oneOf:[oH({typeReference:e.nullable,context:t}),{type:"null"}]};case"set":return{type:"array",items:oH({typeReference:e.set,context:t}),uniqueItems:!0};case"literal":switch(e.literal.type){case"string":return{const:e.literal.string};case"boolean":return{const:e.literal.boolean};default:vt(e.literal)}default:vt(e)}}function oH({typeReference:e,context:t}){switch(e.type){case"named":{let r=t.getTypeDeclarationForId({typeId:e.typeId});if(!t.hasDefinition(e.typeId)&&!t.isBuildingTypeDeclaration(e.typeId)){t.buildingTypeDeclaration(e.typeId);let i=Ola({typeDeclaration:r,context:t});t.registerDefinition(e.typeId,i),t.finishedBuildingTypeDeclaration(e.typeId)}return{$ref:`#/definitions/${t.getDefinitionKey(r)}`}}case"container":return T8j({container:e.container,context:t});case"primitive":return Hw8(e.primitive.v1);case"unknown":return{type:["string","number","boolean","object","array","null"]};default:vt(e)}}function Hw8(e){switch(e){case Su.String:return{type:"string"};case Su.Integer:return{type:"integer"};case Su.Long:return{type:"integer"};case Su.Uint:return{type:"integer",minimum:0};case Su.Uint64:return{type:"integer",minimum:0};case Su.Float:return{type:"number"};case Su.Double:return{type:"number"};case Su.Boolean:return{type:"boolean"};case Su.Date:return{type:"string",format:"date"};case Su.DateTime:return{type:"string",format:"date-time"};case Su.Uuid:return{type:"string",format:"uuid"};case Su.Base64:return{type:"string",contentEncoding:"base64"};case Su.BigInteger:return{type:"string",pattern:"^-?[0-9]+$"};default:vt(e)}}function R8j({object:e,context:t}){let r={type:"object"},i=[...e.extendedProperties??[],...e.properties],n=i.map(o=>{let c=o.name.wireValue,f=oH({typeReference:o.valueType,context:t});return[c,f]}),a=i.filter(o=>!t.isOptional(o.valueType)).map(o=>o.name.wireValue);return n.length>0&&(r.properties=Object.fromEntries(n)),a.length>0&&(r.required=a),r.additionalProperties=e.extraProperties,r}function z8j({undiscriminatedUnion:e,context:t}){return{anyOf:e.members.map(r=>{let i=oH({typeReference:r.type,context:t});return r.docs&&(i.description=r.docs),i})}}function N8j({union:e,context:t}){let r=e.discriminant.wireValue;return{type:"object",properties:{[r]:{type:"string",enum:e.types.map(i=>i.discriminantValue.wireValue)}},oneOf:e.types.map(i=>{let n={},a=[];switch(i.shape.propertiesType){case"samePropertiesAsObject":{let o=t.getTypeDeclarationForId({typeId:i.shape.typeId}),c=Ola({typeDeclaration:o,context:t});n=c.properties??{},a=Array.isArray(c.required)?c.required:[];break}case"singleProperty":n.value=oH({typeReference:i.shape.type,context:t});break;case"noProperties":break;default:vt(i.shape)}return{properties:{[r]:{const:i.discriminantValue.wireValue},...n},required:[r,...a]}})}}function Ola({typeDeclaration:e,context:t}){switch(e.shape.type){case"object":return R8j({object:e.shape,context:t});case"alias":return oH({typeReference:e.shape.aliasOf,context:t});case"enum":return q8j({enum:e.shape,context:t});case"union":return N8j({union:e.shape,context:t});case"undiscriminatedUnion":return z8j({undiscriminatedUnion:e.shape,context:t});default:vt(e.shape)}}var XAs=class{context;ir;buildingTypeIds=new Set;definitions={};constructor(t,r){this.context=t,this.ir=r}getTypeDeclarationForId({typeName:t,typeId:r}){let i=this.ir.types[r];return i??(t!=null&&this.context.logger.error(`Type ${t} not found`),this.context.failAndThrow())}isOptional(t){if(t.type==="container"&&t.container.type==="optional")return!0;if(t.type==="named"){let r=this.getTypeDeclarationForId({typeId:t.typeId});if(r.shape.type==="alias")return this.isOptional(r.shape.aliasOf)}return!1}registerDefinition(t,r){let i=this.getTypeDeclarationForId({typeId:t});this.definitions[this.getDefinitionKey(i)]=r}getDefinitions(){return this.definitions}hasDefinition(t){let r=this.getTypeDeclarationForId({typeId:t});return this.getDefinitionKey(r)in this.definitions}getDefinitionKey(t){return[...t.name.fernFilepath.allParts.map(r=>r.originalName),t.name.name.originalName].join(".")}buildingTypeDeclaration(t){this.buildingTypeIds.add(t)}finishedBuildingTypeDeclaration(t){this.buildingTypeIds.delete(t)}isBuildingTypeDeclaration(t){return this.buildingTypeIds.has(t)}};function Tbd(e){let t=new XAs(e.context,e.ir),r=t.getTypeDeclarationForId({typeId:e.typeId,typeName:e.typeName});return{...Ola({typeDeclaration:r,context:t}),definitions:t.getDefinitions()}}var ZAs=require("fs/promises");async function F8j({typeLocator:e,project:t,jsonschemaFilepath:r,cliContext:i}){await Promise.all(t.apiWorkspaces.map(async n=>{await i.runTaskForWorkspace(n,async a=>{let o=await n.toFernWorkspace({context:a}),c=kw({workspace:o,context:a,generationLanguage:void 0,audiences:{type:"all"},keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!0},disableDynamicExamples:!0,version:void 0,packageName:void 0,readme:void 0,sourceResolver:new Zw(a,o)}),f=e.split("."),s=dx({generationLanguage:void 0,keywords:void 0,smartCasing:!1}),u=f[f.length-1]??e,l=f.length>1?`${f.slice(0,-1).join("/")}.yml`:ob,p=up.generateTypeId({fernFilepath:bK({relativeFilepath:Ze.of(`${f.slice(0,-1).join("/")}.yml`),casingsGenerator:s}),name:s.generateName(u),displayName:void 0}),_=Tbd({ir:c,typeName:u,typeId:p,context:a});await Ri(hn(r))||await(0,ZAs.mkdir)(hn(r),{recursive:!0}),await(0,ZAs.writeFile)(r,JSON.stringify(_,null,2)),a.logger.info(Lt.green(`Wrote JSON Schema to ${r}`))})}))}var Rbd=ae(GHo(),1);var kAs=ae(Sv(),1);function Q8j({request:e,example:t}){if(t.request==null&&Object.entries(e.body??{}).length===0)return{type:"equal"};if(typeof t.request?.jsonExample=="object"){if(m8t(JSON.stringify(e.body),JSON.stringify(t.request?.jsonExample??{})))return{type:"equal"};for(let[r,i]of Object.entries(t.request?.jsonExample??{})){let n=e.body[r];if(!r1(n,i))return{type:"notEqual",parameter:[r],actualValue:n,expectedValue:i,location:"body"}}return{type:"equal"}}return m8t(JSON.stringify(e.body),JSON.stringify(t.request?.jsonExample??{}))?{type:"equal"}:{type:"notEqual",parameter:[],actualValue:e.body,expectedValue:t.request?.jsonExample,location:"body"}}function U8j({request:e,example:t}){for(let r of[...t.serviceHeaders,...t.endpointHeaders]){let i=e.headers[r.name.wireValue.toLowerCase()];if(!m8t(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.wireValue],actualValue:i,expectedValue:r.value.jsonExample,location:"header"}}return{type:"equal"}}function L8j({request:e,example:t}){for(let r of[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters]){let i=e.params[r.name.originalName];if(!m8t(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.originalName],actualValue:i,expectedValue:r.value.jsonExample,location:"path"}}return{type:"equal"}}function V8j({request:e,example:t}){for(let r of[...t.queryParameters]){let i=e.query[r.name.wireValue];if(!m8t(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.wireValue],actualValue:i,expectedValue:r.value.jsonExample,location:"query"}}return{type:"equal"}}function W8j({request:e,example:t}){let r=L8j({request:e,example:t});if(r.type==="notEqual")return r;let i=V8j({request:e,example:t});if(i.type==="notEqual")return i;let n=U8j({request:e,example:t});if(n.type==="notEqual")return n;let a=Q8j({request:e,example:t});return a.type==="notEqual"?a:{type:"equal"}}var MSn=class{app=(0,Rbd.default)();context;server=void 0;port=void 0;constructor({context:t,ir:r,port:i}){this.context=t,this.app.use(Rbd.default.json({limit:"50mb",strict:!1})),this.port=i;let n=new Map;for(let f of Object.values(r.services))for(let s of f.endpoints){let u=Kw8(s);t.logger.debug(`Registering ${s.method} ${u} ...`);let l=n.get(u)??new Map,p=l.get(s.method)??[];n.set(u,l.set(s.method,[...p,s]))}let a=(f,s)=>{let u=f[0],l=s[0],p=u.split("/"),_=l.split("/");if(p.length!==_.length)return p.length-_.length;for(let h=0;h<Math.min(p.length,_.length);h++){let y=p[h],b=_[h];if(y===b)continue;if(y==null||b==null)return y==null?-1:1;let v=y.startsWith(":"),O=b.startsWith(":");return v&&!O?1:!v&&O?-1:y.localeCompare(b)}return 0},c=Array.from(n).sort(a);for(let[f,s]of c)for(let[u,l]of s)switch(u){case"GET":this.app.get(f,beo(l));break;case"POST":this.app.post(f,beo(l));break;case"PUT":this.app.put(f,beo(l));break;case"PATCH":this.app.patch(f,beo(l));break;case"DELETE":this.app.delete(f,beo(l));break}}stop(){this.server?.close()}async start(){return this.port=this.port??await fQn(),this.server=this.app.listen(this.port),this.context.logger.info(`Running Fern mock server on localhost: ${this.port}`),this.port}async keepAlive(){await new Promise(()=>{})}};function Kw8(e){let t="";e.fullPath.head.length>0&&(t=(0,kAs.default)(t,e.fullPath.head));for(let r of e.fullPath.parts)t=(0,kAs.default)(t,":"+r.pathParameter),r.tail.length>0&&(t=(0,kAs.default)(t,r.tail));return t.startsWith("/")?t:`/${t}`}function beo(e){let t=!1;return(r,i)=>{let n=[];for(let a of e)for(let o of[...a.userSpecifiedExamples,...a.autogeneratedExamples])if(t=!0,o.example!=null){let c=W8j({request:r,example:o.example});if(c.type==="notEqual"){n.push(c);continue}o.example.response?._visit({ok:f=>{f._visit({body:s=>{if(s==null){i.sendStatus(a.response?.statusCode??204);return}if(a.response?.body?.type==="text"){i.contentType("text/plain"),i.send(s.jsonExample);return}i.json(s.jsonExample)},stream:s=>{s.forEach(u=>{i.write(u.jsonExample)}),i.end()},sse:s=>{i.setHeader("Content-Type","text/event-stream"),s.forEach(u=>{i.write(`event: ${u.event}
|
|
2033
2033
|
`),i.write(`data: ${JSON.stringify(u.data.jsonExample)}
|
|
2034
2034
|
|