fern-api 1.9.0 → 1.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +3 -3
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1160,7 +1160,7 @@ ${a8p.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&P5s(th
|
|
|
1160
1160
|
`+aHi.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?aHi.default.cyan(_8p(t,this.opt.mask)):aHi.default.italic(aHi.default.dim("[hidden]")):this.opt.mask?_8p(t,this.opt.mask):aHi.default.italic(aHi.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 ZBo=re(b1(),1);var _Vp=re(n7s(),1),YBo=require("child_process"),vRn=require("fs"),$Bo=re(require("path"),1),hVp=re(require("os"),1),yVp=require("crypto"),V7s=re(dVp(),1);var HBo=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var wOa=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var JBo=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var KBo=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function XBo(e="",t,r){let i=new W7s(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 pVp(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function nAS(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 W7s=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=nAS(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??hVp.default.tmpdir(),r=(0,yVp.randomUUID)(),i=pVp(this.fileOptions.prefix),n=pVp(this.fileOptions.postfix),a=`${i}${r}${n}`,o=$Bo.default.resolve(t,a),c=$Bo.default.resolve(t)+$Bo.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,vRn.writeFileSync)(this.tempFile,this.text,f)}catch(t){throw new HBo(t)}}readTemporaryFile(){try{let t=(0,vRn.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,_Vp.detect)(t)??"utf8";V7s.default.encodingExists(r)||(r="utf8"),this.text=V7s.default.decode(t,r)}}catch(t){throw new JBo(t)}}removeTemporaryFile(){try{(0,vRn.unlinkSync)(this.tempFile)}catch(t){throw new KBo(t)}}launchEditor(){try{let t=(0,YBo.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new wOa(t)}}launchEditorAsync(t){try{(0,YBo.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new wOa(r)}}};var bVp=re(ehe(),1);var EOa=class extends v1{_run(t){this.done=t,this.editorResult=new bVp.Subject;let r=FQ(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"?ZBo.default.dim("Received"):ZBo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=ZBo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),XBo(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 mVp=require("stream");var OVp=re(require("readline"),1),AVp=re(gVp(),1),cHi=class{constructor(t){this.rl||=OVp.default.createInterface(oAS(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 oAS(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 AVp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var SOa=class extends cHi{constructor(t={}){super(t),this.log=new mVp.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return lOa(this.rl,this.bottomBar.split(`
|
|
1161
1161
|
`).length),this}updateBottomBar(t){return lOa(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+`
|
|
1162
1162
|
`}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&&OBo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var fO=re(ehe(),1),wVp=re(Iga(),1);var kBo=re(ehe(),1),PVp=re(Iga(),1),eIo=function(e,t,r){return typeof e[t]!="function"?(0,kBo.of)(e):(0,kBo.from)((0,PVp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var jVp={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}},gRn=class extends cHi{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,fO.from)(t):(0,fO.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,fO.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,fO.from)([t]),this.process=i.pipe((0,fO.concatMap)(this.processQuestion.bind(this)),(0,fO.publish)()),this.process.connect(),this.process.pipe((0,fO.reduce)((n,a)=>(jVp.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,fO.defer)(()=>(0,fO.of)(t).pipe((0,fO.concatMap)(this.setDefaultType.bind(this)),(0,fO.concatMap)(this.filterIfRunnable.bind(this)),(0,fO.concatMap)(()=>eIo(t,"message",this.answers)),(0,fO.concatMap)(()=>eIo(t,"default",this.answers)),(0,fO.concatMap)(()=>eIo(t,"choices",this.answers)),(0,fO.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,fO.defer)(()=>(0,fO.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,fO.defer)(()=>(0,fO.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&jVp.get(this.answers,t.name)!==void 0)return fO.EMPTY;if(t.when===!1)return fO.EMPTY;if(typeof t.when!="function")return(0,fO.of)(t);let{answers:r}=this;return(0,fO.defer)(()=>(0,fO.from)((0,wVp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,fO.filter)(i=>i!=null)))}};function EVp(e){let t=function(r,i){let n;try{n=new gRn(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",dOa),this.registerPrompt("input",nHi),this.registerPrompt("number",pOa),this.registerPrompt("confirm",_Oa),this.registerPrompt("rawlist",hOa),this.registerPrompt("expand",yOa),this.registerPrompt("checkbox",bOa),this.registerPrompt("password",vOa),this.registerPrompt("editor",EOa)},t.restoreDefaultPrompts(),t}var G7s=EVp();function sAS(e,t){G7s.registerPrompt(e,t)}function cAS(){G7s.restoreDefaultPrompts()}var lAS={prompt:G7s,ui:{BottomBar:SOa,Prompt:gRn},createPromptModule:EVp,registerPrompt:sAS,restoreDefaultPrompts:cAS,Separator:EH},tIo=lAS;var CRn=require("path"),axp=require("fs"),oxp=require("readline"),BWp="posthog-node";function N0S(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[AIo.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 AIo=class{constructor(t,r,i,n){this.name=BWp,this.name=BWp,this.setupOnce=function(a,o){let c=o()?.getClient()?.getDsn()?.projectId;a(N0S(t,{organization:r,projectId:c,prefix:i,severityAllowList:n}))}}};AIo.POSTHOG_ID_TAG="posthog_distinct_id";var yIo="0123456789abcdef",mIo=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+=yIo.charAt(this.bytes[r]>>>4),t+=yIo.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+=yIo.charAt(this.bytes[r]>>>4),t+=yIo.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}},DHs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??F0S()}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 mIo.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,mIo.ofInner(t)}},F0S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),IWp,BHs=()=>Q0S().toString(),Q0S=()=>(IWp||(IWp=new DHs)).generate();function U0S(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 L0S(e,t){global.process.on("uncaughtException",U0S(e,t))}function V0S(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var bIo,CWp,vIo;function W0S(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return vIo&&r.length===CWp||(CWp=r.length,vIo=r.reduce((i,n)=>{bIo||(bIo={});let a=bIo[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,bIo[n]=[s,u];break}}}return i},{})),vIo}function x0S(e){return typeof Event<"u"&&uxp(e,Event)}function G0S(e){return sxp(e,"Object")}function FHs(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return uxp(e,Error)}}function uxp(e,t){try{return e instanceof t}catch{return!1}}function H0S(e){return sxp(e,"ErrorEvent")}function sxp(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function J0S(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},o=cxp(a,r,i);return{$exception_list:await Promise.all(o.map(async s=>{let u=await ePS(e,t,s);return u.value=u.value||"",u.type=u.type||"Error",u.mechanism=a,u}))}}function cxp(e,t,r){let i=K0S(e,t,r);return i.cause?[i,...cxp(e,i.cause,r)]:[i]}function K0S(e,t,r){if(FHs(t))return t;if(e.synthetic=!0,G0S(t)){let n=$0S(t);if(n)return n;let a=Y0S(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 $0S(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(FHs(r))return r}}function Y0S(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=Z0S(e);if(H0S(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=X0S(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function X0S(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function Z0S(e,t=40){let r=Object.keys(k0S(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return qWp(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:qWp(a,t)}return""}function qWp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function k0S(e){return FHs(e)?{message:e.message,name:e.name,stack:e.stack,...TWp(e)}:x0S(e)?{type:e.type,target:RWp(e.target),currentTarget:RWp(e.currentTarget),...TWp(e)}:e}function TWp(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 RWp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function ePS(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=tPS(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function tPS(e,t){return rPS(e(t.stack||"",1),e)}function rPS(e,t){let r=W0S(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var iPS=2e3,DRn=class e{static async captureException(t,r,i,n,a){let o={...a};n||(o.$process_person_profile=!1);let c=await J0S(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||BHs(),properties:{...c,...o}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(L0S(this.onException.bind(this),this.onFatalError.bind(this)),V0S(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(iPS)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function nPS(e=process.argv[1]?(0,CRn.dirname)(process.argv[1]):process.cwd(),t=CRn.sep==="\\"){let r=t?zWp(e):e;return i=>{if(!i)return;let n=t?zWp(i):i,{dir:a,base:o,ext:c}=CRn.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 zWp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var PIo=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)}}},OIo=new PIo(25),lxp=new PIo(20),QHs=7,aPS=1e3,oPS=1e4;async function uPS(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"||fPS(o)||dPS(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(lxp.get(n))continue;let a=t[n];if(!a)continue;a.sort((f,s)=>f-s);let o=_PS(a);if(o.every(f=>pPS(n,f)))continue;let c=hPS(OIo,n,{});i.push(sPS(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&cPS(e,OIo),OIo.reduce(),e}function sPS(e,t,r){return new Promise(i=>{let n=(0,axp.createReadStream)(e),a=(0,oxp.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(){lxp.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]=yPS(_,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 cPS(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;lPS(r.lineno,r,i)}}function lPS(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=fxp(e);n<e;n++){let a=r[n];if(a===void 0){NWp(t);return}t.pre_context.push(a)}if(r[e]===void 0){NWp(t);return}t.context_line=r[e];let i=dxp(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 NWp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function fPS(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function dPS(e){return e.lineno!==void 0&&e.lineno>oPS||e.colno!==void 0&&e.colno>aPS}function pPS(e,t){let r=OIo.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 _PS(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=FWp(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+QHs:(n.push(i),i=FWp(a)),t++}return n}function FWp(e){return[fxp(e),dxp(e)]}function fxp(e){return Math.max(1,e-QHs)}function dxp(e){return e+QHs}function hPS(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function yPS(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 bPS="4.18.0",IH;(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"})(IH||(IH={}));var QWp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(QWp||(QWp={}));var UWp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(UWp||(UWp={}));var LWp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(LWp||(LWp={}));var VWp;(function(e){e.Html="html",e.Text="text"})(VWp||(VWp={}));var WWp;(function(e){e.Number="number",e.Emoji="emoji"})(WWp||(WWp={}));var xWp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(xWp||(xWp={}));var GWp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(GWp||(GWp={}));var HWp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(HWp||(HWp={}));var JWp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(JWp||(JWp={}));var vPS=e=>{if("flags"in e){let t=OPS(e.flags),r=APS(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,pxp(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,gPS(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function gPS(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 OPS=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,UHs(r)]).filter(([,t])=>t!==void 0)),APS=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?pxp(i):void 0]}))},UHs=e=>e===void 0?void 0:e.variant??e.enabled,pxp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},mPS=1,PPS=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"]),jPS="utf8";function wPS(e,t){if(!e||typeof e!="string"||EPS(e))throw new Error(t)}function EPS(e){return e.trim().length===0}function SPS(e){return e?.replace(/\/+$/,"")}async function MPS(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 KWp(){return new Date().getTime()}function SHs(){return new Date().toISOString()}function jIo(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function DPS(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function BPS(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 IPS(e,t=0,r){let i=BPS(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function $Wp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var NOa=String.fromCharCode,YWp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",gIo={};function CPS(e,t){if(!gIo[e]){gIo[e]={};for(let r=0;r<e.length;r++)gIo[e][e.charAt(r)]=r}return gIo[e][t]}var SRn={compressToBase64:function(e){if(e==null)return"";let t=SRn._compress(e,6,function(r){return YWp.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:SRn._decompress(e.length,32,function(t){return CPS(YWp,e.charAt(t))})},compress:function(e){return SRn._compress(e,16,function(t){return NOa(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:SRn._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=NOa(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=NOa(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++]=NOa(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++]=NOa(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++)}}},IHs=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)}},BRn=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 XWp(e){if(e instanceof BRn){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 MHs(e){return typeof e=="object"&&(e instanceof BRn||e instanceof FOa)}function ZWp(e){return typeof e=="object"&&e instanceof BRn&&e.status===413}var CHs;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(CHs||(CHs={}));var qHs=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new IHs,this._isInitialized=!1,wPS(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=SPS(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:MHs},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(IH.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(IH.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(IH.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=BHs();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=IPS(this.apiKey,mPS,PPS)?`${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=>vPS(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=UHs(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(CHs.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(IH.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(IH.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(IH.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(IH.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(IH.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=jIo(()=>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:SHs()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${KWp()}&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(SRn.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:SHs(),uuid:i?.uuid?i.uuid:BHs()};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 XWp(t)})}async flush(){let t=$Wp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),$Wp([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(IH.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(IH.Queue)||[]).slice(n.length);this.setPersistedProperty(IH.Queue,_),t=_},c={api_key:this.apiKey,batch:a,sent_at:SHs()};this.historicalMigration&&(c.historical_migration=!0);let f=JSON.stringify(c),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${KWp()}&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(SRn.compressToBase64(f))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:f},l={retryCheck:p=>ZWp(p)?!1:MHs(p)};try{await this.fetchWithRetry(s,u,l)}catch(p){if(ZWp(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,jPS)}catch{c=new TextEncoder().encode(o).length}return await MPS(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 BRn(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(IH.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!MHs(n))throw n;await XWp(n)}};return Promise.race([new Promise((n,a)=>{jIo(()=>{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}},THs=DPS();if(!THs){let e=DWp();THs=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 _xp=THs,wIo=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()}},hxp=new wIo(async()=>{try{return await import("crypto")}catch{return}});async function qPS(){return await hxp.getValue()}var TPS=new wIo(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await hxp.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function RPS(){return await TPS.getValue()}async function zPS(e){let t=await qPS();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await RPS();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 NPS=60*1e3,FPS=1152921504606847e3,QPS=["is_not"],MRn=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)}},RHs=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||_xp,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=bxp(c,n,this.cohorts,this.debugMode):s=yxp(c,n,o),!s)return!1}if(a==null)return!0}return!(a!=null&&await kWp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await kWp(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(NPS,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 MRn(`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 MRn(`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 MRn(`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 MRn&&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=jIo(()=>{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=jIo(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function kWp(e,t,r=""){let i=await zPS(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/FPS}function yxp(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&&!QPS.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 exp(String(n))&&String(o).match(String(n))!==null;case"not_regex":return exp(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=UPS(String(n));if(s==null&&(s=txp(n)),s==null)throw new g1(`Invalid date: ${n}`);let u=txp(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new g1(`Unknown operator: ${a}`)}}function bxp(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 vxp(a,t,r,i)}function vxp(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=vxp(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=bxp(c,t,r,i):f=yxp(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 exp(e){try{return new RegExp(e),!0}catch{return!1}}function txp(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 UPS(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 zHs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},LPS=100,rxp=30*1e3,VPS=50*1e3,NHs=class extends qHs{constructor(t,r={}){if(super(t,r),this._memoryStorage=new zHs,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,LPS):rxp,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 RHs({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 DRn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||VPS}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):_xp(t,r)}getLibraryVersion(){return bPS}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=rxp){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=UHs(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");DRn.captureException(this,t,{syntheticException:n},r,i)}},ixp=/\(error: (.*)\)/,gxp=50,Oxp="?";function WPS(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||Oxp,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:nxp(n[3]),colno:nxp(n[4]),in_app:xPS(u||"",l),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function xPS(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 nxp(e){return parseInt(e||"",10)||void 0}function GPS(e){return[90,WPS(e)]}function HPS(e){let r=[GPS(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],o=i.split(`
|
|
1163
|
-
`);for(let c=n;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let s=ixp.test(f)?f.replace(ixp,"$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>=gxp)break}}return JPS(a)}}function JPS(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,gxp).map(r=>({...r,filename:r.filename||KPS(t).filename,function:r.function||Oxp}))}function KPS(e){return e[e.length-1]||{}}DRn.stackParser=HPS(nPS());DRn.frameModifiers=[uPS];var IRn=class extends NHs{getLibraryId(){return"posthog-node"}};var EIo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new IRn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"1.9.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var QOa=class{async sendEvent(){}async identify(){}async flush(){}};var qRn=require("fs/promises"),jxp=require("os"),wxp=require("path");var Axp=re(require("crypto")),MIo=new Uint8Array(256),SIo=MIo.length;function LHs(){return SIo>MIo.length-16&&(Axp.default.randomFillSync(MIo),SIo=0),MIo.slice(SIo,SIo+=16)}var UQ=[];for(let e=0;e<256;++e)UQ.push((e+256).toString(16).slice(1));function mxp(e,t=0){return UQ[e[t+0]]+UQ[e[t+1]]+UQ[e[t+2]]+UQ[e[t+3]]+"-"+UQ[e[t+4]]+UQ[e[t+5]]+"-"+UQ[e[t+6]]+UQ[e[t+7]]+"-"+UQ[e[t+8]]+UQ[e[t+9]]+"-"+UQ[e[t+10]]+UQ[e[t+11]]+UQ[e[t+12]]+UQ[e[t+13]]+UQ[e[t+14]]+UQ[e[t+15]]}var Pxp=re(require("crypto")),VHs={randomUUID:Pxp.default.randomUUID};function $PS(e,t,r){if(VHs.randomUUID&&!t&&!e)return VHs.randomUUID();e=e||{};let i=e.random||(e.rng||LHs)();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 mxp(i)}var rhe=$PS;var YPS="id",XPS=".fern",UOa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new IRn(r),this.userId=t==null?void 0:cWs(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:"1.9.0",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ut(Ur.of((0,jxp.homedir)()),et.of(XPS),et.of(YPS));await Fi(t)||(await(0,qRn.mkdir)((0,wxp.dirname)(t),{recursive:!0}),await(0,qRn.writeFile)(t,rhe())),this.persistedDistinctId=(await(0,qRn.readFile)(t)).toString()}return this.persistedDistinctId}};var WHs;async function TRn(){return WHs==null&&(WHs=await ZPS()),WHs}async function ZPS(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new QOa;let r=await Gjo();return r!=null?new UOa({token:r,posthogApiKey:e}):await N1n()!=null?new EIo({posthogApiKey:e}):new UOa({token:void 0,posthogApiKey:e})}catch{return new QOa}}function LOa(e,t){return function(){return e.apply(t,arguments)}}var{toString:kPS}=Object.prototype,{getPrototypeOf:GHs}=Object,{iterator:BIo,toStringTag:Sxp}=Symbol,IIo=(e=>t=>{let r=kPS.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),VNt=e=>(e=e.toLowerCase(),t=>IIo(t)===e),CIo=e=>t=>typeof t===e,{isArray:zRn}=Array,RRn=CIo("undefined");function VOa(e){return e!==null&&!RRn(e)&&e.constructor!==null&&!RRn(e.constructor)&&CH(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Mxp=VNt("ArrayBuffer");function ejS(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Mxp(e.buffer),t}var tjS=CIo("string"),CH=CIo("function"),Dxp=CIo("number"),WOa=e=>e!==null&&typeof e=="object",rjS=e=>e===!0||e===!1,DIo=e=>{if(IIo(e)!=="object")return!1;let t=GHs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Sxp in e)&&!(BIo in e)},ijS=e=>{if(!WOa(e)||VOa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},njS=VNt("Date"),ajS=VNt("File"),ojS=VNt("Blob"),ujS=VNt("FileList"),sjS=e=>WOa(e)&&CH(e.pipe),cjS=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||CH(e.append)&&((t=IIo(e))==="formdata"||t==="object"&&CH(e.toString)&&e.toString()==="[object FormData]"))},ljS=VNt("URLSearchParams"),[fjS,djS,pjS,_jS]=["ReadableStream","Request","Response","Headers"].map(VNt),hjS=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function xOa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),zRn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(VOa(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 Bxp(e,t){if(VOa(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 hHi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ixp=e=>!RRn(e)&&e!==hHi;function xHs(){let{caseless:e,skipUndefined:t}=Ixp(this)&&this||{},r={},i=(n,a)=>{let o=e&&Bxp(r,a)||a;DIo(r[o])&&DIo(n)?r[o]=xHs(r[o],n):DIo(n)?r[o]=xHs({},n):zRn(n)?r[o]=n.slice():(!t||!RRn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&xOa(arguments[n],i);return r}var yjS=(e,t,r,{allOwnKeys:i}={})=>(xOa(t,(n,a)=>{r&&CH(n)?e[a]=LOa(n,r):e[a]=n},{allOwnKeys:i}),e),bjS=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),vjS=(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)},gjS=(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&&GHs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},OjS=(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},AjS=e=>{if(!e)return null;if(zRn(e))return e;let t=e.length;if(!Dxp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},mjS=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&GHs(Uint8Array)),PjS=(e,t)=>{let i=(e&&e[BIo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},jjS=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},wjS=VNt("HTMLFormElement"),EjS=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),Exp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),SjS=VNt("RegExp"),Cxp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};xOa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},MjS=e=>{Cxp(e,(t,r)=>{if(CH(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(CH(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+"'")})}})},DjS=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return zRn(e)?i(e):i(String(e).split(t)),r},BjS=()=>{},IjS=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function CjS(e){return!!(e&&CH(e.append)&&e[Sxp]==="FormData"&&e[BIo])}var qjS=e=>{let t=new Array(10),r=(i,n)=>{if(WOa(i)){if(t.indexOf(i)>=0)return;if(VOa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=zRn(i)?[]:{};return xOa(i,(o,c)=>{let f=r(o,n+1);!RRn(f)&&(a[c]=f)}),t[n]=void 0,a}}return i};return r(e,0)},TjS=VNt("AsyncFunction"),RjS=e=>e&&(WOa(e)||CH(e))&&CH(e.then)&&CH(e.catch),qxp=((e,t)=>e?setImmediate:t?((r,i)=>(hHi.addEventListener("message",({source:n,data:a})=>{n===hHi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),hHi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",CH(hHi.postMessage)),zjS=typeof queueMicrotask<"u"?queueMicrotask.bind(hHi):typeof process<"u"&&process.nextTick||qxp,NjS=e=>e!=null&&CH(e[BIo]),er={isArray:zRn,isArrayBuffer:Mxp,isBuffer:VOa,isFormData:cjS,isArrayBufferView:ejS,isString:tjS,isNumber:Dxp,isBoolean:rjS,isObject:WOa,isPlainObject:DIo,isEmptyObject:ijS,isReadableStream:fjS,isRequest:djS,isResponse:pjS,isHeaders:_jS,isUndefined:RRn,isDate:njS,isFile:ajS,isBlob:ojS,isRegExp:SjS,isFunction:CH,isStream:sjS,isURLSearchParams:ljS,isTypedArray:mjS,isFileList:ujS,forEach:xOa,merge:xHs,extend:yjS,trim:hjS,stripBOM:bjS,inherits:vjS,toFlatObject:gjS,kindOf:IIo,kindOfTest:VNt,endsWith:OjS,toArray:AjS,forEachEntry:PjS,matchAll:jjS,isHTMLForm:wjS,hasOwnProperty:Exp,hasOwnProp:Exp,reduceDescriptors:Cxp,freezeMethods:MjS,toObjectSet:DjS,toCamelCase:EjS,noop:BjS,toFiniteNumber:IjS,findKey:Bxp,global:hHi,isContextDefined:Ixp,isSpecCompliantForm:CjS,toJSONObject:qjS,isAsyncFn:TjS,isThenable:RjS,setImmediate:qxp,asap:zjS,isIterable:NjS};function NRn(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)}er.inherits(NRn,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:er.toJSONObject(this.config),code:this.code,status:this.status}}});var Txp=NRn.prototype,Rxp={};["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=>{Rxp[e]={value:e}});Object.defineProperties(NRn,Rxp);Object.defineProperty(Txp,"isAxiosError",{value:!0});NRn.from=(e,t,r,i,n,a)=>{let o=Object.create(Txp);er.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 NRn.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 va=NRn;var zxp=re(e7i(),1),qIo=zxp.default;function HHs(e){return er.isPlainObject(e)||er.isArray(e)}function Fxp(e){return er.endsWith(e,"[]")?e.slice(0,-2):e}function Nxp(e,t,r){return e?e.concat(t).map(function(n,a){return n=Fxp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function FjS(e){return er.isArray(e)&&!e.some(HHs)}var QjS=er.toFlatObject(er,{},null,function(t){return/^is[A-Z]/.test(t)});function UjS(e,t,r){if(!er.isObject(e))throw new TypeError("target must be an object");t=t||new(qIo||FormData),r=er.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!er.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&er.isSpecCompliantForm(t);if(!er.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(er.isDate(h))return h.toISOString();if(er.isBoolean(h))return h.toString();if(!f&&er.isBlob(h))throw new va("Blob is not supported. Use a Buffer instead.");return er.isArrayBuffer(h)||er.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(er.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(er.isArray(h)&&FjS(h)||(er.isFileList(h)||er.endsWith(y,"[]"))&&(v=er.toArray(h)))return y=Fxp(y),v.forEach(function(A,g){!(er.isUndefined(A)||A===null)&&t.append(o===!0?Nxp([y],g,a):o===null?y:y+"[]",s(A))}),!1}return HHs(h)?!0:(t.append(Nxp(b,y,a),s(h)),!1)}let l=[],p=Object.assign(QjS,{defaultVisitor:u,convertValue:s,isVisitable:HHs});function _(h,y){if(!er.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),er.forEach(h,function(v,O){(!(er.isUndefined(v)||v===null)&&n.call(t,v,er.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),l.pop()}}if(!er.isObject(e))throw new TypeError("data must be an object");return _(e),t}var uIi=UjS;function Qxp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Uxp(e,t){this._pairs=[],e&&uIi(e,this,t)}var Lxp=Uxp.prototype;Lxp.append=function(t,r){this._pairs.push([t,r])};Lxp.toString=function(t){let r=t?function(i){return t.call(this,i,Qxp)}:Qxp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Vxp=Uxp;function LjS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function yHi(e,t,r){if(!t)return e;let i=r&&r.encode||LjS;er.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=er.isURLSearchParams(t)?t.toString():new Vxp(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var JHs=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){er.forEach(this.handlers,function(i){i!==null&&t(i)})}},KHs=JHs;var FRn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Hxp=re(require("crypto"),1);var Wxp=re(require("url"),1),xxp=Wxp.default.URLSearchParams;var $Hs="abcdefghijklmnopqrstuvwxyz",Gxp="0123456789",Jxp={DIGIT:Gxp,ALPHA:$Hs,ALPHA_DIGIT:$Hs+$Hs.toUpperCase()+Gxp},VjS=(e=16,t=Jxp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);Hxp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},Kxp={isNode:!0,classes:{URLSearchParams:xxp,FormData:qIo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Jxp,generateString:VjS,protocols:["http","https","file","data"]};var ZHs={};Kt(ZHs,{hasBrowserEnv:()=>XHs,hasStandardBrowserEnv:()=>WjS,hasStandardBrowserWebWorkerEnv:()=>xjS,navigator:()=>YHs,origin:()=>GjS});var XHs=typeof window<"u"&&typeof document<"u",YHs=typeof navigator=="object"&&navigator||void 0,WjS=XHs&&(!YHs||["ReactNative","NativeScript","NS"].indexOf(YHs.product)<0),xjS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",GjS=XHs&&window.location.href||"http://localhost";var EA={...ZHs,...Kxp};function kHs(e,t){return uIi(e,new EA.classes.URLSearchParams,{visitor:function(r,i,n,a){return EA.isNode&&er.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function HjS(e){return er.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function JjS(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 KjS(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&&er.isArray(n)?n.length:o,f?(er.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!er.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&er.isArray(n[o])&&(n[o]=JjS(n[o])),!c)}if(er.isFormData(e)&&er.isFunction(e.entries)){let r={};return er.forEachEntry(e,(i,n)=>{t(HjS(i),n,r,0)}),r}return null}var TIo=KjS;function $jS(e,t,r){if(er.isString(e))try{return(t||JSON.parse)(e),er.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var eJs={transitional:FRn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=er.isObject(t);if(a&&er.isHTMLForm(t)&&(t=new FormData(t)),er.isFormData(t))return n?JSON.stringify(TIo(t)):t;if(er.isArrayBuffer(t)||er.isBuffer(t)||er.isStream(t)||er.isFile(t)||er.isBlob(t)||er.isReadableStream(t))return t;if(er.isArrayBufferView(t))return t.buffer;if(er.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 kHs(t,this.formSerializer).toString();if((c=er.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return uIi(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),$jS(t)):t}],transformResponse:[function(t){let r=this.transitional||eJs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(er.isResponse(t)||er.isReadableStream(t))return t;if(t&&er.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"?va.from(c,va.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:EA.classes.FormData,Blob:EA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};er.forEach(["delete","get","head","post","put","patch"],e=>{eJs.headers[e]={}});var QRn=eJs;var YjS=er.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"]),$xp=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1163
|
+
`);for(let c=n;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let s=ixp.test(f)?f.replace(ixp,"$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>=gxp)break}}return JPS(a)}}function JPS(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,gxp).map(r=>({...r,filename:r.filename||KPS(t).filename,function:r.function||Oxp}))}function KPS(e){return e[e.length-1]||{}}DRn.stackParser=HPS(nPS());DRn.frameModifiers=[uPS];var IRn=class extends NHs{getLibraryId(){return"posthog-node"}};var EIo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new IRn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"1.9.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var QOa=class{async sendEvent(){}async identify(){}async flush(){}};var qRn=require("fs/promises"),jxp=require("os"),wxp=require("path");var Axp=re(require("crypto")),MIo=new Uint8Array(256),SIo=MIo.length;function LHs(){return SIo>MIo.length-16&&(Axp.default.randomFillSync(MIo),SIo=0),MIo.slice(SIo,SIo+=16)}var UQ=[];for(let e=0;e<256;++e)UQ.push((e+256).toString(16).slice(1));function mxp(e,t=0){return UQ[e[t+0]]+UQ[e[t+1]]+UQ[e[t+2]]+UQ[e[t+3]]+"-"+UQ[e[t+4]]+UQ[e[t+5]]+"-"+UQ[e[t+6]]+UQ[e[t+7]]+"-"+UQ[e[t+8]]+UQ[e[t+9]]+"-"+UQ[e[t+10]]+UQ[e[t+11]]+UQ[e[t+12]]+UQ[e[t+13]]+UQ[e[t+14]]+UQ[e[t+15]]}var Pxp=re(require("crypto")),VHs={randomUUID:Pxp.default.randomUUID};function $PS(e,t,r){if(VHs.randomUUID&&!t&&!e)return VHs.randomUUID();e=e||{};let i=e.random||(e.rng||LHs)();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 mxp(i)}var rhe=$PS;var YPS="id",XPS=".fern",UOa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new IRn(r),this.userId=t==null?void 0:cWs(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:"1.9.1",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ut(Ur.of((0,jxp.homedir)()),et.of(XPS),et.of(YPS));await Fi(t)||(await(0,qRn.mkdir)((0,wxp.dirname)(t),{recursive:!0}),await(0,qRn.writeFile)(t,rhe())),this.persistedDistinctId=(await(0,qRn.readFile)(t)).toString()}return this.persistedDistinctId}};var WHs;async function TRn(){return WHs==null&&(WHs=await ZPS()),WHs}async function ZPS(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new QOa;let r=await Gjo();return r!=null?new UOa({token:r,posthogApiKey:e}):await N1n()!=null?new EIo({posthogApiKey:e}):new UOa({token:void 0,posthogApiKey:e})}catch{return new QOa}}function LOa(e,t){return function(){return e.apply(t,arguments)}}var{toString:kPS}=Object.prototype,{getPrototypeOf:GHs}=Object,{iterator:BIo,toStringTag:Sxp}=Symbol,IIo=(e=>t=>{let r=kPS.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),VNt=e=>(e=e.toLowerCase(),t=>IIo(t)===e),CIo=e=>t=>typeof t===e,{isArray:zRn}=Array,RRn=CIo("undefined");function VOa(e){return e!==null&&!RRn(e)&&e.constructor!==null&&!RRn(e.constructor)&&CH(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Mxp=VNt("ArrayBuffer");function ejS(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Mxp(e.buffer),t}var tjS=CIo("string"),CH=CIo("function"),Dxp=CIo("number"),WOa=e=>e!==null&&typeof e=="object",rjS=e=>e===!0||e===!1,DIo=e=>{if(IIo(e)!=="object")return!1;let t=GHs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Sxp in e)&&!(BIo in e)},ijS=e=>{if(!WOa(e)||VOa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},njS=VNt("Date"),ajS=VNt("File"),ojS=VNt("Blob"),ujS=VNt("FileList"),sjS=e=>WOa(e)&&CH(e.pipe),cjS=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||CH(e.append)&&((t=IIo(e))==="formdata"||t==="object"&&CH(e.toString)&&e.toString()==="[object FormData]"))},ljS=VNt("URLSearchParams"),[fjS,djS,pjS,_jS]=["ReadableStream","Request","Response","Headers"].map(VNt),hjS=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function xOa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),zRn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(VOa(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 Bxp(e,t){if(VOa(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 hHi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ixp=e=>!RRn(e)&&e!==hHi;function xHs(){let{caseless:e,skipUndefined:t}=Ixp(this)&&this||{},r={},i=(n,a)=>{let o=e&&Bxp(r,a)||a;DIo(r[o])&&DIo(n)?r[o]=xHs(r[o],n):DIo(n)?r[o]=xHs({},n):zRn(n)?r[o]=n.slice():(!t||!RRn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&xOa(arguments[n],i);return r}var yjS=(e,t,r,{allOwnKeys:i}={})=>(xOa(t,(n,a)=>{r&&CH(n)?e[a]=LOa(n,r):e[a]=n},{allOwnKeys:i}),e),bjS=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),vjS=(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)},gjS=(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&&GHs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},OjS=(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},AjS=e=>{if(!e)return null;if(zRn(e))return e;let t=e.length;if(!Dxp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},mjS=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&GHs(Uint8Array)),PjS=(e,t)=>{let i=(e&&e[BIo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},jjS=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},wjS=VNt("HTMLFormElement"),EjS=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),Exp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),SjS=VNt("RegExp"),Cxp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};xOa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},MjS=e=>{Cxp(e,(t,r)=>{if(CH(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(CH(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+"'")})}})},DjS=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return zRn(e)?i(e):i(String(e).split(t)),r},BjS=()=>{},IjS=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function CjS(e){return!!(e&&CH(e.append)&&e[Sxp]==="FormData"&&e[BIo])}var qjS=e=>{let t=new Array(10),r=(i,n)=>{if(WOa(i)){if(t.indexOf(i)>=0)return;if(VOa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=zRn(i)?[]:{};return xOa(i,(o,c)=>{let f=r(o,n+1);!RRn(f)&&(a[c]=f)}),t[n]=void 0,a}}return i};return r(e,0)},TjS=VNt("AsyncFunction"),RjS=e=>e&&(WOa(e)||CH(e))&&CH(e.then)&&CH(e.catch),qxp=((e,t)=>e?setImmediate:t?((r,i)=>(hHi.addEventListener("message",({source:n,data:a})=>{n===hHi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),hHi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",CH(hHi.postMessage)),zjS=typeof queueMicrotask<"u"?queueMicrotask.bind(hHi):typeof process<"u"&&process.nextTick||qxp,NjS=e=>e!=null&&CH(e[BIo]),er={isArray:zRn,isArrayBuffer:Mxp,isBuffer:VOa,isFormData:cjS,isArrayBufferView:ejS,isString:tjS,isNumber:Dxp,isBoolean:rjS,isObject:WOa,isPlainObject:DIo,isEmptyObject:ijS,isReadableStream:fjS,isRequest:djS,isResponse:pjS,isHeaders:_jS,isUndefined:RRn,isDate:njS,isFile:ajS,isBlob:ojS,isRegExp:SjS,isFunction:CH,isStream:sjS,isURLSearchParams:ljS,isTypedArray:mjS,isFileList:ujS,forEach:xOa,merge:xHs,extend:yjS,trim:hjS,stripBOM:bjS,inherits:vjS,toFlatObject:gjS,kindOf:IIo,kindOfTest:VNt,endsWith:OjS,toArray:AjS,forEachEntry:PjS,matchAll:jjS,isHTMLForm:wjS,hasOwnProperty:Exp,hasOwnProp:Exp,reduceDescriptors:Cxp,freezeMethods:MjS,toObjectSet:DjS,toCamelCase:EjS,noop:BjS,toFiniteNumber:IjS,findKey:Bxp,global:hHi,isContextDefined:Ixp,isSpecCompliantForm:CjS,toJSONObject:qjS,isAsyncFn:TjS,isThenable:RjS,setImmediate:qxp,asap:zjS,isIterable:NjS};function NRn(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)}er.inherits(NRn,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:er.toJSONObject(this.config),code:this.code,status:this.status}}});var Txp=NRn.prototype,Rxp={};["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=>{Rxp[e]={value:e}});Object.defineProperties(NRn,Rxp);Object.defineProperty(Txp,"isAxiosError",{value:!0});NRn.from=(e,t,r,i,n,a)=>{let o=Object.create(Txp);er.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 NRn.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 va=NRn;var zxp=re(e7i(),1),qIo=zxp.default;function HHs(e){return er.isPlainObject(e)||er.isArray(e)}function Fxp(e){return er.endsWith(e,"[]")?e.slice(0,-2):e}function Nxp(e,t,r){return e?e.concat(t).map(function(n,a){return n=Fxp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function FjS(e){return er.isArray(e)&&!e.some(HHs)}var QjS=er.toFlatObject(er,{},null,function(t){return/^is[A-Z]/.test(t)});function UjS(e,t,r){if(!er.isObject(e))throw new TypeError("target must be an object");t=t||new(qIo||FormData),r=er.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!er.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&er.isSpecCompliantForm(t);if(!er.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(er.isDate(h))return h.toISOString();if(er.isBoolean(h))return h.toString();if(!f&&er.isBlob(h))throw new va("Blob is not supported. Use a Buffer instead.");return er.isArrayBuffer(h)||er.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(er.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(er.isArray(h)&&FjS(h)||(er.isFileList(h)||er.endsWith(y,"[]"))&&(v=er.toArray(h)))return y=Fxp(y),v.forEach(function(A,g){!(er.isUndefined(A)||A===null)&&t.append(o===!0?Nxp([y],g,a):o===null?y:y+"[]",s(A))}),!1}return HHs(h)?!0:(t.append(Nxp(b,y,a),s(h)),!1)}let l=[],p=Object.assign(QjS,{defaultVisitor:u,convertValue:s,isVisitable:HHs});function _(h,y){if(!er.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),er.forEach(h,function(v,O){(!(er.isUndefined(v)||v===null)&&n.call(t,v,er.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),l.pop()}}if(!er.isObject(e))throw new TypeError("data must be an object");return _(e),t}var uIi=UjS;function Qxp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Uxp(e,t){this._pairs=[],e&&uIi(e,this,t)}var Lxp=Uxp.prototype;Lxp.append=function(t,r){this._pairs.push([t,r])};Lxp.toString=function(t){let r=t?function(i){return t.call(this,i,Qxp)}:Qxp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Vxp=Uxp;function LjS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function yHi(e,t,r){if(!t)return e;let i=r&&r.encode||LjS;er.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=er.isURLSearchParams(t)?t.toString():new Vxp(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var JHs=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){er.forEach(this.handlers,function(i){i!==null&&t(i)})}},KHs=JHs;var FRn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Hxp=re(require("crypto"),1);var Wxp=re(require("url"),1),xxp=Wxp.default.URLSearchParams;var $Hs="abcdefghijklmnopqrstuvwxyz",Gxp="0123456789",Jxp={DIGIT:Gxp,ALPHA:$Hs,ALPHA_DIGIT:$Hs+$Hs.toUpperCase()+Gxp},VjS=(e=16,t=Jxp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);Hxp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},Kxp={isNode:!0,classes:{URLSearchParams:xxp,FormData:qIo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Jxp,generateString:VjS,protocols:["http","https","file","data"]};var ZHs={};Kt(ZHs,{hasBrowserEnv:()=>XHs,hasStandardBrowserEnv:()=>WjS,hasStandardBrowserWebWorkerEnv:()=>xjS,navigator:()=>YHs,origin:()=>GjS});var XHs=typeof window<"u"&&typeof document<"u",YHs=typeof navigator=="object"&&navigator||void 0,WjS=XHs&&(!YHs||["ReactNative","NativeScript","NS"].indexOf(YHs.product)<0),xjS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",GjS=XHs&&window.location.href||"http://localhost";var EA={...ZHs,...Kxp};function kHs(e,t){return uIi(e,new EA.classes.URLSearchParams,{visitor:function(r,i,n,a){return EA.isNode&&er.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function HjS(e){return er.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function JjS(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 KjS(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&&er.isArray(n)?n.length:o,f?(er.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!er.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&er.isArray(n[o])&&(n[o]=JjS(n[o])),!c)}if(er.isFormData(e)&&er.isFunction(e.entries)){let r={};return er.forEachEntry(e,(i,n)=>{t(HjS(i),n,r,0)}),r}return null}var TIo=KjS;function $jS(e,t,r){if(er.isString(e))try{return(t||JSON.parse)(e),er.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var eJs={transitional:FRn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=er.isObject(t);if(a&&er.isHTMLForm(t)&&(t=new FormData(t)),er.isFormData(t))return n?JSON.stringify(TIo(t)):t;if(er.isArrayBuffer(t)||er.isBuffer(t)||er.isStream(t)||er.isFile(t)||er.isBlob(t)||er.isReadableStream(t))return t;if(er.isArrayBufferView(t))return t.buffer;if(er.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 kHs(t,this.formSerializer).toString();if((c=er.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return uIi(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),$jS(t)):t}],transformResponse:[function(t){let r=this.transitional||eJs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(er.isResponse(t)||er.isReadableStream(t))return t;if(t&&er.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"?va.from(c,va.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:EA.classes.FormData,Blob:EA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};er.forEach(["delete","get","head","post","put","patch"],e=>{eJs.headers[e]={}});var QRn=eJs;var YjS=er.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"]),$xp=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1164
1164
|
`).forEach(function(o){n=o.indexOf(":"),r=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim(),!(!r||t[r]&&YjS[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var Yxp=Symbol("internals");function GOa(e){return e&&String(e).trim().toLowerCase()}function RIo(e){return e===!1||e==null?e:er.isArray(e)?e.map(RIo):String(e)}function XjS(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 ZjS=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function tJs(e,t,r,i,n){if(er.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!er.isString(t)){if(er.isString(i))return t.indexOf(i)!==-1;if(er.isRegExp(i))return i.test(t)}}function kjS(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function ewS(e,t){let r=er.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 URn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,f,s){let u=GOa(f);if(!u)throw new Error("header name must be a non-empty string");let l=er.findKey(n,u);(!l||n[l]===void 0||s===!0||s===void 0&&n[l]!==!1)&&(n[l||f]=RIo(c))}let o=(c,f)=>er.forEach(c,(s,u)=>a(s,u,f));if(er.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(er.isString(t)&&(t=t.trim())&&!ZjS(t))o($xp(t),r);else if(er.isObject(t)&&er.isIterable(t)){let c={},f,s;for(let u of t){if(!er.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(f=c[s])?er.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=GOa(t),t){let i=er.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return XjS(n);if(er.isFunction(r))return r.call(this,n,i);if(er.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=GOa(t),t){let i=er.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||tJs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(o){if(o=GOa(o),o){let c=er.findKey(i,o);c&&(!r||tJs(i,i[c],c,r))&&(delete i[c],n=!0)}}return er.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||tJs(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return er.forEach(this,(n,a)=>{let o=er.findKey(i,a);if(o){r[o]=RIo(n),delete r[a];return}let c=t?kjS(a):String(a).trim();c!==a&&delete r[a],r[c]=RIo(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return er.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&er.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(`
|
|
1165
1165
|
`)}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[Yxp]=this[Yxp]={accessors:{}}).accessors,n=this.prototype;function a(o){let c=GOa(o);i[c]||(ewS(n,o),i[c]=!0)}return er.isArray(t)?t.forEach(a):a(t),this}};URn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);er.reduceDescriptors(URn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});er.freezeMethods(URn);var US=URn;function HOa(e,t){let r=this||QRn,i=t||r,n=US.from(i.headers),a=i.data;return er.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function JOa(e){return!!(e&&e.__CANCEL__)}function Xxp(e,t,r){va.call(this,e??"canceled",va.ERR_CANCELED,t,r),this.name="CanceledError"}er.inherits(Xxp,va,{__CANCEL__:!0});var ihe=Xxp;function A9t(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new va("Request failed with status code "+r.status,[va.ERR_BAD_REQUEST,va.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function rJs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function iJs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function bHi(e,t,r){let i=!rJs(t);return e&&(i||r==!1)?iJs(e,t):t}var p6p=re(rIo(),1),_6p=re(require("http"),1),h6p=re(require("https"),1),y6p=re(require("util"),1),b6p=re(nHs(),1),Zbi=re(require("zlib"),1);var vHi="1.12.2";function KOa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var twS=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function nJs(e,t,r){let i=r&&r.Blob||EA.classes.Blob,n=KOa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=twS.exec(e);if(!a)throw new va("Invalid URL",va.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 va("Blob is not supported",va.ERR_NOT_SUPPORT);return new i([s],{type:o})}return s}throw new va("Unsupported protocol "+n,va.ERR_NOT_SUPPORT)}var OHi=re(require("stream"),1);var Zxp=re(require("stream"),1);var aJs=Symbol("internals"),oJs=class extends Zxp.default.Transform{constructor(t){t=er.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!er.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[aJs]={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[aJs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[aJs],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)})}},uJs=oJs;var v6p=require("events");var e6p=re(require("util"),1),t6p=require("stream");var{asyncIterator:kxp}=Symbol,rwS=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[kxp]?yield*e[kxp]():yield e},zIo=rwS;var iwS=EA.ALPHABET.ALPHA_DIGIT+"-_",$Oa=typeof TextEncoder=="function"?new TextEncoder:new e6p.default.TextEncoder,gHi=`\r
|
|
1166
1166
|
`,nwS=$Oa.encode(gHi),awS=2,sJs=class{constructor(t,r){let{escapeName:i}=this.constructor,n=er.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${gHi}`;n?r=$Oa.encode(String(r).replace(/\r?\n|\r\n?/g,gHi)):a+=`Content-Type: ${r.type||"application/octet-stream"}${gHi}`,this.headers=$Oa.encode(a+gHi),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+awS,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;er.isTypedArray(t)?yield t:yield*zIo(t),yield nwS}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},owS=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+EA.generateString(n,iwS)}=r||{};if(!er.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=$Oa.encode("--"+a+gHi),c=$Oa.encode("--"+a+"--"+gHi),f=c.byteLength,s=Array.from(e.entries()).map(([l,p])=>{let _=new sJs(l,p);return f+=_.size,_});f+=o.byteLength*s.length,f=er.toFiniteNumber(f);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(f)&&(u["Content-Length"]=f),t&&t(u),t6p.Readable.from((async function*(){for(let l of s)yield o,yield*l.encode();yield c})())},r6p=owS;var i6p=re(require("stream"),1),cJs=class extends i6p.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)}},n6p=cJs;var uwS=(e,t)=>er.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,a6p=uwS;function swS(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 o6p=swS;function cwS(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 u6p=cwS;var Xbi=(e,t,r=3)=>{let i=0,n=o6p(50,250);return u6p(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)},LRn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},VRn=e=>(...t)=>er.asap(()=>e(...t));function lJs(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 s6p={flush:Zbi.default.constants.Z_SYNC_FLUSH,finishFlush:Zbi.default.constants.Z_SYNC_FLUSH},lwS={flush:Zbi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:Zbi.default.constants.BROTLI_OPERATION_FLUSH},c6p=er.isFunction(Zbi.default.createBrotliDecompress),{http:fwS,https:dwS}=b6p.default,pwS=/https:?/,l6p=EA.protocols.map(e=>e+":"),f6p=(e,[t,r])=>(e.on("end",r).on("error",r),t);function _wS(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function g6p(e,t,r){let i=t;if(!i&&i!==!1){let n=p6p.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){g6p(a,t,a.href)}}var hwS=typeof process<"u"&&er.kindOf(process)==="process",ywS=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)}),bwS=({address:e,family:t})=>{if(!er.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},d6p=(e,t)=>bwS(er.isObject(e)?e:{address:e,family:t}),O6p=hwS&&function(t){return ywS(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=a6p(c,ae=>er.isArray(ae)?ae:[ae]);c=(ae,oe,G)=>{H(ae,oe,(V,Ce,se)=>{if(V)return G(V);let Ie=er.isArray(Ce)?Ce.map(Qe=>d6p(Qe)):[d6p(Ce,se)];oe.all?G(V,Ie):G(V,Ie[0].address,Ie[0].family)})}}let y=new v6p.EventEmitter,b=()=>{t.cancelToken&&t.cancelToken.unsubscribe(v),t.signal&&t.signal.removeEventListener("abort",v),y.removeAllListeners()};a((H,ae)=>{p=!0,ae&&(_=!0,b())});function v(H){y.emit("abort",!H||H.type?new ihe(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=bHi(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(O,EA.hasBrowserEnv?EA.origin:void 0),g=A.protocol||l6p[0];if(g==="data:"){if(t.maxContentLength>-1){let ae=String(t.url||O||"");if(lJs(ae)>t.maxContentLength)return n(new va("maxContentLength size of "+t.maxContentLength+" exceeded",va.ERR_BAD_RESPONSE,t))}let H;if(l!=="GET")return A9t(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{H=nJs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(ae){throw va.from(ae,va.ERR_BAD_REQUEST,t)}return s==="text"?(H=H.toString(u),(!u||u==="utf8")&&(H=er.stripBOM(H))):s==="stream"&&(H=OHi.default.Readable.from(H)),A9t(i,n,{data:H,status:200,statusText:"OK",headers:new US,config:t})}if(l6p.indexOf(g)===-1)return n(new va("Unsupported protocol "+g,va.ERR_BAD_REQUEST,t));let m=US.from(t.headers).normalize();m.set("User-Agent","axios/"+vHi,!1);let{onUploadProgress:w,onDownloadProgress:D}=t,E=t.maxRate,S,B;if(er.isSpecCompliantForm(o)){let H=m.getContentType(/boundary=([-_\w\d]{10,70})/i);o=r6p(o,ae=>{m.set(ae)},{tag:`axios-${vHi}-boundary`,boundary:H&&H[1]||void 0})}else if(er.isFormData(o)&&er.isFunction(o.getHeaders)){if(m.set(o.getHeaders()),!m.hasContentLength())try{let H=await y6p.default.promisify(o.getLength).call(o);Number.isFinite(H)&&H>=0&&m.setContentLength(H)}catch{}}else if(er.isBlob(o)||er.isFile(o))o.size&&m.setContentType(o.type||"application/octet-stream"),m.setContentLength(o.size||0),o=OHi.default.Readable.from(zIo(o));else if(o&&!er.isStream(o)){if(!Buffer.isBuffer(o))if(er.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(er.isString(o))o=Buffer.from(o,"utf-8");else return n(new va("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",va.ERR_BAD_REQUEST,t));if(m.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return n(new va("Request body larger than maxBodyLength limit",va.ERR_BAD_REQUEST,t))}let F=er.toFiniteNumber(m.getContentLength());er.isArray(E)?(S=E[0],B=E[1]):S=B=E,o&&(w||S)&&(er.isStream(o)||(o=OHi.default.Readable.from(o,{objectMode:!1})),o=OHi.default.pipeline([o,new uJs({maxRate:er.toFiniteNumber(S)})],er.noop),w&&o.on("progress",f6p(o,LRn(F,Xbi(VRn(w),!1,3)))));let R;if(t.auth){let H=t.auth.username||"",ae=t.auth.password||"";R=H+":"+ae}if(!R&&A.username){let H=A.username,ae=A.password;R=H+":"+ae}R&&m.delete("authorization");let z;try{z=yHi(A.pathname+A.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(H){let ae=new Error(H.message);return ae.config=t,ae.url=t.url,ae.exists=!0,n(ae)}m.set("Accept-Encoding","gzip, compress, deflate"+(c6p?", br":""),!1);let T={path:z,method:l,headers:m.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:R,protocol:g,family:f,beforeRedirect:_wS,beforeRedirects:{}};!er.isUndefined(c)&&(T.lookup=c),t.socketPath?T.socketPath=t.socketPath:(T.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,T.port=A.port,g6p(T,t.proxy,g+"//"+A.hostname+(A.port?":"+A.port:"")+T.path));let U,L=pwS.test(T.protocol);if(T.agent=L?t.httpsAgent:t.httpAgent,t.transport?U=t.transport:t.maxRedirects===0?U=L?h6p.default:_6p.default:(t.maxRedirects&&(T.maxRedirects=t.maxRedirects),t.beforeRedirect&&(T.beforeRedirects.config=t.beforeRedirect),U=L?dwS:fwS),t.maxBodyLength>-1?T.maxBodyLength=t.maxBodyLength:T.maxBodyLength=1/0,t.insecureHTTPParser&&(T.insecureHTTPParser=t.insecureHTTPParser),h=U.request(T,function(ae){if(h.destroyed)return;let oe=[ae],G=+ae.headers["content-length"];if(D||B){let Qe=new uJs({maxRate:er.toFiniteNumber(B)});D&&Qe.on("progress",f6p(Qe,LRn(G,Xbi(VRn(D),!0,3)))),oe.push(Qe)}let V=ae,Ce=ae.req||h;if(t.decompress!==!1&&ae.headers["content-encoding"])switch((l==="HEAD"||ae.statusCode===204)&&delete ae.headers["content-encoding"],(ae.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":oe.push(Zbi.default.createUnzip(s6p)),delete ae.headers["content-encoding"];break;case"deflate":oe.push(new n6p),oe.push(Zbi.default.createUnzip(s6p)),delete ae.headers["content-encoding"];break;case"br":c6p&&(oe.push(Zbi.default.createBrotliDecompress(lwS)),delete ae.headers["content-encoding"])}V=oe.length>1?OHi.default.pipeline(oe,er.noop):oe[0];let se=OHi.default.finished(V,()=>{se(),b()}),Ie={status:ae.statusCode,statusText:ae.statusMessage,headers:new US(ae.headers),config:t,request:Ce};if(s==="stream")Ie.data=V,A9t(i,n,Ie);else{let Qe=[],ne=0;V.on("data",function(Ue){Qe.push(Ue),ne+=Ue.length,t.maxContentLength>-1&&ne>t.maxContentLength&&(_=!0,V.destroy(),n(new va("maxContentLength size of "+t.maxContentLength+" exceeded",va.ERR_BAD_RESPONSE,t,Ce)))}),V.on("aborted",function(){if(_)return;let Ue=new va("stream has been aborted",va.ERR_BAD_RESPONSE,t,Ce);V.destroy(Ue),n(Ue)}),V.on("error",function(Ue){h.destroyed||n(va.from(Ue,null,t,Ce))}),V.on("end",function(){try{let Ue=Qe.length===1?Qe[0]:Buffer.concat(Qe);s!=="arraybuffer"&&(Ue=Ue.toString(u),(!u||u==="utf8")&&(Ue=er.stripBOM(Ue))),Ie.data=Ue}catch(Ue){return n(va.from(Ue,null,t,Ie.request,Ie))}A9t(i,n,Ie)})}y.once("abort",Qe=>{V.destroyed||(V.emit("error",Qe),V.destroy())})}),y.once("abort",H=>{n(H),h.destroy(H)}),h.on("error",function(ae){n(va.from(ae,null,t,h))}),h.on("socket",function(ae){ae.setKeepAlive(!0,1e3*60)}),t.timeout){let H=parseInt(t.timeout,10);if(Number.isNaN(H)){n(new va("error trying to parse `config.timeout` to int",va.ERR_BAD_OPTION_VALUE,t,h));return}h.setTimeout(H,function(){if(p)return;let oe=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",G=t.transitional||FRn;t.timeoutErrorMessage&&(oe=t.timeoutErrorMessage),n(new va(oe,G.clarifyTimeoutError?va.ETIMEDOUT:va.ECONNABORTED,t,h)),v()})}if(er.isStream(o)){let H=!1,ae=!1;o.on("end",()=>{H=!0}),o.once("error",oe=>{ae=!0,h.destroy(oe)}),o.on("close",()=>{!H&&!ae&&v(new ihe("Request stream has been aborted",t,h))}),o.pipe(h)}else h.end(o)})};var A6p=EA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,EA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(EA.origin),EA.navigator&&/(msie|trident)/i.test(EA.navigator.userAgent)):()=>!0;var m6p=EA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let o=[e+"="+encodeURIComponent(t)];er.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),er.isString(i)&&o.push("path="+i),er.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 P6p=e=>e instanceof US?{...e}:e;function WNt(e,t){t=t||{};let r={};function i(s,u,l,p){return er.isPlainObject(s)&&er.isPlainObject(u)?er.merge.call({caseless:p},s,u):er.isPlainObject(u)?er.merge({},u):er.isArray(u)?u.slice():u}function n(s,u,l,p){if(er.isUndefined(u)){if(!er.isUndefined(s))return i(void 0,s,l,p)}else return i(s,u,l,p)}function a(s,u){if(!er.isUndefined(u))return i(void 0,u)}function o(s,u){if(er.isUndefined(u)){if(!er.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(P6p(s),P6p(u),l,!0)};return er.forEach(Object.keys({...e,...t}),function(u){let l=f[u]||n,p=l(e[u],t[u],u);er.isUndefined(p)&&l!==c||(r[u]=p)}),r}var NIo=e=>{let t=WNt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=US.from(o),t.url=yHi(bHi(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),er.isFormData(r)){if(EA.hasStandardBrowserEnv||EA.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(er.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(EA.hasStandardBrowserEnv&&(i&&er.isFunction(i)&&(i=i(t)),i||i!==!1&&A6p(t.url))){let f=n&&a&&m6p.read(a);f&&o.set(n,f)}return t};var vwS=typeof XMLHttpRequest<"u",j6p=vwS&&function(e){return new Promise(function(r,i){let n=NIo(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};A9t(function(D){r(D),y()},function(D){i(D),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 va("Request aborted",va.ECONNABORTED,e,b)),b=null)},b.onerror=function(g){let m=g&&g.message?g.message:"Network Error",w=new va(m,va.ERR_NETWORK,e,b);w.event=g||null,i(w),b=null},b.ontimeout=function(){let g=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",m=n.transitional||FRn;n.timeoutErrorMessage&&(g=n.timeoutErrorMessage),i(new va(g,m.clarifyTimeoutError?va.ETIMEDOUT:va.ECONNABORTED,e,b)),b=null},a===void 0&&o.setContentType(null),"setRequestHeader"in b&&er.forEach(o.toJSON(),function(g,m){b.setRequestHeader(m,g)}),er.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 ihe(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=KOa(n.url);if(O&&EA.protocols.indexOf(O)===-1){i(new va("Unsupported protocol "+O+":",va.ERR_BAD_REQUEST,e));return}b.send(a||null)})};var gwS=(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 va?u:new ihe(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new va(`timeout ${t} of ms exceeded`,va.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=()=>er.asap(c),f}},w6p=gwS;var OwS=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},AwS=async function*(e,t){for await(let r of mwS(e))yield*OwS(r,t)},mwS=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()}},fJs=(e,t,r,i)=>{let n=AwS(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 E6p=64*1024,{isFunction:FIo}=er,PwS=(({Request:e,Response:t})=>({Request:e,Response:t}))(er.global),{ReadableStream:S6p,TextEncoder:M6p}=er.global,D6p=(e,...t)=>{try{return!!e(...t)}catch{return!1}},jwS=e=>{e=er.merge.call({skipUndefined:!0},PwS,e);let{fetch:t,Request:r,Response:i}=e,n=t?FIo(t):typeof fetch=="function",a=FIo(r),o=FIo(i);if(!n)return!1;let c=n&&FIo(S6p),f=n&&(typeof M6p=="function"?(h=>y=>h.encode(y))(new M6p):async h=>new Uint8Array(await new r(h).arrayBuffer())),s=a&&c&&D6p(()=>{let h=!1,y=new r(EA.origin,{body:new S6p,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!y}),u=o&&c&&D6p(()=>er.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 va(`Response type '${h}' is not supported`,va.ERR_NOT_SUPPORT,b)})});let p=async h=>{if(h==null)return 0;if(er.isBlob(h))return h.size;if(er.isSpecCompliantForm(h))return(await new r(EA.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(er.isArrayBufferView(h)||er.isArrayBuffer(h))return h.byteLength;if(er.isURLSearchParams(h)&&(h=h+""),er.isString(h))return(await f(h)).byteLength},_=async(h,y)=>{let b=er.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:w,responseType:D,headers:E,withCredentials:S="same-origin",fetchOptions:B}=NIo(h),F=t||fetch;D=D?(D+"").toLowerCase():"text";let R=w6p([O,A&&A.toAbortSignal()],g),z=null,T=R&&R.unsubscribe&&(()=>{R.unsubscribe()}),U;try{if(w&&s&&b!=="get"&&b!=="head"&&(U=await _(E,v))!==0){let V=new r(y,{method:"POST",body:v,duplex:"half"}),Ce;if(er.isFormData(v)&&(Ce=V.headers.get("content-type"))&&E.setContentType(Ce),V.body){let[se,Ie]=LRn(U,Xbi(VRn(w)));v=fJs(V.body,E6p,se,Ie)}}er.isString(S)||(S=S?"include":"omit");let L=a&&"credentials"in r.prototype,H={...B,signal:R,method:b.toUpperCase(),headers:E.normalize().toJSON(),body:v,duplex:"half",credentials:L?S:void 0};z=a&&new r(y,H);let ae=await(a?F(z,B):F(y,H)),oe=u&&(D==="stream"||D==="response");if(u&&(m||oe&&T)){let V={};["status","statusText","headers"].forEach(Qe=>{V[Qe]=ae[Qe]});let Ce=er.toFiniteNumber(ae.headers.get("content-length")),[se,Ie]=m&&LRn(Ce,Xbi(VRn(m),!0))||[];ae=new i(fJs(ae.body,E6p,se,()=>{Ie&&Ie(),T&&T()}),V)}D=D||"text";let G=await l[er.findKey(l,D)||"text"](ae,h);return!oe&&T&&T(),await new Promise((V,Ce)=>{A9t(V,Ce,{data:G,headers:US.from(ae.headers),status:ae.status,statusText:ae.statusText,config:h,request:z})})}catch(L){throw T&&T(),L&&L.name==="TypeError"&&/Load failed|fetch/i.test(L.message)?Object.assign(new va("Network Error",va.ERR_NETWORK,h,z),{cause:L.cause||L}):va.from(L,L&&L.code,h,z)}}},wwS=new Map,dJs=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=wwS;for(;c--;)f=a[c],s=u.get(f),s===void 0&&u.set(f,s=c?new Map:jwS(t)),u=s;return s},NXW=dJs();var pJs={http:O6p,xhr:j6p,fetch:{get:dJs}};er.forEach(pJs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var B6p=e=>`- ${e}`,SwS=e=>er.isFunction(e)||e===null||e===!1,QIo={getAdapter:(e,t)=>{e=er.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,!SwS(i)&&(n=pJs[(c=String(i)).toLowerCase()],n===void 0))throw new va(`Unknown adapter '${c}'`);if(n&&(er.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 :
|
|
@@ -1401,7 +1401,7 @@ ${g}${O}${m}${vQn}`});function lUo({message:e,error:t,logger:r,logLevel:i=ks.Err
|
|
|
1401
1401
|
Run ${Jt.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
1402
1402
|
Run ${Jt.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),xRn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function huc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!up_(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+=`
|
|
1403
1403
|
${await H2S(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Jt.dim(c.currentVersion)+Jt.reset(" \u2192 ")+Jt.green(c.latestVersion);return n+=`
|
|
1404
|
-
`,i?xRn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function H2S(e){let r=await new op_.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 J2S({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await cp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=WMi(u.name,l),_=await fNt({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 cp_({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=WMi(s.name,u),p=await fNt({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 cp_({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 X_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 lp_(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=YH(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 _Uo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await J2S({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(...lp_(s,f,t.logger));else o.push(...lp_(c.versions,void 0,t.logger))}return o}var HPa=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 mQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var yuc=(()=>{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})(),fp_=typeof globalThis.AbortController=="function",dp_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",pp_=typeof globalThis.ReadableStream=="function",_p_=typeof globalThis.FormData=="function",hUo=["get","post","put","patch","head","delete"],K2S=()=>{};K2S();var hp_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},yUo=2147483647,yp_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,bUo=Symbol("stop"),bp_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},vp_={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 $2S=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=yp_,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},gp_=(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))}}))},Op_=(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(gp_(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},Ap_=(e,t,r)=>{if(!e.body)return e;let i=$2S(r??e.body);return new Request(e,{duplex:"half",body:gp_(e.body,i,t)})};var PQn=e=>e!==null&&typeof e=="object";var JPa=(...e)=>{for(let t of e)if((!PQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return guc({},...e)},buc=(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 vUo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:guc(e[r]??[],t[r]??[])}var vuc=(e={},t={})=>({beforeRequest:vUo(e,t,"beforeRequest"),beforeRetry:vUo(e,t,"beforeRetry"),afterResponse:vUo(e,t,"afterResponse"),beforeError:vUo(e,t,"beforeError")}),guc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(PQn(n)){for(let[a,o]of Object.entries(n))PQn(o)&&a in t&&(o=guc(t[a],o)),t={...t,[a]:o};PQn(n.hooks)&&(i=vuc(i,n.hooks),t.hooks=i),PQn(n.headers)&&(r=buc(r,n.headers),t.headers=r)}return t};var Pp_=e=>hUo.includes(e)?e.toUpperCase():e,Y2S=["get","put","head","delete","options","trace"],X2S=[408,413,429,500,502,503,504],Z2S=[413,429,503],mp_={limit:2,methods:Y2S,statusCodes:X2S,afterStatusCodes:Z2S,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},jp_=(e={})=>{if(typeof e=="number")return{...mp_,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{...mp_,...e}};async function Ouc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new mQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function Auc(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 wp_=(e,t)=>{let r={};for(let i in t)!(i in vp_)&&!(i in bp_)&&!(i in e)&&(r[i]=t[i]);return r},Ep_=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 KPa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>yUo)throw new RangeError(`The \`timeout\` option cannot be greater than ${yUo}`);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 HPa(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(!pp_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return Op_(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(hp_))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:buc(this._input.headers,r.headers),hooks:vuc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Pp_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:jp_(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(fp_&&dp_){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(yuc&&(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),Ep_(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);(_p_&&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(!yuc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Ap_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof mQn)throw t;if(t instanceof HPa){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),yUo);if(this._retryCount<1)throw r;await Auc(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})===bUo)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=wp_(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):Ouc(this._originalRequest,t,this.abortController,this._options)}};var muc=e=>{let t=(r,i)=>KPa.create(r,JPa(e,i));for(let r of hUo)t[r]=(i,n)=>KPa.create(i,JPa(e,n,{method:r}));return t.create=r=>muc(JPa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),muc(JPa(e,r))),t.stop=bUo,t},k2S=muc(),Sp_=k2S;var Yp_=re($p_(),1);function Suc(e){let t=(0,Yp_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var x__=re(W__(),1),G__=re(ZOe(),1),Uuc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Luc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Vuc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Suc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,x__.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 Sp_(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new Uuc(e):l}if(t.allVersions)return s;let u=new Luc(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=G__.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 eja(e,t){let{version:r}=await Vuc(e.toLowerCase(),t);return r}async function BCi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:eja(e.packageName,{version:t?"prerelease":"latest"})}var H__=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],BUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ks.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new pUo(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"1.9.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Jt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new BE}failWithoutThrowing(t,r){this.didSucceed=!1,lUo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await TRn()).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 sp_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1404
|
+
`,i?xRn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function H2S(e){let r=await new op_.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 J2S({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await cp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=WMi(u.name,l),_=await fNt({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 cp_({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=WMi(s.name,u),p=await fNt({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 cp_({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 X_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 lp_(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=YH(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 _Uo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await J2S({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(...lp_(s,f,t.logger));else o.push(...lp_(c.versions,void 0,t.logger))}return o}var HPa=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 mQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var yuc=(()=>{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})(),fp_=typeof globalThis.AbortController=="function",dp_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",pp_=typeof globalThis.ReadableStream=="function",_p_=typeof globalThis.FormData=="function",hUo=["get","post","put","patch","head","delete"],K2S=()=>{};K2S();var hp_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},yUo=2147483647,yp_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,bUo=Symbol("stop"),bp_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},vp_={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 $2S=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=yp_,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},gp_=(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))}}))},Op_=(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(gp_(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},Ap_=(e,t,r)=>{if(!e.body)return e;let i=$2S(r??e.body);return new Request(e,{duplex:"half",body:gp_(e.body,i,t)})};var PQn=e=>e!==null&&typeof e=="object";var JPa=(...e)=>{for(let t of e)if((!PQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return guc({},...e)},buc=(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 vUo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:guc(e[r]??[],t[r]??[])}var vuc=(e={},t={})=>({beforeRequest:vUo(e,t,"beforeRequest"),beforeRetry:vUo(e,t,"beforeRetry"),afterResponse:vUo(e,t,"afterResponse"),beforeError:vUo(e,t,"beforeError")}),guc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(PQn(n)){for(let[a,o]of Object.entries(n))PQn(o)&&a in t&&(o=guc(t[a],o)),t={...t,[a]:o};PQn(n.hooks)&&(i=vuc(i,n.hooks),t.hooks=i),PQn(n.headers)&&(r=buc(r,n.headers),t.headers=r)}return t};var Pp_=e=>hUo.includes(e)?e.toUpperCase():e,Y2S=["get","put","head","delete","options","trace"],X2S=[408,413,429,500,502,503,504],Z2S=[413,429,503],mp_={limit:2,methods:Y2S,statusCodes:X2S,afterStatusCodes:Z2S,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},jp_=(e={})=>{if(typeof e=="number")return{...mp_,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{...mp_,...e}};async function Ouc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new mQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function Auc(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 wp_=(e,t)=>{let r={};for(let i in t)!(i in vp_)&&!(i in bp_)&&!(i in e)&&(r[i]=t[i]);return r},Ep_=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 KPa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>yUo)throw new RangeError(`The \`timeout\` option cannot be greater than ${yUo}`);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 HPa(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(!pp_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return Op_(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(hp_))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:buc(this._input.headers,r.headers),hooks:vuc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Pp_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:jp_(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(fp_&&dp_){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(yuc&&(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),Ep_(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);(_p_&&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(!yuc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Ap_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof mQn)throw t;if(t instanceof HPa){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),yUo);if(this._retryCount<1)throw r;await Auc(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})===bUo)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=wp_(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):Ouc(this._originalRequest,t,this.abortController,this._options)}};var muc=e=>{let t=(r,i)=>KPa.create(r,JPa(e,i));for(let r of hUo)t[r]=(i,n)=>KPa.create(i,JPa(e,n,{method:r}));return t.create=r=>muc(JPa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),muc(JPa(e,r))),t.stop=bUo,t},k2S=muc(),Sp_=k2S;var Yp_=re($p_(),1);function Suc(e){let t=(0,Yp_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var x__=re(W__(),1),G__=re(ZOe(),1),Uuc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Luc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Vuc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Suc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,x__.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 Sp_(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new Uuc(e):l}if(t.allVersions)return s;let u=new Luc(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=G__.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 eja(e,t){let{version:r}=await Vuc(e.toLowerCase(),t);return r}async function BCi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:eja(e.packageName,{version:t?"prerelease":"latest"})}var H__=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],BUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ks.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new pUo(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"1.9.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Jt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new BE}failWithoutThrowing(t,r){this.didSucceed=!1,lUo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await TRn()).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 sp_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1405
1405
|
`)||(r+=`
|
|
1406
1406
|
`),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=jws(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 UPa(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 BE}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await TRn()).sendEvent(t)}logger=L8t((t,...r)=>this.log(t,...r));stderr=L8t((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=J__(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?J__(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=H__[this.numTasks++%H__.length],o=Jt.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=>cMi.indexOf(n.level)>=cMi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===ks.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 BCi({cliEnvironment:this.environment,includePreReleases:t}),i=YH(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await _Uo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await nuc({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Jt.yellow("?"),style:{answer:n=>Jt.cyan(n),message:n=>Jt.bold(n),highlight:n=>Jt.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
|
|
1407
1407
|
Cancelled by user.`),new BE):i}}async getInput(t){return await euc({message:t.message,default:t.default})}};function J__(e){return`[${e}]:`}var pFt=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 IUo(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)=>IUo.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 K__(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 $__(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 Y__=Function.bind,X__=Y__.bind(Y__);function Z__(e,t,r){let i=X__($__,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]=X__(K__,null).apply(null,a)})}function aeM(){let e=Symbol("Singular"),t={registry:{}},r=IUo.bind(null,t,e);return Z__(r,t,e),r}function oeM(){let e={registry:{}},t=IUo.bind(null,e);return Z__(t,e),t}var k__={Singular:aeM,Collection:oeM};var ueM="0.0.0-development",seM=`octokit-endpoint.js/${ueM} ${WR()}`,ceM={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":seM},mediaType:{format:""}};function leM(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function feM(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 rh_(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(i=>{feM(t[i])?i in e?r[i]=rh_(e[i],t[i]):Object.assign(r,{[i]:t[i]}):Object.assign(r,{[i]:t[i]})}),r}function eh_(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function xuc(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=leM(r.headers),eh_(r),eh_(r.headers);let i=rh_(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 deM(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 peM=/\{[^{}}]+\}/g;function _eM(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function heM(e){let t=e.match(peM);return t?t.map(_eM).reduce((r,i)=>r.concat(i),[]):[]}function th_(e,t){let r={__proto__:null};for(let i of Object.keys(e))t.indexOf(i)===-1&&(r[i]=e[i]);return r}function ih_(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 IQn(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function tja(e,t,r){return t=e==="+"||e==="#"?ih_(t):IQn(t),r?IQn(r)+"="+t:t}function BQn(e){return e!=null}function Wuc(e){return e===";"||e==="&"||e==="?"}function yeM(e,t,r,i){var n=e[r],a=[];if(BQn(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(tja(t,n,Wuc(t)?r:""));else if(i==="*")Array.isArray(n)?n.filter(BQn).forEach(function(o){a.push(tja(t,o,Wuc(t)?r:""))}):Object.keys(n).forEach(function(o){BQn(n[o])&&a.push(tja(t,n[o],o))});else{let o=[];Array.isArray(n)?n.filter(BQn).forEach(function(c){o.push(tja(t,c))}):Object.keys(n).forEach(function(c){BQn(n[c])&&(o.push(IQn(c)),o.push(tja(t,n[c].toString())))}),Wuc(t)?a.push(IQn(r)+"="+o.join(",")):o.length!==0&&a.push(o.join(","))}else t===";"?BQn(n)&&a.push(IQn(r)):n===""&&(t==="&"||t==="?")?a.push(IQn(r)+"="):n===""&&a.push("");return a}function beM(e){return{expand:veM.bind(null,e)}}function veM(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(yeM(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 ih_(a)}),e==="/"?e:e.replace(/\/$/,"")}function nh_(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),i=Object.assign({},e.headers),n,a=th_(e,["method","baseUrl","url","headers","request","mediaType"]),o=heM(r);r=beM(r).expand(a),/^http/.test(r)||(r=e.baseUrl+r);let c=Object.keys(e).filter(u=>o.includes(u)).concat("baseUrl"),f=th_(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=deM(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 geM(e,t,r){return nh_(xuc(e,t,r))}function ah_(e,t){let r=xuc(e,t),i=geM.bind(null,r);return Object.assign(i,{DEFAULTS:r,defaults:ah_.bind(null,r),merge:xuc.bind(null,r),parse:nh_})}var oh_=ah_(null,ceM);var dh_=re(lh_(),1);var _Ft=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 OeM="10.0.6",AeM={headers:{"user-agent":`octokit-request.js/${OeM} ${WR()}`}};function meM(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 fh_(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=meM(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 _Ft(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 _Ft(o.statusText,c,{response:u,request:e})}if(c===304)throw u.data=await Guc(o),new _Ft("Not modified",c,{response:u,request:e});if(c>=400)throw u.data=await Guc(o),new _Ft(jeM(u.data),c,{response:u,request:e});return u.data=i?await Guc(o):o.body,u}async function Guc(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(()=>"");let r=(0,dh_.safeParse)(t);if(PeM(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 PeM(e){return e.type==="application/json"||e.type==="application/scim+json"}function jeM(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 Huc(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 fh_(r.parse(o));let c=(f,s)=>fh_(r.parse(r.merge(f,s)));return Object.assign(c,{endpoint:r,defaults:Huc.bind(null,r)}),o.request.hook(c,o)},{endpoint:r,defaults:Huc.bind(null,r)})}var xO=Huc(oh_,AeM);var weM="0.0.0-development";function EeM(e){return`Request failed due to following response errors:
|
|
@@ -1800,7 +1800,7 @@ ${l}
|
|
|
1800
1800
|
`,o=o.replace(f,l)}catch{i.logger.warn(`Failed to read markdown file "${u}" referenced in ${r}`);break}}return o}var j7_=require("fs/promises"),w7_=re(R_e(),1);async function C7M(e){let{content:t}=(0,w7_.default)(await(0,j7_.readFile)(e));return t}function q7M(e){let t={},r=/(\w+)=(?:{?['"]([^'"]+)['"]?}?|{([^}]+)})/g,i;for(;(i=r.exec(e))!=null;){let n=i[1],a=i[2]??i[3];n!=null&&a!=null&&(t[n]=a)}return t}function T7M(e){let t=new Set,r=/{{([A-Za-z_][A-Za-z0-9_]*)}}/g,i;for(;(i=r.exec(e))!=null;)i[1]!=null&&t.add(i[1]);return t}function R7M(e,t){return e.slice(0,t).split(`
|
|
1801
1801
|
`).length}function z7M(e,t){let r=e;for(let[i,n]of Object.entries(t)){let a=new RegExp(`\\{{${i}\\}}`,"g");r=r.replace(a,n)}return r}async function Lmc({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,markdownLoader:n=C7M}){if(!e.includes("<Markdown"))return e;let a=/([ \t]*)<Markdown\s+([^>]+)\/>/g,o=e,c;for(;(c=a.exec(e))!=null;){let f=c[0],s=c[1],u=c[2];if(f==null||u==null)throw new Error(`Failed to parse regex "${c}" in ${r}`);let l=q7M(u),p=l.src;if(p==null||!p.match(/\.mdx?$/))continue;let _=bs(p.startsWith("/")?t:cn(r),et.of(p.replace(/^\//,"")));try{let h=await n(_),{src:y,...b}=l,v=T7M(h),O=new Set(Object.keys(b)),A=[...v].filter(g=>!O.has(g));if(A.length>0){let g=c.index??e.indexOf(f),m=R7M(e,g),w=String(r).split("/").pop()??String(r);for(let D of A)i.logger.warn(`[${r}:${m}] Markdown snippet missing property: \`${D}\``)}h=z7M(h,b),h=h.split(`
|
|
1802
1802
|
`).map(g=>s+g).join(`
|
|
1803
|
-
`),o=o.replace(f,h)}catch{i.logger.warn(`Failed to read markdown file "${p}" referenced in ${r}`);break}}return o}var AJo=new Map;function E7_(e){try{let{data:t}=(0,M7_.default)(e);if(t.position==null)return;let r=typeof t.position=="string"?parseFloat(t.position):t.position;return typeof r=="number"&&Number.isFinite(r)?r:void 0}catch{return}}async function mJo({domain:e,project:t,context:r,previousDocsDefinition:i,editedAbsoluteFilepaths:n}){let a=t.docsWorkspaces,o=t.apiWorkspaces;if(a==null)throw new Error("No docs workspace found in project");if(n!=null&&i!=null){let y=n.every(v=>v.endsWith(".mdx")||v.endsWith(".md")),b=!1;for(let v of n){let O=Mv(a.absoluteFilePath,v),A=hi.PageId(O),g=i.pages[A];if(!await Fi(v)){b=!0;continue}let m=(await(0,S7_.readFile)(v)).toString(),w=g==null;w&&(b=!0);let D=E7_(m);if(AJo.get(v)!==D&&(b=!0),AJo.set(v,D),w)continue;let S=await Lmc({markdown:m,absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:v,context:r}),{markdown:B,filepaths:F}=Fmc(S,{absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:v});i.filesV2==null&&(i.filesV2={});let R=new Map(Object.entries(i.filesV2).map(([T,U])=>{let L="/"+U.url.replace("/_local/","");return[Ur.of(L),T]}));for(let T of F)if(!R.has(T)){let U=hi.FileId(rhe());i.filesV2[U]={type:"url",url:Qt.Url(`/_local${Ruo(T)}`)},R.set(T,U)}let z=Qmc(B,R,{},{absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:v},r);z=await Umc({markdown:z,absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:v,context:r}),i.pages[A]={markdown:z,editThisPageUrl:g.editThisPageUrl,rawMarkdown:m}}if(y&&!b)return i}let c=await aU(t),f=new Vmc(r),s=new Wmc(r),u={},p=await new FFt({domain:e,docsWorkspace:a,ossWorkspaces:c,apiWorkspaces:o,taskContext:r,editThisPage:void 0,uploadFiles:async y=>y.map(b=>{let v=rhe();return u[v]={type:"url",url:Qt.Url(`/_local${Ruo(b.absoluteFilePath)}`)},{absoluteFilePath:b.absoluteFilePath,relativeFilePath:b.relativeFilePath,fileId:v}}),registerApi:async y=>f.addReferencedAPI(y),targetAudiences:void 0}).resolve(),_=iup({writeShape:p,files:{}}),h=sup({dbShape:_.config});AJo.clear();for(let[y,b]of Object.entries(_.pages))if(b.rawMarkdown!=null){let v=Ur.of(`${a.absoluteFilePath}/${y.replace("api/","")}`),O=E7_(b.rawMarkdown);AJo.set(v,O)}return{apis:f.getAPIsForDefinition(),apisV2:s.getAPIsForDefinition(),config:h,files:{},filesV2:u,pages:_.pages,jsFiles:_.jsFiles,id:void 0}}var Vmc=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:i}){try{let n=rhe(),a=Fdo(q6({ir:t,snippetsConfig:r,playgroundConfig:i,context:this.context}),hi.ApiDefinitionId(n),new Udo({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),o=Ldo(a);return this.apis[n]=o,n}catch(n){let a=n;throw this.context.logger.debug(`Failed to read referenced API: ${a?.message} ${a?.stack}`),this.context.logger.error("An error occurred while trying to read an API definition. Please reach out to support."),a.stack!=null&&this.context.logger.error(a?.stack),n}}getAPIsForDefinition(){return this.apis}},Wmc=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({api:t,snippetsConfig:r}){try{return t.snippetsConfiguration=r,this.apis[t.id]=t,t.id}catch(i){let n=i;throw this.context.logger.debug(`Failed to read referenced API: ${n?.message} ${n?.stack}`),this.context.logger.error("An error occurred while trying to read an API definition. Please reach out to support."),n.stack!=null&&this.context.logger.error(n?.stack),i}}getAPIsForDefinition(){return this.apis}};var N7M={pages:{},apis:{},apisV2:{},files:{},filesV2:{},config:{aiChatConfig:void 0,hideNavLinks:void 0,navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,languages:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,settings:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0,pageActions:void 0,theme:void 0},jsFiles:void 0,id:void 0},xmc=class{context;snippetToPages=new Map;pageToSnippets=new Map;constructor(t){this.context=t}extractReferences(t,r,i){let n=new Set,a=/<Markdown\s+src={?['"]([^'"]+\.mdx?)['"](?! \+)}?\s*\/>/g,o;for(;(o=a.exec(t))!==null;){let f=o[1];if(f){let s=bs(f.startsWith("/")?i:cn(r),et.of(f.replace(/^\//,"")));n.add(s)}}let c=/<Code(?:\s+[^>]*?)?\s+src={?['"]([^'"]+)['"](?! \+)}?((?:\s+[^>]*)?)\/>/g;for(;(o=c.exec(t))!==null;){let f=o[1];if(f){let s=bs(f.startsWith("/")?i:cn(r),et.of(f.replace(/^\//,"")));n.add(s)}}return n}async buildDependencyMap(t){this.snippetToPages.clear(),this.pageToSnippets.clear();let r=t.docsWorkspaces;if(r){this.context.logger.debug("Building snippet dependency map...");try{let i=await this.findMarkdownFiles(r.absoluteFilePath);for(let n of i)try{let a=await(0,I7_.readFile)(n,"utf-8"),o=this.extractReferences(a,n,r.absoluteFilePath);this.pageToSnippets.set(n,o);for(let c of o)this.snippetToPages.has(c)||this.snippetToPages.set(c,new Set),this.snippetToPages.get(c)?.add(n)}catch(a){this.context.logger.debug(`Failed to read markdown file ${n}: ${a}`)}this.context.logger.debug(`Built dependency map: ${this.snippetToPages.size} snippets, ${this.pageToSnippets.size} pages`)}catch(i){this.context.logger.debug(`Failed to build dependency map: ${i}`)}}}async findMarkdownFiles(t){try{let r=await ZF(t,"md"),i=await ZF(t,"mdx");return[...r,...i]}catch(r){return this.context.logger.debug(`Failed to list files in ${t}: ${r}`),[]}}getFilesToReload(t){let r=new Set;for(let i of t)r.add(i);for(let i of t){let n=this.snippetToPages.get(i);if(n){this.context.logger.debug(`Snippet ${i} affects ${n.size} pages`);for(let a of n)r.add(a)}}return Array.from(r).map(Ur.of)}hasSnippetDependencies(t){for(let r of t){let i=this.snippetToPages.get(r);if(i&&i.size>0)return!0}return!1}getDebugInfo(){let t=0;for(let r of this.snippetToPages.values())t+=r.size;return{snippetCount:this.snippetToPages.size,pageCount:this.pageToSnippets.size,totalDependencies:t}}};async function Gmc({initialProject:e,reloadProject:t,validateProject:r,context:i,port:n,bundlePath:a,backendPort:o}){if(a!=null)i.logger.info(`Using bundle from path: ${a}`);else try{let U="https://prod-local-preview-bundle4.s3.amazonaws.com/";if(U==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await OMa({bucketUrl:U,logger:i.logger,preferCached:!0,app:!0,tryTar:!0})}catch(U){U instanceof Error&&(i.logger.debug(`Failed to download latest docs bundle: ${U.message}`),i.logger.error("Failed to unzip .tar.gz bundle. Please report to support@buildwithfern.com")),i.logger.debug("Falling back to .zip bundle");try{let L="https://prod-local-preview-bundle3.s3.amazonaws.com/";if(L==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await OMa({bucketUrl:L,logger:i.logger,preferCached:!0,app:!0,tryTar:!1})}catch{if(await Fi(R1i({app:!0})))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}}let c=a||R1i({app:!0}),f=q7_.default.join(c,"standalone/packages/fern-docs/bundle/server.js"),s={...process.env,PORT:n.toString(),HOSTNAME:"0.0.0.0",NEXT_PUBLIC_FDR_ORIGIN_PORT:o.toString(),NEXT_PUBLIC_FDR_ORIGIN:`http://localhost:${o}`,NEXT_PUBLIC_DOCS_DOMAIN:e.docsWorkspaces?.config.instances[0]?.url,NEXT_PUBLIC_IS_LOCAL:"1",NEXT_DISABLE_CACHE:"1",NODE_ENV:"production",NODE_PATH:c,NODE_OPTIONS:"--max-old-space-size=8096 --enable-source-maps"},u=Yqi(i.logger,"node",[f],{env:s,doNotPipeOutput:!0});u.stdout?.on("data",U=>{i.logger.debug(`[Next.js] ${U.toString()}`)}),u.stderr?.on("data",U=>{i.logger.debug(`[Next.js] ${U.toString()}`)}),i.logger.debug(`Next.js standalone server started with PID: ${u.pid}`),u.on("error",U=>{i.logger.debug(`Server process error: ${U.message}`)}),u.on("exit",(U,L)=>{U?i.logger.debug(`Server process exited with code: ${U}`):L?i.logger.debug(`Server process killed with signal: ${L}`):i.logger.debug("Server process exited")});let l=()=>{if(!u.killed){i.logger.debug(`Killing server process with PID: ${u.pid}`);try{u.kill(),setTimeout(()=>{if(!u.killed){i.logger.debug(`Force killing server process with PID: ${u.pid}`);try{u.kill("SIGKILL")}catch(U){i.logger.error(`Failed to force kill server process: ${U}`)}}},2e3)}catch(U){i.logger.error(`Failed to kill server process: ${U}`)}}i.logger.debug("Cleaning up WebSocket connections...");for(let[U,L]of O)clearInterval(L.pingInterval),U.readyState===xNn.default.OPEN&&U.close(1e3,"Server shutting down");O.clear(),b.close()},p=["SIGTERM","SIGINT"],_=["SIGHUP"];for(let U of p)process.on(U,()=>{i.logger.debug("Shutting down server..."),l()});for(let U of _)process.on(U,()=>{i.logger.debug("Server failed, shutting down process..."),l()});process.on("exit",l),process.on("uncaughtException",U=>{i.logger.debug(`Uncaught exception: ${U}`),l(),process.exit(1)}),process.on("unhandledRejection",U=>{i.logger.debug(`Unhandled rejection: ${U}`),l(),process.exit(1)}),process.on("beforeExit",l),await new Promise(U=>setTimeout(U,3e3)),i.logger.debug(`Next.js server should now be running on http://localhost:${n}`);let h=cn(e.config._absolutePath),y=(0,B7_.default)(),b=C7_.default.createServer(y),v=new M0a.default({server:b,clientTracking:!0,perMessageDeflate:!1}),O=new Map;function A(U){let L=JSON.stringify(U),H=[];for(let[ae,oe]of O)if(ae.readyState===xNn.default.OPEN)try{ae.send(L)}catch(G){i.logger.debug(`Failed to send message to connection ${oe.id}: ${G}`),H.push(ae)}else H.push(ae);H.forEach(ae=>{let oe=O.get(ae);oe&&(clearInterval(oe.pingInterval),O.delete(ae))})}v.on("connection",function(L,H){let ae=`${H.socket.remoteAddress}:${H.socket.remotePort}-${Date.now()}`,oe={id:ae,isAlive:!0,lastPong:Date.now(),pingInterval:setInterval(()=>{if(L.readyState===xNn.default.OPEN){let G=Date.now();if(G-oe.lastPong>9e4){i.logger.debug(`Connection ${ae} timed out, closing`),L.terminate();return}oe.isAlive=!1;try{L.send(JSON.stringify({type:"ping",timestamp:G}))}catch(V){i.logger.debug(`Failed to send ping to ${ae}: ${V}`),L.terminate()}}},3e4)};O.set(L,oe),L.on("message",function(V){try{JSON.parse(V.toString()).type==="pong"&&(oe.isAlive=!0,oe.lastPong=Date.now())}catch(Ce){i.logger.debug(`Failed to parse message from ${ae}: ${Ce}`)}}),L.on("error",function(V){i.logger.debug(`WebSocket error for connection ${ae}: ${V.message}`)}),L.on("close",function(V,Ce){clearInterval(oe.pingInterval),O.delete(L)});try{L.send(JSON.stringify({type:"connected",connectionId:ae}))}catch(G){i.logger.debug(`Failed to send connection confirmation: ${G}`)}}),y.use((0,D7_.default)());let g=new URL(N1(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),m=e,w,D=new xmc(i);await D.buildDependencyMap(m);let E=null,S=!1,B=1e3,F=async U=>{i.logger.info("Reloading docs...");let L=Date.now();try{m=await t(),await D.buildDependencyMap(m);let H=Date.now();r(m).catch(oe=>{let G=Date.now()-H;i.logger.error(`Validation failed (took ${G}ms): ${oe instanceof Error?oe.message:String(oe)}`),oe instanceof Error&&oe.stack&&i.logger.debug(`Validation error stack: ${oe.stack}`)});let ae=await mJo({domain:`${g.host}${g.pathname}`,project:m,context:i,previousDocsDefinition:w,editedAbsoluteFilepaths:U});return i.logger.info(`Reload completed in ${Date.now()-L}ms`),ae}catch(H){return w==null?i.logger.error("Failed to read docs configuration. Rendering blank page."):i.logger.error("Failed to read docs configuration. Rendering last successful configuration."),H instanceof Error&&(i.logger.error(H.message),H instanceof Error&&H.stack&&i.logger.debug(`Stack Trace:
|
|
1803
|
+
`),o=o.replace(f,h)}catch{i.logger.warn(`Failed to read markdown file "${p}" referenced in ${r}`);break}}return o}var AJo=new Map;function E7_(e){try{let{data:t}=(0,M7_.default)(e);if(t.position==null)return;let r=typeof t.position=="string"?parseFloat(t.position):t.position;return typeof r=="number"&&Number.isFinite(r)?r:void 0}catch{return}}async function mJo({domain:e,project:t,context:r,previousDocsDefinition:i,editedAbsoluteFilepaths:n}){let a=t.docsWorkspaces,o=t.apiWorkspaces;if(a==null)throw new Error("No docs workspace found in project");if(n!=null&&i!=null){let y=n.every(v=>v.endsWith(".mdx")||v.endsWith(".md")),b=!1;for(let v of n){let O=Mv(a.absoluteFilePath,v),A=hi.PageId(O),g=i.pages[A];if(!await Fi(v)){b=!0;continue}let m=(await(0,S7_.readFile)(v)).toString(),w=g==null;w&&(b=!0);let D=E7_(m);if(AJo.get(v)!==D&&(b=!0),AJo.set(v,D),w)continue;let S=await Lmc({markdown:m,absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:v,context:r}),B=await Umc({markdown:S,absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:v,context:r}),{markdown:F,filepaths:R}=Fmc(B,{absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:v});i.filesV2==null&&(i.filesV2={});let z=new Map(Object.entries(i.filesV2).map(([U,L])=>{let H="/"+L.url.replace("/_local/","");return[Ur.of(H),U]}));for(let U of R)if(!z.has(U)){let L=hi.FileId(rhe());i.filesV2[L]={type:"url",url:Qt.Url(`/_local${Ruo(U)}`)},z.set(U,L)}let T=Qmc(F,z,{},{absolutePathToFernFolder:a.absoluteFilePath,absolutePathToMarkdownFile:v},r);i.pages[A]={markdown:T,editThisPageUrl:g.editThisPageUrl,rawMarkdown:m}}if(y&&!b)return i}let c=await aU(t),f=new Vmc(r),s=new Wmc(r),u={},p=await new FFt({domain:e,docsWorkspace:a,ossWorkspaces:c,apiWorkspaces:o,taskContext:r,editThisPage:void 0,uploadFiles:async y=>y.map(b=>{let v=rhe();return u[v]={type:"url",url:Qt.Url(`/_local${Ruo(b.absoluteFilePath)}`)},{absoluteFilePath:b.absoluteFilePath,relativeFilePath:b.relativeFilePath,fileId:v}}),registerApi:async y=>f.addReferencedAPI(y),targetAudiences:void 0}).resolve(),_=iup({writeShape:p,files:{}}),h=sup({dbShape:_.config});AJo.clear();for(let[y,b]of Object.entries(_.pages))if(b.rawMarkdown!=null){let v=Ur.of(`${a.absoluteFilePath}/${y.replace("api/","")}`),O=E7_(b.rawMarkdown);AJo.set(v,O)}return{apis:f.getAPIsForDefinition(),apisV2:s.getAPIsForDefinition(),config:h,files:{},filesV2:u,pages:_.pages,jsFiles:_.jsFiles,id:void 0}}var Vmc=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:i}){try{let n=rhe(),a=Fdo(q6({ir:t,snippetsConfig:r,playgroundConfig:i,context:this.context}),hi.ApiDefinitionId(n),new Udo({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),o=Ldo(a);return this.apis[n]=o,n}catch(n){let a=n;throw this.context.logger.debug(`Failed to read referenced API: ${a?.message} ${a?.stack}`),this.context.logger.error("An error occurred while trying to read an API definition. Please reach out to support."),a.stack!=null&&this.context.logger.error(a?.stack),n}}getAPIsForDefinition(){return this.apis}},Wmc=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({api:t,snippetsConfig:r}){try{return t.snippetsConfiguration=r,this.apis[t.id]=t,t.id}catch(i){let n=i;throw this.context.logger.debug(`Failed to read referenced API: ${n?.message} ${n?.stack}`),this.context.logger.error("An error occurred while trying to read an API definition. Please reach out to support."),n.stack!=null&&this.context.logger.error(n?.stack),i}}getAPIsForDefinition(){return this.apis}};var N7M={pages:{},apis:{},apisV2:{},files:{},filesV2:{},config:{aiChatConfig:void 0,hideNavLinks:void 0,navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,languages:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,settings:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0,pageActions:void 0,theme:void 0},jsFiles:void 0,id:void 0},xmc=class{context;snippetToPages=new Map;pageToSnippets=new Map;constructor(t){this.context=t}extractReferences(t,r,i){let n=new Set,a=/<Markdown\s+src={?['"]([^'"]+\.mdx?)['"](?! \+)}?\s*\/>/g,o;for(;(o=a.exec(t))!==null;){let f=o[1];if(f){let s=bs(f.startsWith("/")?i:cn(r),et.of(f.replace(/^\//,"")));n.add(s)}}let c=/<Code(?:\s+[^>]*?)?\s+src={?['"]([^'"]+)['"](?! \+)}?((?:\s+[^>]*)?)\/>/g;for(;(o=c.exec(t))!==null;){let f=o[1];if(f){let s=bs(f.startsWith("/")?i:cn(r),et.of(f.replace(/^\//,"")));n.add(s)}}return n}async buildDependencyMap(t){this.snippetToPages.clear(),this.pageToSnippets.clear();let r=t.docsWorkspaces;if(r){this.context.logger.debug("Building snippet dependency map...");try{let i=await this.findMarkdownFiles(r.absoluteFilePath);for(let n of i)try{let a=await(0,I7_.readFile)(n,"utf-8"),o=this.extractReferences(a,n,r.absoluteFilePath);this.pageToSnippets.set(n,o);for(let c of o)this.snippetToPages.has(c)||this.snippetToPages.set(c,new Set),this.snippetToPages.get(c)?.add(n)}catch(a){this.context.logger.debug(`Failed to read markdown file ${n}: ${a}`)}this.context.logger.debug(`Built dependency map: ${this.snippetToPages.size} snippets, ${this.pageToSnippets.size} pages`)}catch(i){this.context.logger.debug(`Failed to build dependency map: ${i}`)}}}async findMarkdownFiles(t){try{let r=await ZF(t,"md"),i=await ZF(t,"mdx");return[...r,...i]}catch(r){return this.context.logger.debug(`Failed to list files in ${t}: ${r}`),[]}}getFilesToReload(t){let r=new Set;for(let i of t)r.add(i);for(let i of t){let n=this.snippetToPages.get(i);if(n){this.context.logger.debug(`Snippet ${i} affects ${n.size} pages`);for(let a of n)r.add(a)}}return Array.from(r).map(Ur.of)}hasSnippetDependencies(t){for(let r of t){let i=this.snippetToPages.get(r);if(i&&i.size>0)return!0}return!1}getDebugInfo(){let t=0;for(let r of this.snippetToPages.values())t+=r.size;return{snippetCount:this.snippetToPages.size,pageCount:this.pageToSnippets.size,totalDependencies:t}}};async function Gmc({initialProject:e,reloadProject:t,validateProject:r,context:i,port:n,bundlePath:a,backendPort:o}){if(a!=null)i.logger.info(`Using bundle from path: ${a}`);else try{let U="https://prod-local-preview-bundle4.s3.amazonaws.com/";if(U==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await OMa({bucketUrl:U,logger:i.logger,preferCached:!0,app:!0,tryTar:!0})}catch(U){U instanceof Error&&(i.logger.debug(`Failed to download latest docs bundle: ${U.message}`),i.logger.error("Failed to unzip .tar.gz bundle. Please report to support@buildwithfern.com")),i.logger.debug("Falling back to .zip bundle");try{let L="https://prod-local-preview-bundle3.s3.amazonaws.com/";if(L==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await OMa({bucketUrl:L,logger:i.logger,preferCached:!0,app:!0,tryTar:!1})}catch{if(await Fi(R1i({app:!0})))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}}let c=a||R1i({app:!0}),f=q7_.default.join(c,"standalone/packages/fern-docs/bundle/server.js"),s={...process.env,PORT:n.toString(),HOSTNAME:"0.0.0.0",NEXT_PUBLIC_FDR_ORIGIN_PORT:o.toString(),NEXT_PUBLIC_FDR_ORIGIN:`http://localhost:${o}`,NEXT_PUBLIC_DOCS_DOMAIN:e.docsWorkspaces?.config.instances[0]?.url,NEXT_PUBLIC_IS_LOCAL:"1",NEXT_DISABLE_CACHE:"1",NODE_ENV:"production",NODE_PATH:c,NODE_OPTIONS:"--max-old-space-size=8096 --enable-source-maps"},u=Yqi(i.logger,"node",[f],{env:s,doNotPipeOutput:!0});u.stdout?.on("data",U=>{i.logger.debug(`[Next.js] ${U.toString()}`)}),u.stderr?.on("data",U=>{i.logger.debug(`[Next.js] ${U.toString()}`)}),i.logger.debug(`Next.js standalone server started with PID: ${u.pid}`),u.on("error",U=>{i.logger.debug(`Server process error: ${U.message}`)}),u.on("exit",(U,L)=>{U?i.logger.debug(`Server process exited with code: ${U}`):L?i.logger.debug(`Server process killed with signal: ${L}`):i.logger.debug("Server process exited")});let l=()=>{if(!u.killed){i.logger.debug(`Killing server process with PID: ${u.pid}`);try{u.kill(),setTimeout(()=>{if(!u.killed){i.logger.debug(`Force killing server process with PID: ${u.pid}`);try{u.kill("SIGKILL")}catch(U){i.logger.error(`Failed to force kill server process: ${U}`)}}},2e3)}catch(U){i.logger.error(`Failed to kill server process: ${U}`)}}i.logger.debug("Cleaning up WebSocket connections...");for(let[U,L]of O)clearInterval(L.pingInterval),U.readyState===xNn.default.OPEN&&U.close(1e3,"Server shutting down");O.clear(),b.close()},p=["SIGTERM","SIGINT"],_=["SIGHUP"];for(let U of p)process.on(U,()=>{i.logger.debug("Shutting down server..."),l()});for(let U of _)process.on(U,()=>{i.logger.debug("Server failed, shutting down process..."),l()});process.on("exit",l),process.on("uncaughtException",U=>{i.logger.debug(`Uncaught exception: ${U}`),l(),process.exit(1)}),process.on("unhandledRejection",U=>{i.logger.debug(`Unhandled rejection: ${U}`),l(),process.exit(1)}),process.on("beforeExit",l),await new Promise(U=>setTimeout(U,3e3)),i.logger.debug(`Next.js server should now be running on http://localhost:${n}`);let h=cn(e.config._absolutePath),y=(0,B7_.default)(),b=C7_.default.createServer(y),v=new M0a.default({server:b,clientTracking:!0,perMessageDeflate:!1}),O=new Map;function A(U){let L=JSON.stringify(U),H=[];for(let[ae,oe]of O)if(ae.readyState===xNn.default.OPEN)try{ae.send(L)}catch(G){i.logger.debug(`Failed to send message to connection ${oe.id}: ${G}`),H.push(ae)}else H.push(ae);H.forEach(ae=>{let oe=O.get(ae);oe&&(clearInterval(oe.pingInterval),O.delete(ae))})}v.on("connection",function(L,H){let ae=`${H.socket.remoteAddress}:${H.socket.remotePort}-${Date.now()}`,oe={id:ae,isAlive:!0,lastPong:Date.now(),pingInterval:setInterval(()=>{if(L.readyState===xNn.default.OPEN){let G=Date.now();if(G-oe.lastPong>9e4){i.logger.debug(`Connection ${ae} timed out, closing`),L.terminate();return}oe.isAlive=!1;try{L.send(JSON.stringify({type:"ping",timestamp:G}))}catch(V){i.logger.debug(`Failed to send ping to ${ae}: ${V}`),L.terminate()}}},3e4)};O.set(L,oe),L.on("message",function(V){try{JSON.parse(V.toString()).type==="pong"&&(oe.isAlive=!0,oe.lastPong=Date.now())}catch(Ce){i.logger.debug(`Failed to parse message from ${ae}: ${Ce}`)}}),L.on("error",function(V){i.logger.debug(`WebSocket error for connection ${ae}: ${V.message}`)}),L.on("close",function(V,Ce){clearInterval(oe.pingInterval),O.delete(L)});try{L.send(JSON.stringify({type:"connected",connectionId:ae}))}catch(G){i.logger.debug(`Failed to send connection confirmation: ${G}`)}}),y.use((0,D7_.default)());let g=new URL(N1(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),m=e,w,D=new xmc(i);await D.buildDependencyMap(m);let E=null,S=!1,B=1e3,F=async U=>{i.logger.info("Reloading docs...");let L=Date.now();try{m=await t(),await D.buildDependencyMap(m);let H=Date.now();r(m).catch(oe=>{let G=Date.now()-H;i.logger.error(`Validation failed (took ${G}ms): ${oe instanceof Error?oe.message:String(oe)}`),oe instanceof Error&&oe.stack&&i.logger.debug(`Validation error stack: ${oe.stack}`)});let ae=await mJo({domain:`${g.host}${g.pathname}`,project:m,context:i,previousDocsDefinition:w,editedAbsoluteFilepaths:U});return i.logger.info(`Reload completed in ${Date.now()-L}ms`),ae}catch(H){return w==null?i.logger.error("Failed to read docs configuration. Rendering blank page."):i.logger.error("Failed to read docs configuration. Rendering last successful configuration."),H instanceof Error&&(i.logger.error(H.message),H instanceof Error&&H.stack&&i.logger.debug(`Stack Trace:
|
|
1804
1804
|
${H.stack}`)),w}};w=await F();let R=m.apiWorkspaces.flatMap(U=>U.getAbsoluteFilePaths()),z=new lHo([h,...R],{recursive:!0,ignoreInitial:!0,debounce:100,renameDetection:!0}),T=[];z.on("all",async(U,L,H)=>{i.logger.info(Jt.dim(`[${U}] ${L}`)),!S&&(T.push(Ur.of(L)),E!=null&&clearTimeout(E),E=setTimeout(()=>{(async()=>{S=!0;let ae=D.getFilesToReload(T);D.hasSnippetDependencies(T)&&i.logger.info(`Snippet dependencies detected. Reloading ${ae.length} files (${T.length} changed, ${ae.length-T.length} dependent pages)`),A({version:1,type:"startReload"});let G=await F(ae);G!=null&&(w=G),T.length=0,A({version:1,type:"finishReload"}),S=!1})()},B))}),y.post("/v2/registry/docs/load-with-url",async(U,L)=>{try{let H=w??N7M,ae={baseUrl:{domain:g.host,basePath:g.pathname},definition:H,lightModeEnabled:H.config.colorsV3?.type!=="dark",orgId:Qt.OrgId(e.config.organization)};L.send(ae)}catch(H){i.logger.error("Stack trace:",H.stack??""),i.logger.error("Error loading docs",H.message),L.status(500).send()}}),y.get(/^\/_local\/(.*)/,(U,L)=>L.sendFile(`/${U.params[0]}`)),b.listen(o,()=>{i.logger.info(Jt.dim(`Backend server running on http://localhost:${o}`)),i.logger.info(`Development server ready on http://localhost:${n}`)}),await new Promise(()=>{})}var T7_=re(Mgc(),1),Hmc=re(nHo(),1),R7_=re(require("http"),1),PJo=re(require("path"),1);Szo();var F7M={pages:{},apis:{},apisV2:{},files:{},filesV2:{},config:{aiChatConfig:void 0,hideNavLinks:void 0,navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,languages:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,settings:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0,pageActions:void 0,theme:void 0},jsFiles:void 0,id:void 0};async function Jmc({initialProject:e,reloadProject:t,validateProject:r,context:i,port:n,bundlePath:a}){if(a!=null)i.logger.info(`Using bundle from path: ${a}`);else try{let D="https://prod-local-preview-bundle2.s3.amazonaws.com/";if(D==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await OMa({bucketUrl:D,logger:i.logger,preferCached:!0,tryTar:!1})}catch(D){let E=R1i({});if(D instanceof Error&&i.logger.debug(`Failed to download latest docs bundle: ${D.message}`),await Fi(E))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}let o=cn(e.config._absolutePath),c=(0,Hmc.default)(),f=R7_.default.createServer(c),s=new M0a.default({server:f}),u=new Set;function l(D){for(let E of u)E.send(JSON.stringify(D))}s.on("connection",function(E){u.add(E),E.on("close",function(){u.delete(E)})}),c.use((0,T7_.default)());let p=new URL(N1(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),_=e,h,y=null,b=!1,v=1e3,O=async D=>{i.logger.info("Reloading docs...");let E=Date.now();try{_=await t(),i.logger.info("Validating docs..."),await r(_);let S=await mJo({domain:`${p.host}${p.pathname}`,project:_,context:i,previousDocsDefinition:h,editedAbsoluteFilepaths:D});return i.logger.info(`Reload completed in ${Date.now()-E}ms`),S}catch(S){return h==null?i.logger.error("Failed to read docs configuration. Rendering blank page."):i.logger.error("Failed to read docs configuration. Rendering last successful configuration."),S instanceof Error&&(i.logger.error(S.message),S instanceof Error&&S.stack&&i.logger.debug(`Stack Trace:
|
|
1805
1805
|
${S.stack}`)),h}};h=await O();let A=_.apiWorkspaces.flatMap(D=>D.getAbsoluteFilePaths()),g=a?Ur.of(PJo.default.resolve(a)):R1i({}),m=new lHo([o,...A],{recursive:!0,ignoreInitial:!0,debounce:100,renameDetection:!0}),w=[];m.on("all",async(D,E,S)=>{i.logger.info(Jt.dim(`[${D}] ${E}`)),!b&&(w.push(Ur.of(E)),y!=null&&clearTimeout(y),y=setTimeout(()=>{(async()=>{b=!0,l({version:1,type:"startReload"});let B=await O(w);B!=null&&(h=B),w.length=0,l({version:1,type:"finishReload"}),b=!1})()},v))}),c.post("/v2/registry/docs/load-with-url",async(D,E)=>{try{let S=h??F7M,B={baseUrl:{domain:p.host,basePath:p.pathname},definition:S,lightModeEnabled:S.config.colorsV3?.type!=="dark",orgId:Qt.OrgId(e.config.organization)};E.send(B)}catch(S){i.logger.error("Stack trace:",S.stack??""),i.logger.error("Error loading docs",S.message),E.status(500).send()}}),c.get(/^\/_local\/(.*)/,(D,E)=>{let S=`/${D.params[0]}`,B=new Set;if(h?.filesV2){for(let F of Object.values(h.filesV2))if(F.type==="url"){let R=F.url.replace(/^\/_local/,"");B.add(R)}}return B.has(S)?E.sendFile(S):(i.logger.warn(`Blocked unauthorized file access attempt: ${S}`),E.status(403).send("Access denied"))}),c.get("/",(D,E,S)=>D.headers.upgrade==="websocket"?s.handleUpgrade(D,D.socket,Buffer.alloc(0),B=>{s.emit("connection",B,D)}):S()),c.use("/_next",Hmc.default.static(PJo.default.join(g,"/_next"))),c.use("*",async(D,E)=>E.sendFile(PJo.default.join(g,"/[[...slug]].html"))),c.listen(n),i.logger.info(`Running server on http://localhost:${n}`),await new Promise(()=>{})}var Kmc={};Kt(Kmc,{additionalProperties:()=>V7M,default:()=>x7M,definitions:()=>W7M,properties:()=>U7M,required:()=>L7M,type:()=>Q7M});var Q7M="object",U7M={tabs:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/docs.TabConfig"}},{type:"null"}]},"landing-page":{oneOf:[{$ref:"#/definitions/docs.PageConfiguration"},{type:"null"}]},navigation:{$ref:"#/definitions/docs.NavigationConfig"}},L7M=["navigation"],V7M=!1,W7M={"docs.RoleId":{type:"string"},"docs.Role":{anyOf:[{$ref:"#/definitions/docs.RoleId"},{type:"array",items:{$ref:"#/definitions/docs.RoleId"}}]},"docs.FeatureFlag":{type:"object",properties:{flag:{type:"string"},"fallback-value":{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},match:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]}},required:["flag"],additionalProperties:!1},"docs.FeatureFlagConfiguration":{anyOf:[{type:"string",description:"The name of the feature flag, We assume that it is a boolean feature flag that needs to be evaluated to true."},{$ref:"#/definitions/docs.FeatureFlag",description:"A single feature flag with a configurable name, fallback value, and match value. Especially useful for non boolean feature flags."},{type:"array",items:{$ref:"#/definitions/docs.FeatureFlag"},description:"A list of feature flags. If any of the feature flags are satisfied, we will show all content."}]},"docs.Target":{type:"string",enum:["_blank","_self","_parent","_top"]},"docs.ChangelogFolderRelativePath":{type:"string"},"docs.TabConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]},target:{oneOf:[{$ref:"#/definitions/docs.Target"},{type:"null"}]},changelog:{oneOf:[{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},{type:"null"}]}},required:["display-name"],additionalProperties:!1},"docs.Availability":{type:"string",enum:["stable","generally-available","in-development","pre-release","deprecated","beta"]},"docs.PageConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},page:{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},noindex:{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]}},required:["page","path"],additionalProperties:!1},"docs.SectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},path:{oneOf:[{type:"string"},{type:"null"}]},contents:{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]}},required:["section","contents"],additionalProperties:!1},"docs.AudienceId":{type:"string"},"docs.Audience":{anyOf:[{$ref:"#/definitions/docs.AudienceId"},{type:"array",items:{$ref:"#/definitions/docs.AudienceId"}}]},"docs.VersionedSnippetLanguageConfiguration":{type:"object",properties:{version:{type:"string"},package:{type:"string"}},required:["version","package"],additionalProperties:!1},"docs.SnippetLanguageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.VersionedSnippetLanguageConfiguration"}]},"docs.SnippetsConfiguration":{type:"object",properties:{python:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},typescript:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},go:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},java:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},ruby:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},csharp:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},php:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},swift:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},rust:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundButtonSettings":{type:"object",properties:{href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundSettings":{type:"object",properties:{environments:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},button:{oneOf:[{$ref:"#/definitions/docs.PlaygroundButtonSettings"},{type:"null"}]},oauth:{oneOf:[{type:"boolean"},{type:"null"}]},"limit-websocket-messages-per-connection":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfigurationWithOptions":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},title:{oneOf:[{type:"string"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfiguration":{anyOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{$ref:"#/definitions/docs.ApiReferencePackageConfigurationWithOptions"}]},"docs.ApiReferenceSectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},"referenced-packages":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["section"],additionalProperties:!1},"docs.ApiReferenceEndpointConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},endpoint:{type:"string"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"docs.LinkConfiguration":{type:"object",properties:{link:{type:"string"},href:{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]},target:{oneOf:[{$ref:"#/definitions/docs.Target"},{type:"null"}]}},required:["link","href"],additionalProperties:!1},"docs.ApiReferenceLayoutItem":{anyOf:[{type:"string",description:"This should be either an endpoint, websocket, webhook, or subpackage ID"},{type:"object",additionalProperties:{$ref:"#/definitions/docs.ApiReferencePackageConfiguration"},description:"Keyed by subpackage name, this object allows you to group endpoints and pages together."},{$ref:"#/definitions/docs.ApiReferenceSectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceEndpointConfiguration"},{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"}]},"docs.ApiReferenceConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},api:{type:"string"},"api-name":{oneOf:[{type:"string"},{type:"null"}]},openrpc:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{$ref:"#/definitions/docs.Audience"},{type:"null"}]},"display-errors":{oneOf:[{type:"boolean"},{type:"null"}]},snippets:{oneOf:[{$ref:"#/definitions/docs.SnippetsConfiguration"},{type:"null"}]},postman:{oneOf:[{type:"string"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},alphabetized:{oneOf:[{type:"boolean"},{type:"null"}]},flattened:{oneOf:[{type:"boolean"},{type:"null"}]},paginated:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["api"],additionalProperties:!1},"docs.ChangelogConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},changelog:{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["changelog"],additionalProperties:!1},"docs.FolderConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},folder:{type:"string"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]}},required:["folder"],additionalProperties:!1},"docs.NavigationItem":{anyOf:[{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.SectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"},{$ref:"#/definitions/docs.ChangelogConfiguration"},{$ref:"#/definitions/docs.FolderConfiguration"}]},"docs.UntabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},"docs.TabId":{type:"string"},"docs.TabbedNavigationItemWithLayout":{type:"object",properties:{tab:{$ref:"#/definitions/docs.TabId"},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},{type:"null"}]}},required:["tab"],additionalProperties:!1},"docs.TabVariant":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},title:{type:"string"},subtitle:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},layout:{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},slug:{oneOf:[{type:"string"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},default:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["title","layout"],additionalProperties:!1},"docs.TabbedNavigationItemWithVariants":{type:"object",properties:{tab:{$ref:"#/definitions/docs.TabId"},variants:{type:"array",items:{$ref:"#/definitions/docs.TabVariant"}}},required:["tab","variants"],additionalProperties:!1},"docs.TabbedNavigationItem":{anyOf:[{$ref:"#/definitions/docs.TabbedNavigationItemWithLayout"},{$ref:"#/definitions/docs.TabbedNavigationItemWithVariants"}]},"docs.TabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.TabbedNavigationItem"}},"docs.NavigationConfig":{anyOf:[{$ref:"#/definitions/docs.UntabbedNavigationConfig"},{$ref:"#/definitions/docs.TabbedNavigationConfig"}]}},x7M={type:Q7M,properties:U7M,required:L7M,additionalProperties:V7M,definitions:W7M};async function jJo({value:e}){let t=tzt(e,Kmc);if(t.success)return{type:"success",contents:v7.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(e)};let r=t.error?.instancePath?` at ${t?.error.instancePath}`:"";return{type:"failure",message:`${t.error?.message??"Failed to parse because JSON schema validation failed"}${r}`}}var Xmc=require("fs/promises");var $mc={};Kt($mc,{additionalProperties:()=>K7M,default:()=>Y7M,definitions:()=>$7M,properties:()=>H7M,required:()=>J7M,type:()=>G7M});var G7M="object",H7M={tabs:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/docs.TabConfig"}},{type:"null"}]},"landing-page":{oneOf:[{$ref:"#/definitions/docs.PageConfiguration"},{type:"null"}]},navigation:{$ref:"#/definitions/docs.NavigationConfig"}},J7M=["navigation"],K7M=!1,$7M={"docs.RoleId":{type:"string"},"docs.Role":{anyOf:[{$ref:"#/definitions/docs.RoleId"},{type:"array",items:{$ref:"#/definitions/docs.RoleId"}}]},"docs.FeatureFlag":{type:"object",properties:{flag:{type:"string"},"fallback-value":{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},match:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]}},required:["flag"],additionalProperties:!1},"docs.FeatureFlagConfiguration":{anyOf:[{type:"string",description:"The name of the feature flag, We assume that it is a boolean feature flag that needs to be evaluated to true."},{$ref:"#/definitions/docs.FeatureFlag",description:"A single feature flag with a configurable name, fallback value, and match value. Especially useful for non boolean feature flags."},{type:"array",items:{$ref:"#/definitions/docs.FeatureFlag"},description:"A list of feature flags. If any of the feature flags are satisfied, we will show all content."}]},"docs.Target":{type:"string",enum:["_blank","_self","_parent","_top"]},"docs.ChangelogFolderRelativePath":{type:"string"},"docs.TabConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]},target:{oneOf:[{$ref:"#/definitions/docs.Target"},{type:"null"}]},changelog:{oneOf:[{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},{type:"null"}]}},required:["display-name"],additionalProperties:!1},"docs.Availability":{type:"string",enum:["stable","generally-available","in-development","pre-release","deprecated","beta"]},"docs.PageConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},page:{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},noindex:{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]}},required:["page","path"],additionalProperties:!1},"docs.SectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},path:{oneOf:[{type:"string"},{type:"null"}]},contents:{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]}},required:["section","contents"],additionalProperties:!1},"docs.AudienceId":{type:"string"},"docs.Audience":{anyOf:[{$ref:"#/definitions/docs.AudienceId"},{type:"array",items:{$ref:"#/definitions/docs.AudienceId"}}]},"docs.VersionedSnippetLanguageConfiguration":{type:"object",properties:{version:{type:"string"},package:{type:"string"}},required:["version","package"],additionalProperties:!1},"docs.SnippetLanguageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.VersionedSnippetLanguageConfiguration"}]},"docs.SnippetsConfiguration":{type:"object",properties:{python:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},typescript:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},go:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},java:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},ruby:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},csharp:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},php:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},swift:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},rust:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundButtonSettings":{type:"object",properties:{href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundSettings":{type:"object",properties:{environments:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},button:{oneOf:[{$ref:"#/definitions/docs.PlaygroundButtonSettings"},{type:"null"}]},oauth:{oneOf:[{type:"boolean"},{type:"null"}]},"limit-websocket-messages-per-connection":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfigurationWithOptions":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},title:{oneOf:[{type:"string"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfiguration":{anyOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{$ref:"#/definitions/docs.ApiReferencePackageConfigurationWithOptions"}]},"docs.ApiReferenceSectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},"referenced-packages":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["section"],additionalProperties:!1},"docs.ApiReferenceEndpointConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},endpoint:{type:"string"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"docs.LinkConfiguration":{type:"object",properties:{link:{type:"string"},href:{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]},target:{oneOf:[{$ref:"#/definitions/docs.Target"},{type:"null"}]}},required:["link","href"],additionalProperties:!1},"docs.ApiReferenceLayoutItem":{anyOf:[{type:"string",description:"This should be either an endpoint, websocket, webhook, or subpackage ID"},{type:"object",additionalProperties:{$ref:"#/definitions/docs.ApiReferencePackageConfiguration"},description:"Keyed by subpackage name, this object allows you to group endpoints and pages together."},{$ref:"#/definitions/docs.ApiReferenceSectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceEndpointConfiguration"},{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"}]},"docs.ApiReferenceConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},api:{type:"string"},"api-name":{oneOf:[{type:"string"},{type:"null"}]},openrpc:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{$ref:"#/definitions/docs.Audience"},{type:"null"}]},"display-errors":{oneOf:[{type:"boolean"},{type:"null"}]},snippets:{oneOf:[{$ref:"#/definitions/docs.SnippetsConfiguration"},{type:"null"}]},postman:{oneOf:[{type:"string"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},alphabetized:{oneOf:[{type:"boolean"},{type:"null"}]},flattened:{oneOf:[{type:"boolean"},{type:"null"}]},paginated:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["api"],additionalProperties:!1},"docs.ChangelogConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},changelog:{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["changelog"],additionalProperties:!1},"docs.FolderConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},folder:{type:"string"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.Availability"},{type:"null"}]}},required:["folder"],additionalProperties:!1},"docs.NavigationItem":{anyOf:[{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.SectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"},{$ref:"#/definitions/docs.ChangelogConfiguration"},{$ref:"#/definitions/docs.FolderConfiguration"}]},"docs.UntabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},"docs.TabId":{type:"string"},"docs.TabbedNavigationItemWithLayout":{type:"object",properties:{tab:{$ref:"#/definitions/docs.TabId"},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},{type:"null"}]}},required:["tab"],additionalProperties:!1},"docs.TabVariant":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},title:{type:"string"},subtitle:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},layout:{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},slug:{oneOf:[{type:"string"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},default:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["title","layout"],additionalProperties:!1},"docs.TabbedNavigationItemWithVariants":{type:"object",properties:{tab:{$ref:"#/definitions/docs.TabId"},variants:{type:"array",items:{$ref:"#/definitions/docs.TabVariant"}}},required:["tab","variants"],additionalProperties:!1},"docs.TabbedNavigationItem":{anyOf:[{$ref:"#/definitions/docs.TabbedNavigationItemWithLayout"},{$ref:"#/definitions/docs.TabbedNavigationItemWithVariants"}]},"docs.TabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.TabbedNavigationItem"}},"docs.NavigationConfig":{anyOf:[{$ref:"#/definitions/docs.UntabbedNavigationConfig"},{$ref:"#/definitions/docs.TabbedNavigationConfig"}]}},Y7M={type:G7M,properties:H7M,required:J7M,additionalProperties:K7M,definitions:$7M};async function wJo({value:e}){let t=tzt(e,$mc);if(t.success)return{type:"success",contents:v7.RawSchemas.Serializer.ProductFileConfig.parseOrThrow(e)};let r=t.error?.instancePath?` at ${t?.error.instancePath}`:"";return{type:"failure",message:`${t.error?.message??"Failed to parse because JSON schema validation failed"}${r}`}}async function Iz({absoluteFilepathToConfiguration:e,rawUnresolvedFilepath:t,visitor:r,nodePath:i,willBeUploaded:n=!0}){let a=bs(cn(e),t);await r.filepath?.({absoluteFilepath:a,value:t,willBeUploaded:n},[a])}var jMa=require("fs/promises");async function SJo({absolutePathToFernFolder:e,navigation:t,apiWorkspaces:r,visitor:i,absoluteFilepathToConfiguration:n,context:a,nodePath:o}){eHM(t)?await Promise.all(t.map(async(c,f)=>{tHM(c)?await Promise.all(c.layout.map(async(s,u)=>{await EJo({absolutePathToFernFolder:e,navigationItem:s,visitor:i,nodePath:[...o,`${f}`,"layout",`${u}`],absoluteFilepathToConfiguration:n,apiWorkspaces:r,context:a})})):rHM(c)&&await Promise.all(c.variants.flatMap((s,u)=>s.layout.map(async(l,p)=>{await EJo({absolutePathToFernFolder:e,navigationItem:l,visitor:i,nodePath:[...o,`${f}`,"variants",`${u}`,"layout",`${p}`],absoluteFilepathToConfiguration:n,apiWorkspaces:r,context:a})})))})):await Promise.all(t.map(async(c,f)=>{await EJo({absolutePathToFernFolder:e,navigationItem:c,visitor:i,nodePath:[...o,`${f}`],absoluteFilepathToConfiguration:n,apiWorkspaces:r,context:a})}))}async function EJo({absolutePathToFernFolder:e,navigationItem:t,visitor:r,nodePath:i,absoluteFilepathToConfiguration:n,apiWorkspaces:a,context:o}){if(await g8t(t,{alphabetized:It,api:It,apiName:It,audiences:It,openrpc:async c=>{c!=null&&await Iz({absoluteFilepathToConfiguration:n,rawUnresolvedFilepath:c,visitor:r,nodePath:[...i,"openrpc"],willBeUploaded:!1})},displayErrors:It,snippets:It,summary:It,title:It,layout:It,collapsed:It,icon:It,slug:It,hidden:It,skipSlug:It,paginated:It,playground:It,flattened:It,featureFlag:It,postman:It,path:async c=>{c!=null&&await Iz({absoluteFilepathToConfiguration:n,rawUnresolvedFilepath:c,visitor:r,nodePath:[...i,"path"],willBeUploaded:!1})},page:It,contents:async c=>{c!=null&&await Promise.all(c.map(async(f,s)=>{await EJo({absolutePathToFernFolder:e,navigationItem:f,visitor:r,nodePath:[...i,"contents",`${s}`],absoluteFilepathToConfiguration:n,apiWorkspaces:a,context:o})}))},viewers:async c=>{c!=null&&c.length>0&&await r.permissions?.({viewers:c},[...i,"viewers"])},orphaned:It,availability:It}),Z7M(t)){let c=bs(cn(n),t.path);if(await Fi(c)){let f=(await(0,jMa.readFile)(c)).toString();await r.markdownPage?.({title:t.page,content:f,absoluteFilepath:c},[...i,t.path]);try{let{filepaths:s}=W$i(f,{absolutePathToFernFolder:e,absolutePathToMarkdownFile:c});for(let u of s)await r.filepath?.({absoluteFilepath:u,value:Mv(e,u),willBeUploaded:!0},[...i,t.path])}catch{}}}if(k7M(t)){let c=a.find(f=>f.workspaceName===t.apiName);c!=null&&await r.apiSection?.({config:t,workspace:c,context:o},[...i,"api"])}if(X7M(t)){let c=bs(cn(n),t.changelog);if(o.logger.trace(`Starting changelog processing for directory: ${c}`),await Fi(c)){let f=await(0,jMa.readdir)(c);o.logger.trace(`Validating ${f.length} files in changelog directory ${c}`),await Promise.all(f.filter(s=>s.endsWith(".md")||s.endsWith(".mdx")).map(async s=>{let u=bs(c,s),l=(await(0,jMa.readFile)(u)).toString();o.logger.trace(`Validating markdown file: ${u}`),await r.markdownPage?.({title:s,content:l,absoluteFilepath:u},[...i,"changelog",s])}))}else o.logger.trace(`Changelog directory does not exist: ${c}`)}}function X7M(e){return e?.changelog!=null}function Z7M(e){return e?.page!=null}function k7M(e){return e?.api!=null}function eHM(e){return e[0]?.tab!=null}function tHM(e){return"layout"in e&&Array.isArray(e.layout)}function rHM(e){return"variants"in e&&Array.isArray(e.variants)}async function N7_({contents:e,visitor:t,absoluteFilepathToConfiguration:r,context:i,apiWorkspaces:n,absolutePathToFernFolder:a}){await t.file?.({config:e},[]),await g8t(e,{instances:It,analytics:It,aiChat:It,aiSearch:It,pageActions:It,announcement:It,backgroundImage:async o=>{o!=null&&(typeof o=="string"?await Iz({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:o,visitor:t,nodePath:["background-image"]}):(o.dark!=null&&await Iz({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:o.dark,visitor:t,nodePath:["background-image","dark"]}),o.light!=null&&await Iz({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:o.light,visitor:t,nodePath:["background-image","light"]})))},colors:It,css:async o=>{o!=null&&(Array.isArray(o)?await Promise.all(o.map((c,f)=>Iz({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:c,visitor:t,nodePath:["css",`${f}`],willBeUploaded:!1}))):await Iz({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:o,visitor:t,nodePath:["css"],willBeUploaded:!1}))},defaultLanguage:It,experimental:It,favicon:async o=>{o!=null&&await Iz({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:o,visitor:t,nodePath:["favicon"]})},footerLinks:It,integrations:It,js:async o=>{o!=null&&(Array.isArray(o)?await Promise.all(o.map((c,f)=>z7_({absoluteFilepathToConfiguration:r,visitor:t,script:c,nodePath:["js",`${f}`]}))):await z7_({absoluteFilepathToConfiguration:r,visitor:t,script:o,nodePath:["js"]}))},landingPage:It,layout:It,settings:It,logo:async()=>{e.logo?.dark!=null&&await Iz({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:e.logo.dark,visitor:t,nodePath:["logo","dark"]}),e.logo?.light!=null&&await Iz({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:e.logo.light,visitor:t,nodePath:["logo","light"]})},metadata:It,navbarLinks:It,navigation:async o=>{o!=null&&await SJo({absolutePathToFernFolder:a,navigation:o,visitor:t,nodePath:["navigation"],absoluteFilepathToConfiguration:r,apiWorkspaces:n,context:i})},products:async o=>{o!=null&&await Promise.all(o.map(async(c,f)=>{if("path"in c){await Iz({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:c.path,visitor:t,nodePath:["products",`${f}`],willBeUploaded:!1});let s=bs(cn(r),c.path),u=Gi.load((await(0,Xmc.readFile)(s)).toString());await Fi(s)&&await t.productFile?.({path:c.path,content:u},[c.path]);let l=await wJo({value:u});l.type==="success"&&await SJo({absolutePathToFernFolder:a,navigation:l.contents.navigation,visitor:t,nodePath:["navigation"],absoluteFilepathToConfiguration:s,apiWorkspaces:n,context:i})}}))},redirects:It,tabs:It,title:It,typography:async o=>{o!=null&&await g8t(o,{bodyFont:async c=>{c!=null&&await Ymc({absoluteFilepathToConfiguration:r,visitor:t,font:c,nodePath:["typography","bodyFont"]})},codeFont:async c=>{c!=null&&await Ymc({absoluteFilepathToConfiguration:r,visitor:t,font:c,nodePath:["typography","codeFont"]})},headingsFont:async c=>{c!=null&&await Ymc({absoluteFilepathToConfiguration:r,visitor:t,font:c,nodePath:["typography","headingsFont"]})}})},versions:async o=>{o!=null&&await Promise.all(o.map(async(c,f)=>{await Iz({absoluteFilepathToConfiguration:r,rawUnresolvedFilepath:c.path,visitor:t,nodePath:["versions",`${f}`],willBeUploaded:!1});let s=bs(cn(r),c.path),u=Gi.load((await(0,Xmc.readFile)(s)).toString());await Fi(s)&&await t.versionFile?.({path:c.path,content:u},[c.path]);let l=await jJo({value:u});l.type==="success"&&await SJo({absolutePathToFernFolder:a,navigation:l.contents.navigation,visitor:t,nodePath:["navigation"],absoluteFilepathToConfiguration:s,apiWorkspaces:n,context:i})}))},roles:It,languages:It,theme:It})}async function Ymc({absoluteFilepathToConfiguration:e,visitor:t,font:r,nodePath:i}){r.path!=null&&await Iz({absoluteFilepathToConfiguration:e,rawUnresolvedFilepath:r.path,visitor:t,nodePath:i,willBeUploaded:!0});for(let n of r.paths??[])typeof n=="string"?await Iz({absoluteFilepathToConfiguration:e,rawUnresolvedFilepath:n,visitor:t,nodePath:i,willBeUploaded:!0}):await Iz({absoluteFilepathToConfiguration:e,rawUnresolvedFilepath:n.path,visitor:t,nodePath:i,willBeUploaded:!0})}async function z7_({absoluteFilepathToConfiguration:e,visitor:t,script:r,nodePath:i}){let n=typeof r=="string"?r:"path"in r?r.path:null;n&&await Iz({absoluteFilepathToConfiguration:e,rawUnresolvedFilepath:n,visitor:t,nodePath:i,willBeUploaded:!0})}var qMa={};Kt(qMa,{AccentColorContrastRule:()=>Zmc,AllRolesMustBeDeclaredRule:()=>kmc,FilepathsExistRule:()=>MJo,OnlyVersionedNavigation:()=>DJo,TabWithHrefRule:()=>nHM,ValidDocsEndpoints:()=>BJo,ValidFileTypes:()=>zJo,ValidFrontmatter:()=>NJo,ValidMarkdownFileReferences:()=>UJ_,ValidMarkdownLinks:()=>F1i,ValidMarkdownRule:()=>NJ_,ValidateProductFileRule:()=>nKo,ValidateVersionFileRule:()=>aKo,enforceBackgroundTheme:()=>F7_,validateTheme:()=>wMa});var Zmc={name:"accent-color-contrast",create:()=>({file:async({config:e})=>{if(e.colors==null)return[];let t=yso(e.colors);return t==="dark"?wMa(e.colors,"dark"):t==="light"?wMa(e.colors,"light"):t==="darkAndLight"?[...wMa(e.colors,"dark"),...wMa(e.colors,"light")]:[]}})};function wMa(e,t){let r=Qpa(e.accentPrimary??e.accentPrimaryDeprecated,"accent-primary",t),i=Qpa(e.background,"background",t)??(t==="dark"?"#000":"#FFF"),n=[];if(!Oo(i).isValid())n.push({severity:"fatal",message:`Invalid background color provided for colors.background.${t}: ${i}.`});else{let a=F7_(Oo(i),t);Oo(i).toHexString()!==a.toHexString()&&n.push({severity:"warning",message:`The provided background color for ${t} mode is not ${t} enough. It will be adjusted to ${a.toHexString()}.`}),i=a.toHexString()}if(r==null)n.push({severity:"warning",message:`No accent-color provided for ${t} mode. A random color will be used.`});else if(!Oo(r).isValid())n.push({severity:"fatal",message:`Invalid accent-color provided for colors.accent-primary.${t}: ${r}.`});else{let a=Oo.readability(r,i),o=`${a.toFixed(2)}:1`;a<3?n.push({severity:"warning",message:`The contrast ratio between the accent color and the background color for ${t} mode is ${o}. It should be at least 3:1.`}):a<4.5?n.push({severity:"warning",message:`The contrast ratio between the accent color and the background color for ${t} mode is ${o}. Fern will adjust the color to meet the minimum contrast ratio of 4.5:1 for WCAG AA and 7:1 for WCAG AAA.`}):a<7&&n.push({severity:"warning",message:`The contrast ratio between the accent color and the background color for ${t} mode is ${o}. Fern will adjust the color to meet the minimum contrast ratio of 7:1 for WCAG AAA.`})}return n}function F7_(e,t){return t==="dark"&&e.isDark()||t==="light"&&e.isLight()?e:iHM(e)}function iHM(e){if(e==null)return;let{h:t,s:r,v:i}=e.toHsv();return Oo({h:t,s:r,v:1-i})}var kmc={name:"all-roles-must-be-declared",create:e=>{let t=e.workspace.config.roles;return{permissions:r=>{let i=[...r.viewers??[]],n=[];for(let a of i)(t==null||!t.includes(a))&&n.push({severity:"fatal",message:`Role "${a}" is used but not declared at the top level of the docs.yml file.`});return n}}}};var MJo={name:"filepaths-exist",create:()=>({filepath:async({absoluteFilepath:e,value:t})=>await Fi(e)?[]:[{severity:"fatal",message:`Path ${t} does not exist`}]})};var DJo={name:"only-versioned-navigation",create:()=>({file:async({config:e})=>e.navigation!=null&&e.versions!=null?[{severity:"fatal",message:"Cannot contain both navigation and versions. If you want versioned docs, use versions. Otherwise use navigation."}]:[]})};var nHM={name:"tab-with-href",create:()=>({file:async({config:e})=>{let t=e.tabs??{};if(e.navigation==null)return[];let r=[];if(aHM(e.navigation))for(let i of e.navigation){let n=t[i.tab];if(n==null){r.push({severity:"fatal",message:`Tab "${i.tab}" is missing from the tabs configuration.`});continue}let a=oHM(i),o=uHM(i);if(n.href!=null&&(a||o)){r.push({severity:"fatal",message:`Tab "${i.tab}" has both a href and ${a?"layout":"variants"}. Only one should be used.`});continue}if(n.href==null&&!a&&!o){r.push({severity:"fatal",message:`Tab "${i.tab}" is missing a href, layout, or variants.`});continue}}return[]}})};function aHM(e){return Array.isArray(e)&&e.length>0&&e[0].tab!=null}function oHM(e){return"layout"in e&&Array.isArray(e.layout)}function uHM(e){return"variants"in e&&Array.isArray(e.variants)}var BJo={name:"valid-docs-endpoints",create:()=>({file:async({config:e})=>!e.analytics||!Object.keys(e.analytics).length?[]:[[e.analytics.intercom?.apiBase,"Intercom API Base"],[e.analytics.posthog?.endpoint,"Posthog Host Endpoint"]].filter(([i])=>i&&!sHM(i)).map(([i,n])=>({severity:"warning",message:`${n} <${i}> is malformed. Make sure it includes a protocol (e.g. 'https://')!`}))})};function sHM(e){try{return!!new URL(e).protocol}catch{return!1}}var rH_=re(n7s(),1);var wHM=require("stream/web"),o0c=require("stream");var pHM=require("fs/promises");var cHM="End-Of-Stream",o0=class extends Error{constructor(){super(cHM)}};var EMa=class{constructor(){this.maxStreamReadSize=1*1024*1024,this.endOfStream=!1,this.peekQueue=[]}async peek(t,r,i){let n=await this.read(t,r,i);return this.peekQueue.push(t.subarray(r,r+n)),n}async read(t,r,i){if(i===0)return 0;let n=this.readFromPeekBuffer(t,r,i);if(n+=await this.readRemainderFromStream(t,r+n,i-n),n===0)throw new o0;return n}readFromPeekBuffer(t,r,i){let n=i,a=0;for(;this.peekQueue.length>0&&n>0;){let o=this.peekQueue.pop();if(!o)throw new Error("peekData should be defined");let c=Math.min(o.length,n);t.set(o.subarray(0,c),r+a),a+=c,n-=c,c<o.length&&this.peekQueue.push(o.subarray(c))}return a}async readRemainderFromStream(t,r,i){let n=i,a=0;for(;n>0&&!this.endOfStream;){let o=Math.min(n,this.maxStreamReadSize),c=await this.readFromStream(t,r+a,o);if(c===0)break;a+=c,n-=c}return a}};var SMa=class extends EMa{constructor(t){super(),this.reader=t.getReader({mode:"byob"})}async readFromStream(t,r,i){if(this.endOfStream)throw new o0;let n=await this.reader.read(new Uint8Array(i));return n.done&&(this.endOfStream=n.done),n.value?(t.set(n.value,r),n.value.byteLength):0}abort(){return this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};var sOi=class{constructor(t){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=t?.onClose,t?.abortSignal&&t.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(t,r=this.position){let i=new Uint8Array(t.len);if(await this.readBuffer(i,{position:r})<t.len)throw new o0;return t.get(i,0)}async peekToken(t,r=this.position){let i=new Uint8Array(t.len);if(await this.peekBuffer(i,{position:r})<t.len)throw new o0;return t.get(i,0)}async readNumber(t){if(await this.readBuffer(this.numBuffer,{length:t.len})<t.len)throw new o0;return t.get(this.numBuffer,0)}async peekNumber(t){if(await this.peekBuffer(this.numBuffer,{length:t.len})<t.len)throw new o0;return t.get(this.numBuffer,0)}async ignore(t){if(this.fileInfo.size!==void 0){let r=this.fileInfo.size-this.position;if(t>r)return this.position+=r,r}return this.position+=t,t}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(t,r){if(r&&r.position!==void 0&&r.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return r?{mayBeLess:r.mayBeLess===!0,offset:r.offset?r.offset:0,length:r.length?r.length:t.length-(r.offset?r.offset:0),position:r.position?r.position:this.position}:{mayBeLess:!1,offset:0,length:t.length,position:this.position}}abort(){return Promise.resolve()}};var fHM=256e3,IJo=class extends sOi{constructor(t,r){super(r),this.streamReader=t,this.fileInfo=r?.fileInfo??{}}async readBuffer(t,r){let i=this.normalizeOptions(t,r),n=i.position-this.position;if(n>0)return await this.ignore(n),this.readBuffer(t,r);if(n<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(i.length===0)return 0;let a=await this.streamReader.read(t,i.offset,i.length);if(this.position+=a,(!r||!r.mayBeLess)&&a<i.length)throw new o0;return a}async peekBuffer(t,r){let i=this.normalizeOptions(t,r),n=0;if(i.position){let a=i.position-this.position;if(a>0){let o=new Uint8Array(i.length+a);return n=await this.peekBuffer(o,{mayBeLess:i.mayBeLess}),t.set(o.subarray(a),i.offset),n-a}if(a<0)throw new Error("Cannot peek from a negative offset in a stream")}if(i.length>0){try{n=await this.streamReader.peek(t,i.offset,i.length)}catch(a){if(r?.mayBeLess&&a instanceof o0)return 0;throw a}if(!i.mayBeLess&&n<i.length)throw new o0}return n}async ignore(t){let r=Math.min(fHM,t),i=new Uint8Array(r),n=0;for(;n<t;){let a=t-n,o=await this.readBuffer(i,{length:Math.min(r,a)});if(o<0)return o;n+=o}return n}abort(){return this.streamReader.abort()}supportsRandomAccess(){return!1}};var CJo=class extends sOi{constructor(t,r){super(r),this.uint8Array=t,this.fileInfo={...r?.fileInfo??{},size:t.length}}async readBuffer(t,r){if(r?.position){if(r.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");this.position=r.position}let i=await this.peekBuffer(t,r);return this.position+=i,i}async peekBuffer(t,r){let i=this.normalizeOptions(t,r),n=Math.min(this.uint8Array.length-i.position,i.length);if(!i.mayBeLess&&n<i.length)throw new o0;return t.set(this.uint8Array.subarray(i.position,i.position+n),i.offset),n}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(t){this.position=t}};function e0c(e,t){return new IJo(new SMa(e),t)}function Q7_(e,t){return new CJo(e,t)}var U7_=require("fs/promises"),MMa=class e extends sOi{static async fromFile(t){let r=await(0,U7_.open)(t,"r"),i=await r.stat();return new e(r,{fileInfo:{path:t,size:i.size}})}constructor(t,r){super(r),this.fileHandle=t,this.fileInfo=r.fileInfo}async readBuffer(t,r){let i=this.normalizeOptions(t,r);if(this.position=i.position,i.length===0)return 0;let n=await this.fileHandle.read(t,i.offset,i.length,i.position);if(this.position+=n.bytesRead,n.bytesRead<i.length&&(!r||!r.mayBeLess))throw new o0;return n.bytesRead}async peekBuffer(t,r){let i=this.normalizeOptions(t,r),n=await this.fileHandle.read(t,i.offset,i.length,i.position);if(!i.mayBeLess&&n.bytesRead<i.length)throw new o0;return n.bytesRead}async close(){return await this.fileHandle.close(),super.close()}setPosition(t){this.position=t}supportsRandomAccess(){return!0}};var _HM=MMa.fromFile;var W7_=re(L7_(),1);var r0c={128:"\u20AC",130:"\u201A",131:"\u0192",132:"\u201E",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02C6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017D",145:"\u2018",146:"\u2019",147:"\u201C",148:"\u201D",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02DC",153:"\u2122",154:"\u0161",155:"\u203A",156:"\u0153",158:"\u017E",159:"\u0178"},yHM={};for(let[e,t]of Object.entries(r0c))yHM[t]=Number.parseInt(e);function V7_(e,t="utf-8"){switch(t.toLowerCase()){case"utf-8":case"utf8":return typeof globalThis.TextDecoder<"u"?new globalThis.TextDecoder("utf-8").decode(e):bHM(e);case"utf-16le":return vHM(e);case"ascii":return gHM(e);case"latin1":case"iso-8859-1":return OHM(e);case"windows-1252":return AHM(e);default:throw new RangeError(`Encoding '${t}' not supported`)}}function bHM(e){let t="",r=0;for(;r<e.length;){let i=e[r++];if(i<128)t+=String.fromCharCode(i);else if(i<224){let n=e[r++]&63;t+=String.fromCharCode((i&31)<<6|n)}else if(i<240){let n=e[r++]&63,a=e[r++]&63;t+=String.fromCharCode((i&15)<<12|n<<6|a)}else{let n=e[r++]&63,a=e[r++]&63,o=e[r++]&63,c=(i&7)<<18|n<<12|a<<6|o;c-=65536,t+=String.fromCharCode(55296+(c>>10&1023),56320+(c&1023))}}return t}function vHM(e){let t="";for(let r=0;r<e.length;r+=2)t+=String.fromCharCode(e[r]|e[r+1]<<8);return t}function gHM(e){return String.fromCharCode(...e.map(t=>t&127))}function OHM(e){return String.fromCharCode(...e)}function AHM(e){let t="";for(let r of e)r>=128&&r<=159&&r0c[r]?t+=r0c[r]:t+=String.fromCharCode(r);return t}function AJ(e){return new DataView(e.buffer,e.byteOffset)}var x7_={len:1,get(e,t){return AJ(e).getUint8(t)},put(e,t,r){return AJ(e).setUint8(t,r),t+1}},qJo={len:2,get(e,t){return AJ(e).getUint16(t,!0)},put(e,t,r){return AJ(e).setUint16(t,r,!0),t+2}},TJo={len:2,get(e,t){return AJ(e).getUint16(t)},put(e,t,r){return AJ(e).setUint16(t,r),t+2}};var G7_={len:4,get(e,t){return AJ(e).getUint32(t,!0)},put(e,t,r){return AJ(e).setUint32(t,r,!0),t+4}},H7_={len:4,get(e,t){return AJ(e).getUint32(t)},put(e,t,r){return AJ(e).setUint32(t,r),t+4}};var J7_={len:4,get(e,t){return AJ(e).getInt32(t)},put(e,t,r){return AJ(e).setInt32(t,r),t+4}};var K7_={len:8,get(e,t){return AJ(e).getBigUint64(t,!0)},put(e,t,r){return AJ(e).setBigUint64(t,r,!0),t+8}};var Zhe=class{constructor(t,r){this.len=t,this.encoding=r}get(t,r=0){let i=t.subarray(r,r+this.len);return V7_(i,this.encoding)}};var Hn9={utf8:new globalThis.TextDecoder("utf8")};var Jn9=new globalThis.TextEncoder;var Kn9=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function i0c(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function n0c(e,t){let r=e.length,i=t.length;if(i===0||i>r)return-1;let n=r-i;for(let a=0;a<=n;a++){let o=!0;for(let c=0;c<i;c++)if(e[a+c]!==t[c]){o=!1;break}if(o)return a}return-1}function $7_(e,t){return n0c(e,t)!==-1}function Y7_(e){return[...e].map(t=>t.charCodeAt(0))}function X7_(e,t=0){let r=Number.parseInt(new Zhe(6).get(e,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(r))return!1;let i=256;for(let n=t;n<t+148;n++)i+=e[n];for(let n=t+156;n<t+512;n++)i+=e[n];return r===i}var Z7_={get:(e,t)=>e[t+3]&127|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4};var k7_=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","ai","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk"],eH_=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/x-apache-arrow","video/mp4","audio/midi","video/x-matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/x-flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/x-parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive"];var tH_=4100;async function a0c(e){return new RJo().fromBuffer(e)}function _5t(e,t,r){r={offset:0,...r};for(let[i,n]of t.entries())if(r.mask){if(n!==(r.mask[i]&e[i+r.offset]))return!1}else if(n!==e[i+r.offset])return!1;return!0}var RJo=class{constructor(t){this.detectors=t?.customDetectors,this.tokenizerOptions={abortSignal:t?.signal},this.fromTokenizer=this.fromTokenizer.bind(this),this.fromBuffer=this.fromBuffer.bind(this),this.parse=this.parse.bind(this)}async fromTokenizer(t){let r=t.position;for(let i of this.detectors||[]){let n=await i(t);if(n)return n;if(r!==t.position)return}return this.parse(t)}async fromBuffer(t){if(!(t instanceof Uint8Array||t instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof t}\``);let r=t instanceof Uint8Array?t:new Uint8Array(t);if(r?.length>1)return this.fromTokenizer(Q7_(r,this.tokenizerOptions))}async fromBlob(t){return this.fromStream(t.stream())}async fromStream(t){let r=await e0c(t,this.tokenizerOptions);try{return await this.fromTokenizer(r)}finally{await r.close()}}async toDetectionStream(t,r){let{sampleSize:i=tH_}=r,n,a,o=t.getReader({mode:"byob"});try{let{value:s,done:u}=await o.read(new Uint8Array(i));if(a=s,!u&&s)try{n=await this.fromBuffer(s.slice(0,i))}catch(l){if(!(l instanceof o0))throw l;n=void 0}a=s}finally{o.releaseLock()}let c=new TransformStream({async start(s){s.enqueue(a)},transform(s,u){u.enqueue(s)}}),f=t.pipeThrough(c);return f.fileType=n,f}check(t,r){return _5t(this.buffer,t,r)}checkString(t,r){return this.check(Y7_(t),r)}async parse(t){if(this.buffer=new Uint8Array(tH_),t.fileInfo.size===void 0&&(t.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=t,await t.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await t.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.parse(t);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await t.ignore(6);let r=await t.readToken(Z7_);return t.position+r>t.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await t.ignore(r),this.fromTokenizer(t))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){try{for(;t.position+30<t.fileInfo.size;){await t.readBuffer(this.buffer,{length:30});let r=new DataView(this.buffer.buffer),i={compressedSize:r.getUint32(18,!0),uncompressedSize:r.getUint32(22,!0),filenameLength:r.getUint16(26,!0),extraFieldLength:r.getUint16(28,!0)};if(i.filename=await t.readToken(new Zhe(i.filenameLength,"utf-8")),await t.ignore(i.extraFieldLength),/classes\d*\.dex/.test(i.filename))return{ext:"apk",mime:"application/vnd.android.package-archive"};if(i.filename==="META-INF/mozilla.rsa")return{ext:"xpi",mime:"application/x-xpinstall"};if(i.filename.endsWith(".rels")||i.filename.endsWith(".xml"))switch(i.filename.split("/")[0]){case"_rels":break;case"word":return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};case"ppt":return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};case"xl":return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};case"visio":return{ext:"vsdx",mime:"application/vnd.visio"};default:break}if(i.filename.startsWith("xl/"))return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};if(i.filename.startsWith("3D/")&&i.filename.endsWith(".model"))return{ext:"3mf",mime:"model/3mf"};if(i.filename==="mimetype"&&i.compressedSize===i.uncompressedSize){let n=await t.readToken(new Zhe(i.compressedSize,"utf-8"));switch(n=n.trim(),n){case"application/epub+zip":return{ext:"epub",mime:"application/epub+zip"};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:"application/vnd.oasis.opendocument.text"};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:"application/vnd.oasis.opendocument.spreadsheet"};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:"application/vnd.oasis.opendocument.presentation"};default:}}if(i.compressedSize===0){let n=-1;for(;n<0&&t.position<t.fileInfo.size;)await t.peekBuffer(this.buffer,{mayBeLess:!0}),n=n0c(this.buffer,new Uint8Array([80,75,3,4])),await t.ignore(n>=0?n:this.buffer.length)}else await t.ignore(i.compressedSize)}}catch(r){if(!(r instanceof o0))throw r}return{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await t.ignore(28);let r=new Uint8Array(8);return await t.readBuffer(r),_5t(r,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:_5t(r,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:_5t(r,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:_5t(r,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:_5t(r,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:_5t(r,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("ftyp",{offset:4})&&(this.buffer[8]&96)!==0){let r=new Zhe(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(r){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return r.startsWith("3g")?r.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/x-flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF")){try{await t.ignore(1350);let r=10*1024*1024,i=new Uint8Array(Math.min(r,t.fileInfo.size));if(await t.readBuffer(i,{mayBeLess:!0}),$7_(i,new TextEncoder().encode("AIPrivateData")))return{ext:"ai",mime:"application/postscript"}}catch(r){if(!(r instanceof o0))throw r}return{ext:"pdf",mime:"application/pdf"}}if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let r=await this.readTiffHeader(!1);if(r)return r}if(this.check([77,77])){let r=await this.readTiffHeader(!0);if(r)return r}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function r(){let c=await t.peekNumber(x7_),f=128,s=0;for(;(c&f)===0&&f!==0;)++s,f>>=1;let u=new Uint8Array(s+1);return await t.readBuffer(u),u}async function i(){let c=await r(),f=await r();f[0]^=128>>f.length-1;let s=Math.min(6,f.length),u=new DataView(c.buffer),l=new DataView(f.buffer,f.length-s,s);return{id:i0c(u),len:i0c(l)}}async function n(c){for(;c>0;){let f=await i();if(f.id===17026)return(await t.readToken(new Zhe(f.len))).replaceAll(/\00.*$/g,"");await t.ignore(f.len),--c}}let a=await i();switch(await n(a.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/x-matroska"};default:return}}if(this.check([82,73,70,70])){if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1"))return{ext:"parquet",mime:"application/x-parquet"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){let r=new Zhe(4,"latin1").get(this.buffer,2);if(r.match("^d*")&&r>=1e3&&r<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>"))return await t.ignore(8),await t.readToken(new Zhe(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[`
|
|
1806
1806
|
`,"\r"," "," ","\0"].some(r=>this.checkString(r,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){await t.ignore(8);async function r(){return{length:await t.readToken(J7_),type:await t.readToken(new Zhe(4,"latin1"))}}do{let i=await r();if(i.length<0)return;switch(i.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await t.ignore(i.length+4)}}while(t.position+8<t.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/x-apache-arrow"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function r(){let i=new Uint8Array(16);return await t.readBuffer(i),{id:i,size:Number(await t.readToken(K7_))}}for(await t.ignore(30);t.position+24<t.fileInfo.size;){let i=await r(),n=i.size-24;if(_5t(i.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let a=new Uint8Array(16);if(n-=await t.readBuffer(a),_5t(a,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(_5t(a,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await t.ignore(n)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await t.ignore(20),await t.readToken(new Zhe(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await t.peekBuffer(this.buffer,{length:Math.min(256,t.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){let r=new DataView(this.buffer.buffer).getUint32(12,!0);if(r>12&&this.buffer.length>=r+16)try{let i=new TextDecoder().decode(this.buffer.slice(16,r+16));if(JSON.parse(i).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await t.peekBuffer(this.buffer,{length:Math.min(512,t.fileInfo.size),mayBeLess:!0}),X7_(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0;if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"};if(this.buffer.length>=2&&this.check([255,224],{offset:0,mask:[255,224]})){if(this.check([16],{offset:1,mask:[22]}))return this.check([8],{offset:1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}async readTiffTag(t){let r=await this.tokenizer.readToken(t?TJo:qJo);switch(this.tokenizer.ignore(10),r){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(t){let r=await this.tokenizer.readToken(t?TJo:qJo);for(let i=0;i<r;++i){let n=await this.readTiffTag(t);if(n)return n}}async readTiffHeader(t){let r=(t?TJo:qJo).get(this.buffer,2),i=(t?H7_:G7_).get(this.buffer,4);if(r===42){if(i>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(i>=8&&(this.check([28,0,254,0],{offset:8})||this.check([31,0,11,0],{offset:8})))return{ext:"nef",mime:"image/x-nikon-nef"}}return await this.tokenizer.ignore(i),await this.readTiffIFD(t)??{ext:"tif",mime:"image/tiff"}}if(r===43)return{ext:"tif",mime:"image/tiff"}}},PHM=new Set(k7_),jHM=new Set(eH_);var iH_=require("fs/promises"),nH_=re(require("path"),1),EHM=new Set(["image/jpeg","image/png","image/gif","image/webp","image/tiff","image/x-icon","image/avif","video/quicktime","video/mp4","video/webm","audio/mpeg","audio/ogg","audio/wav","application/pdf","application/xml","font/woff","font/woff2","font/otf","font/ttf"]),SHM=new Set(["ASCII","UTF-8","UTF-16","ISO-8859-1","ISO-8859-2","ISO-8859-3","ISO-8859-4","ISO-8859-5","ISO-8859-6","ISO-8859-7","ISO-8859-8","ISO-8859-9","ISO-8859-10","ISO-8859-13","ISO-8859-14","ISO-8859-15","ISO-8859-16","WINDOWS-1250","WINDOWS-1251","WINDOWS-1252","WINDOWS-1253","WINDOWS-1254","WINDOWS-1255","WINDOWS-1256","WINDOWS-1257","WINDOWS-1258","SHIFT_JIS","SHIFT-JIS","EUC-JP","ISO-2022-JP","BIG5","GB2312","GB18030","KOI8-R"]),zJo={name:"valid-file-types",create:()=>({filepath:async({absoluteFilepath:e,willBeUploaded:t})=>t?await Fi(e)?MHM(e):[]:[]})},MHM=async e=>{let t=new Uint8Array(await(0,iH_.readFile)(e)),r=await a0c(t);if(r!=null)return EHM.has(r.mime)?[]:[{severity:"fatal",message:`The file type of ${r.mime} is not allowed: ${e}`}];let i=nH_.default.extname(e).toLowerCase();i.startsWith(".")&&(i=i.substring(1));let n=rH_.default.detect(t);return n==null?[{severity:"fatal",message:`The encoding of the file could not be detected: ${e}`}]:SHM.has(n.toUpperCase())?[]:[{severity:"fatal",message:`The encoding of ${n} is not allowed: ${e}`}]};var aH_=require("fs/promises"),oH_=re(R_e(),1),NJo={name:"valid-frontmatter",create:()=>({filepath:async({absoluteFilepath:e})=>{if(!e.endsWith(".md")&&!e.endsWith(".mdx"))return[];try{let t=await(0,aH_.readFile)(e,"utf-8");return(0,oH_.default)(t),[]}catch(t){return[{severity:"fatal",message:`Failed to parse frontmatter${t instanceof Error?`: ${t.message}`:""}`}]}}})};var DHM=["md","markdown","mdown","mkdn","mkd","mdwn","mkdown","ron"],uH_=DHM;var sH_=uH_.map(function(e){return"."+e});function cH_(e,t){let r=BHM(e)?e:new d0e(e),{format:i,...n}=t||{};return{file:r,options:{format:i==="md"||i==="mdx"?i:r.extname&&(n.mdExtensions||sH_).includes(r.extname)?"md":"mdx",...n}}}function BHM(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}var u0c=/@(jsx|jsxFrag|jsxImportSource|jsxRuntime)\s+(\S+)/g;function s0c(e,t){let r=t||{},i=r.runtime==="automatic",n={},a={};QC(e,{enter(o){if(o.type==="Program"){let c=o.comments||[],f=-1;for(;++f<c.length;){u0c.lastIndex=0;let s=u0c.exec(c[f].value);for(;s;)n[s[1]]=s[2],s=u0c.exec(c[f].value)}if(n.jsxRuntime)if(n.jsxRuntime==="automatic"){if(i=!0,n.jsx)throw new Error("Unexpected `@jsx` pragma w/ automatic runtime");if(n.jsxFrag)throw new Error("Unexpected `@jsxFrag` pragma w/ automatic runtime")}else if(n.jsxRuntime==="classic"){if(i=!1,n.jsxImportSource)throw new Error("Unexpected `@jsxImportSource` w/ classic runtime")}else throw new Error("Unexpected `jsxRuntime` `"+n.jsxRuntime+"`, expected `automatic` or `classic`")}},leave(o){if(o.type==="Program"){let y=[];if(a.fragment&&y.push({type:"ImportSpecifier",imported:{type:"Identifier",name:"Fragment"},local:{type:"Identifier",name:"_Fragment"}}),a.jsx&&y.push({type:"ImportSpecifier",imported:{type:"Identifier",name:"jsx"},local:{type:"Identifier",name:"_jsx"}}),a.jsxs&&y.push({type:"ImportSpecifier",imported:{type:"Identifier",name:"jsxs"},local:{type:"Identifier",name:"_jsxs"}}),a.jsxDEV&&y.push({type:"ImportSpecifier",imported:{type:"Identifier",name:"jsxDEV"},local:{type:"Identifier",name:"_jsxDEV"}}),y.length>0){let b=0;for(;b<o.body.length;){let v=o.body[b];if("directive"in v&&v.directive)b++;else break}o.body.splice(b,0,{type:"ImportDeclaration",specifiers:y,source:{type:"Literal",value:(n.jsxImportSource||r.importSource||"react")+(r.development?"/jsx-dev-runtime":"/jsx-runtime")}})}}if(o.type!=="JSXElement"&&o.type!=="JSXFragment")return;let c=[],f=-1;for(;++f<o.children.length;){let y=o.children[f];if(y.type==="JSXExpressionContainer")y.expression.type!=="JSXEmptyExpression"&&c.push(y.expression);else if(y.type==="JSXText"){let b=y.value.replace(/\t/g," ").replace(/ *(\r?\n|\r) */g,`
|