fern-api 3.64.6 → 3.65.0
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 +5 -5
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1355,7 +1355,7 @@ ${BYh.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&g3c(th
|
|
|
1355
1355
|
`+hAn.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?hAn.default.cyan(UYh(t,this.opt.mask)):hAn.default.italic(hAn.default.dim("[hidden]")):this.opt.mask?UYh(t,this.opt.mask):hAn.default.italic(hAn.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 onu=ce(ON(),1);var QXh=ce(eWc(),1),nnu=require("child_process"),Xca=require("fs"),inu=ce(require("path"),1),UXh=ce(require("os"),1),LXh=require("crypto"),FWc=ce(NXh(),1);var enu=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var Q2a=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var tnu=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var rnu=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function anu(e="",t,r){let i=new QWc(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 FXh(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function xVD(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 QWc=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=xVD(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??UXh.default.tmpdir(),r=(0,LXh.randomUUID)(),i=FXh(this.fileOptions.prefix),n=FXh(this.fileOptions.postfix),a=`${i}${r}${n}`,o=inu.default.resolve(t,a),c=inu.default.resolve(t)+inu.default.sep;if(!o.startsWith(c))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=o;let d={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(d.mode=this.fileOptions.mode),(0,Xca.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new enu(t)}}readTemporaryFile(){try{let t=(0,Xca.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,QXh.detect)(t)??"utf8";FWc.default.encodingExists(r)||(r="utf8"),this.text=FWc.default.decode(t,r)}}catch(t){throw new tnu(t)}}removeTemporaryFile(){try{(0,Xca.unlinkSync)(this.tempFile)}catch(t){throw new rnu(t)}}launchEditor(){try{let t=(0,nnu.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new Q2a(t)}}launchEditorAsync(t){try{(0,nnu.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new Q2a(r)}}};var VXh=ce(Fme(),1);var U2a=class extends mN{_run(t){this.done=t,this.editorResult=new VXh.Subject;let r=S3(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"?onu.default.dim("Received"):onu.default.dim("Press <enter> to launch your preferred editor."),t&&(r=onu.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),anu(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 KXh=require("stream");var HXh=ce(require("readline"),1),GXh=ce(xXh(),1),vAn=class{constructor(t){this.rl||=HXh.default.createInterface(GVD(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 GVD(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 GXh.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var L2a=class extends vAn{constructor(t={}){super(t),this.log=new KXh.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return j2a(this.rl,this.bottomBar.split(`
|
|
1356
1356
|
`).length),this}updateBottomBar(t){return j2a(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+`
|
|
1357
1357
|
`}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&&Miu(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var oA=ce(Fme(),1),YXh=ce(HZa(),1);var unu=ce(Fme(),1),$Xh=ce(HZa(),1),snu=function(e,t,r){return typeof e[t]!="function"?(0,unu.of)(e):(0,unu.from)((0,$Xh.default)(e[t])(r).then(i=>(e[t]=i,e)))};var JXh={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}},Zca=class extends vAn{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,oA.from)(t):(0,oA.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,oA.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,oA.from)([t]),this.process=i.pipe((0,oA.concatMap)(this.processQuestion.bind(this)),(0,oA.publish)()),this.process.connect(),this.process.pipe((0,oA.reduce)((n,a)=>(JXh.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,oA.defer)(()=>(0,oA.of)(t).pipe((0,oA.concatMap)(this.setDefaultType.bind(this)),(0,oA.concatMap)(this.filterIfRunnable.bind(this)),(0,oA.concatMap)(()=>snu(t,"message",this.answers)),(0,oA.concatMap)(()=>snu(t,"default",this.answers)),(0,oA.concatMap)(()=>snu(t,"choices",this.answers)),(0,oA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,oA.defer)(()=>(0,oA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,oA.defer)(()=>(0,oA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&JXh.get(this.answers,t.name)!==void 0)return oA.EMPTY;if(t.when===!1)return oA.EMPTY;if(typeof t.when!="function")return(0,oA.of)(t);let{answers:r}=this;return(0,oA.defer)(()=>(0,oA.from)((0,YXh.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,oA.filter)(i=>i!=null)))}};function XXh(e){let t=function(r,i){let n;try{n=new Zca(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",E2a),this.registerPrompt("input",pAn),this.registerPrompt("number",S2a),this.registerPrompt("confirm",M2a),this.registerPrompt("rawlist",D2a),this.registerPrompt("expand",I2a),this.registerPrompt("checkbox",B2a),this.registerPrompt("password",C2a),this.registerPrompt("editor",U2a)},t.restoreDefaultPrompts(),t}var LWc=XXh();function $VD(e,t){LWc.registerPrompt(e,t)}function JVD(){LWc.restoreDefaultPrompts()}var YVD={prompt:LWc,ui:{BottomBar:L2a,Prompt:Zca},createPromptModule:XXh,registerPrompt:$VD,restoreDefaultPrompts:JVD,Separator:SZ},w5t=YVD;var kca=require("path");function kXh(){let e=XVD();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function XVD(e=process.argv[1]?(0,kca.dirname)(process.argv[1]):process.cwd(),t=kca.sep==="\\"){let r=t?ZXh(e):e;return i=>{if(!i)return;let n=t?ZXh(i):i,{dir:a,base:o,ext:c}=kca.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,-1*c.length));let d=decodeURIComponent(o);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let u=a.slice(r.length+1).replace(/\//g,".");return u?`${u}:${d}`:d}return d}}function ZXh(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var VWc=e=>{if("flags"in e){let t=eZh(e.flags),r=tZh(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,rZh(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,ZVD(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function ZVD(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 eZh=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,V2a(r)]).filter(([,t])=>t!==void 0)),tZh=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?rZh(i):void 0]}))};var V2a=e=>e===void 0?void 0:e.variant??e.enabled,rZh=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var cnu="0123456789abcdef",lnu=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length===16)return new e(t);throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,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/256,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;default: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)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=cnu.charAt(this.bytes[r]>>>4),t+=cnu.charAt(15&this.bytes[r]),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=cnu.charAt(this.bytes[r]>>>4),t+=cnu.charAt(15&this.bytes[r]);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},WWc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??kVD()}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))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return lnu.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,lnu.ofInner(t)}},kVD=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),iZh,R2t=()=>e3D().toString(),e3D=()=>(iZh||(iZh=new WWc)).generate();var t3D=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],nZh=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return t3D.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var DZ=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e})({});var i3D=Array.isArray,aZh=Object.prototype,Hm6=aZh.hasOwnProperty,xWc=aZh.toString,HWc=i3D||function(e){return xWc.call(e)==="[object Array]"};var oZh=e=>e===Object(e)&&!HWc(e);var ela=e=>e===void 0,W2a=e=>xWc.call(e)=="[object String]",uZh=e=>W2a(e)&&e.trim().length===0;var sZh=e=>xWc.call(e)=="[object Number]"&&e===e;var GWc=e=>e instanceof Error;function x2a(e){return e===null||typeof e!="object"}function gAn(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function cZh(e){return gAn(e,"ErrorEvent")}function fnu(e){return!ela(Event)&&n3D(e,Event)}function lZh(e){return gAn(e,"Object")}function n3D(e,t){try{return e instanceof t}catch{return!1}}function H2a(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),sZh(e)?e>r?(i.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),H2a(n||r,t,r,i))}var a3D=864e5,dnu=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=H2a(t.bucketSize,0,100,t._logger),this._refillRate=H2a(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=H2a(t.refillInterval,0,a3D,t._logger)}_applyRefill(t,r){let i=r-t.lastAccess,n=Math.floor(i/this._refillInterval);if(n>0){let a=n*this._refillRate;t.tokens=Math.min(t.tokens+a,this._bucketSize),t.lastAccess=t.lastAccess+n*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),i=String(t),n=this._buckets[i];return n?this._applyRefill(n,r):(n={tokens:this._bucketSize,lastAccess:r},this._buckets[i]=n),n.tokens===0?!0:(n.tokens--,n.tokens===0&&this._onBucketRateLimited?.(t),n.tokens===0)}stop(){this._buckets={}}};var pnu=class{add(t){let r=R2t();return this.promiseByIds[r]=t,t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds),r=t.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function o3D(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var fZh=(e,t,r)=>{function i(a,...o){t(()=>{let c=r[a];c(e,...o)})}return{info:(...a)=>{i("log",...a)},warn:(...a)=>{i("warn",...a)},error:(...a)=>{i("error",...a)},critical:(...a)=>{r.error(e,...a)},createLogger:a=>fZh(`${e} ${a}`,t,r)}},u3D=e=>e();function dZh(e,t=u3D){return fZh(e,t,o3D())}var rla="Mobile",_nu="iOS",tla="Android",pZh="Tablet",iA6=tla+" "+pZh;var s3D="Apple",nA6=s3D+" Watch",hZh="Safari",ynu="BlackBerry",_Zh="Samsung",c3D=_Zh+"Browser",l3D=_Zh+" Internet",bnu="Chrome",f3D=bnu+" OS",d3D=bnu+" "+_nu,yZh="Internet Explorer",p3D=yZh+" "+rla,$Wc="Opera",aA6=$Wc+" Mini",bZh="Edge",h3D="Microsoft "+bZh,JWc="Firefox",_3D=JWc+" "+_nu,YWc="Nintendo",XWc="PlayStation",hnu="Xbox",y3D=tla+" "+rla,b3D=rla+" "+hZh,G2a="Windows",v3D=G2a+" Phone";var vZh="Generic",oA6=vZh+" "+rla.toLowerCase(),uA6=vZh+" "+pZh.toLowerCase(),g3D="Konqueror",M7="(\\d+(\\.\\d+)?)",KWc=new RegExp("Version/"+M7),sA6=new RegExp(hnu,"i"),cA6=new RegExp(XWc+" \\w+","i"),lA6=new RegExp(YWc+" \\w+","i"),O3D=new RegExp(ynu+"|PlayBook|BB10","i"),m3D={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var fA6={[p3D]:[new RegExp("rv:"+M7)],[h3D]:[new RegExp(bZh+"?\\/"+M7)],[bnu]:[new RegExp("("+bnu+"|CrMo)\\/"+M7)],[d3D]:[new RegExp("CriOS\\/"+M7)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+M7)],[hZh]:[KWc],[b3D]:[KWc],[$Wc]:[new RegExp("("+$Wc+"|OPR)\\/"+M7)],[JWc]:[new RegExp(JWc+"\\/"+M7)],[_3D]:[new RegExp("FxiOS\\/"+M7)],[g3D]:[new RegExp("Konqueror[:/]?"+M7,"i")],[ynu]:[new RegExp(ynu+" "+M7),KWc],[y3D]:[new RegExp("android\\s"+M7,"i")],[l3D]:[new RegExp(c3D+"\\/"+M7)],[yZh]:[new RegExp("(rv:|MSIE )"+M7)],Mozilla:[new RegExp("rv:"+M7)]};var dA6=[[new RegExp(hnu+"; "+hnu+" (.*?)[);]","i"),e=>[hnu,e&&e[1]||""]],[new RegExp(YWc,"i"),[YWc,""]],[new RegExp(XWc,"i"),[XWc,""]],[O3D,[ynu,""]],[new RegExp(G2a,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[v3D,""];if(new RegExp(rla).test(t)&&!/IEMobile\b/.test(t))return[G2a+" "+rla,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=m3D[i]||"";return/arm/i.test(t)&&(n="RT"),[G2a,n]}return[G2a,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[_nu,t.join(".")]}return[_nu,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=ela(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+tla+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+tla+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[tla,t.join(".")]}return[tla,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[f3D,""]],[/Linux|debian/i,["Linux",""]]];var gZh="utf8";function OZh(e,t){if(!e||typeof e!="string"||A3D(e))throw new Error(t)}function A3D(e){return e.trim().length===0}function mZh(e){return e?.replace(/\/+$/,"")}async function AZh(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 vnu(){return new Date().toISOString()}function OAn(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var PZh=e=>e instanceof Error;function ZWc(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var gnu=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)}};function jZh(){return"CompressionStream"in globalThis}async function kWc(e,t=!0){try{let i=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(i).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var mAn=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()}},ila=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function wZh(e){if(e instanceof mAn){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 e8c(e){return typeof e=="object"&&(e instanceof mAn||e instanceof ila)}function EZh(e){return typeof e=="object"&&e instanceof mAn&&e.status===413}var K2a=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new pnu,this._events=new gnu,this._isInitialized=!1,OZh(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=mZh(r.host||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:e8c},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=r.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=dZh("[PostHog]",this.logMsgIfDebug.bind(this)),this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!jZh()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(DZ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(DZ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(DZ.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>this._logger.info(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){return this.promiseQueue.add(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._logger.error("Remote config could not be loaded",n),this._events.emit("error",n)})}async getFlags(t,r={},i={},n={},a={},o=!0){await this._initPromise;let c=o?"&config=true":"",d=`${this.host}/flags/?v=2${c}`,s={token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a};this.evaluationContexts&&this.evaluationContexts.length>0&&(s.evaluation_contexts=this.evaluationContexts);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(s)};return this._logger.info("Flags URL",d),this.fetchWithRetry(d,u,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(f=>f.json()).then(f=>({success:!0,response:VWc(f)})).catch(f=>(this._events.emit("error",f),{success:!1,error:this.categorizeRequestError(f)}))}categorizeRequestError(t){if(t instanceof mAn)return{type:"api_error",statusCode:t.status};if(t instanceof ila){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,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 d=V2a(c.response);return d===void 0&&(d=!1),{response:d,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,evaluatedAt:c.evaluatedAt}}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 d=c[t];return d===void 0?null:d}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 d=await this.getFlags(t,r,i,n,c);if(!d.success)return;let s=d.response;return s.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"),s.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:s?.requestId,quotaLimited:s.quotaLimited}):s}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},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._logger.error(c),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}))?.surveys;return n&&this._logger.info("Surveys fetched from API: ",JSON.stringify(n)),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(DZ.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(DZ.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(DZ.Props,this.props)})}processBeforeEnqueue(t){return t}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,r,i);if(n=this.processBeforeEnqueue(n),n===null)return;let a=this.getPersistedProperty(DZ.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(DZ.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=OAn(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,r,i);if(n=this.processBeforeEnqueue(n),n===null)return;let a={api_key:this.apiKey,batch:[n],sent_at:vnu()};this.historicalMigration&&(a.historical_migration=!0);let o=JSON.stringify(a),c=`${this.host}/batch/`,d=this.disableCompression?null:await kWc(o,this.isDebug),s={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...d!==null&&{"Content-Encoding":"gzip"}},body:d||o};try{await this.fetchWithRetry(c,s)}catch(u){this._events.emit("error",u)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:vnu(),uuid:i?.uuid?i.uuid:R2t()};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 wZh(t)})}async flush(){let t=ZWc([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),ZWc([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(DZ.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(h=>h.message),o=()=>{let _=(this.getPersistedProperty(DZ.Queue)||[]).slice(n.length);this.setPersistedProperty(DZ.Queue,_),t=_},c={api_key:this.apiKey,batch:a,sent_at:vnu()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await kWc(d,this.isDebug),f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:h=>EZh(h)?!1:e8c(h)};try{await this.fetchWithRetry(s,f,p)}catch(h){if(EZh(h)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw h instanceof ila||o(),this._events.emit("error",h),h}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){AbortSignal.timeout??=function(c){let d=new AbortController;return setTimeout(()=>d.abort(),c),d.signal};let a=r.body?r.body:"",o=-1;try{o=a instanceof Blob?a.size:Buffer.byteLength(a,gZh)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await AZh(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new ila(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new mAn(c,o);return c},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(DZ.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!e8c(n))throw n;await wZh(n)}};return Promise.race([new Promise((n,a)=>{OAn(()=>{this._logger.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._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var IZ={};$t(IZ,{DOMExceptionCoercer:()=>n8c,ErrorCoercer:()=>a8c,ErrorEventCoercer:()=>o8c,ErrorPropertiesBuilder:()=>t8c,EventCoercer:()=>c8c,ObjectCoercer:()=>s8c,PrimitiveCoercer:()=>l8c,PromiseRejectionEventCoercer:()=>f8c,ReduceableCache:()=>d8c,StringCoercer:()=>u8c,chromeStackLineParser:()=>r8c,createDefaultStackParser:()=>N3D,createStackParser:()=>NZh,geckoStackLineParser:()=>i8c,nodeStackLineParser:()=>qZh,opera10StackLineParser:()=>IZh,opera11StackLineParser:()=>BZh,reverseAndStripFrames:()=>zZh,winjsStackLineParser:()=>DZh});var Onu,SZh,mnu;function MZh(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return mnu&&r.length===SZh||(SZh=r.length,mnu=r.reduce((i,n)=>{Onu||(Onu={});let a=Onu[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,Onu[n]=[s,u];break}}}return i},{})),mnu}var j3D=4,t8c=class{constructor(t,r,i=[]){this.coercers=t,this.stackParser=r,this.modifiers=i}buildFromUnknown(t,r={}){let n=r&&r.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(n,r,0).apply(t),c=this.buildParsingContext(),d=this.parseStacktrace(o,c);return{$exception_list:this.convertToExceptionList(d,n),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&HWc(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let i;t.cause!=null&&(i=this.parseStacktrace(t.cause,r));let n;return t.stack!=""&&t.stack!=null&&(n=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?1:0),r.chunkIdMap)),{...t,cause:i,stack:n}}applyChunkIds(t,r){return t.map(i=>(i.filename&&r&&(i.chunk_id=r[i.filename]),i))}applyCoercers(t,r){for(let i of this.coercers)if(i.match(t))return i.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let i of this.modifiers)r=await i(r);return r}convertToExceptionList(t,r){let i={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(i.stacktrace={type:"raw",frames:t.stack});let n=[i];return t.cause!=null&&n.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),n}buildParsingContext(){return{chunkIdMap:MZh(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=j3D){let d=this.buildCoercingContext(t,r,c);return this.applyCoercers(o,d)}};return{...r,syntheticException:i==0?r.syntheticException:void 0,mechanism:t,apply:o=>n(o,i),next:o=>n(o,i+1)}}};var D3="?";function z2t(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?D3:r,in_app:!0};return ela(i)||(a.lineno=i),ela(n)||(a.colno=n),a}var Anu=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:D3,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var w3D=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,E3D=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,S3D=/\((\S*)(?::(\d+))(?::(\d+))\)/,r8c=(e,t)=>{let r=w3D.exec(e);if(r){let[,n,a,o]=r;return z2t(t,n,D3,+a,+o)}let i=E3D.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=S3D.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=Anu(i[1]||D3,i[2]);return z2t(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var M3D=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,D3D=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,i8c=(e,t)=>{let r=M3D.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=D3D.exec(r[3]);o&&(r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]="")}let n=r[3],a=r[1]||D3;return[a,n]=Anu(a,n),z2t(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var I3D=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,DZh=(e,t)=>{let r=I3D.exec(e);return r?z2t(t,r[2],r[1]||D3,+r[3],r[4]?+r[4]:void 0):void 0};var B3D=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,IZh=(e,t)=>{let r=B3D.exec(e);return r?z2t(t,r[2],r[3]||D3,+r[1]):void 0},C3D=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,BZh=(e,t)=>{let r=C3D.exec(e);return r?z2t(t,r[5],r[3]||r[4]||D3,+r[1],+r[2]):void 0};var q3D=/^\s*[-]{4,}$/,T3D=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,qZh=(e,t)=>{let r=e.match(T3D);if(r){let i,n,a,o,c;if(r[1]){a=r[1];let u=a.lastIndexOf(".");if(a[u-1]==="."&&u--,u>0){i=a.slice(0,u),n=a.slice(u+1);let f=i.indexOf(".Module");f>0&&(a=a.slice(f+1),i=i.slice(0,f))}o=void 0}n&&(o=i,c=n),n==="<anonymous>"&&(c=void 0,a=void 0),a===void 0&&(c=c||D3,a=o?`${o}.${c}`:c);let d=r[2]?.startsWith("file://")?r[2].slice(7):r[2],s=r[5]==="native";return d?.match(/\/[A-Z]:/)&&(d=d.slice(1)),!d&&r[5]&&!s&&(d=r[5]),{filename:d?decodeURI(d):void 0,module:void 0,function:a,lineno:CZh(r[3]),colno:CZh(r[4]),in_app:R3D(d||"",s),platform:t}}if(e.match(q3D))return{filename:e,platform:t}};function R3D(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 CZh(e){return parseInt(e||"",10)||void 0}var TZh=/\(error: (.*)\)/,RZh=50;function zZh(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,RZh).map(r=>({...r,filename:r.filename||z3D(t).filename,function:r.function||D3}))}function z3D(e){return e[e.length-1]||{}}function N3D(){return NZh("web:javascript",r8c,i8c)}function NZh(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
|
|
1358
|
-
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=TZh.test(c)?c.replace(TZh,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=RZh)break}}return zZh(n)}}var n8c=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=W2a(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return gAn(t,"DOMException")}isDOMError(t){return gAn(t,"DOMError")}};var a8c=class{match(t){return GWc(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var o8c=class{constructor(){}match(t){return cZh(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var F3D=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,u8c=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(F3D);return n&&(r=n[1],i=n[2]),[r,i]}};var FZh=["fatal","error","warning","log","info","debug"];function Pnu(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var s8c=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return fnu(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=Pnu(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return W2a(t)&&!uZh(t)&&FZh.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(PZh(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var c8c=class{match(t){return fnu(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Pnu(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var l8c=class{match(t){return x2a(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var f8c=class{match(t){return gAn(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return x2a(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(x2a(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var d8c=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var LZh=require("fs"),VZh=require("readline"),jnu=new IZ.ReduceableCache(25),WZh=new IZ.ReduceableCache(20),p8c=7,Q3D=1e3,U3D=1e4;async function xZh(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"||x3D(o)||H3D(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(WZh.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=K3D(a);if(o.every(d=>G3D(n,d)))continue;let c=$3D(jnu,n,{});i.push(L3D(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&V3D(e,jnu),jnu.reduce(),e}function L3D(e,t,r){return new Promise(i=>{let n=(0,LZh.createReadStream)(e),a=(0,VZh.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],f=s[1];function p(){WZh.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",h=>{if(c++,!(c<u)&&(r[c]=J3D(h,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let _=t[d];if(_===void 0){a.close(),a.removeAllListeners();return}u=_[0],f=_[1]}})})}function V3D(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;W3D(r.lineno,r,i)}}function W3D(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=HZh(e);n<e;n++){let a=r[n];if(a===void 0)return void QZh(t);t.pre_context.push(a)}if(r[e]===void 0)return void QZh(t);t.context_line=r[e];let i=GZh(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 QZh(e){delete e.pre_context,delete e.context_line,delete e.post_context}function x3D(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function H3D(e){return e.lineno!==void 0&&e.lineno>U3D||e.colno!==void 0&&e.colno>Q3D}function G3D(e,t){let r=jnu.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 K3D(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=UZh(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+p8c:(n.push(i),i=UZh(a)),t++}return n}function UZh(e){return[HZh(e),GZh(e)]}function HZh(e){return Math.max(1,e-p8c)}function GZh(e){return e+p8c}function $3D(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function J3D(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}function Y3D(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(i))},{_posthogErrorHandler:!0})}function KZh(e,t){globalThis.process?.on("uncaughtException",Y3D(e,t))}function $Zh(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var X3D=2e3,E5t=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new dnu({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return oZh(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||R2t(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(KZh(this.onException.bind(this),this.onFatalError.bind(this)),$Zh(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(X3D),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var JZh="5.24.7";var $2a={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function YZh(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var Z3D=6e4,k3D=1152921504606847e3,eWD=["is_not"],nla=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},W0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},N2t=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},wnu=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||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.strictLocalEvaluation=c.strictLocalEvaluation??!1,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;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof N2t||d instanceof W0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:h}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,h&&(c[f.key]=h)}catch(p){p instanceof N2t||p instanceof W0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new W0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new W0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new W0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new W0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new W0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new W0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new W0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new W0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new W0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof N2t)throw u;if(u instanceof W0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new W0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?t2h(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):e2h(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await XZh(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await XZh(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}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(i=>i.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(i=>i.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Z3D,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new nla(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new nla(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new nla(`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 i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(t){t instanceof nla&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=OAn(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function XZh(e,t,r=""){let i=await YZh(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/k3D}function e2h(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 W0("Operator is_not_set is not supported")}else throw new W0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!eWD.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(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}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 ZZh(String(n))&&String(o).match(String(n))!==null;case"not_regex":return ZZh(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?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new W0("Date operations cannot be performed on boolean values");let s=rWD(String(n));if(s==null&&(s=kZh(n)),s==null)throw new W0(`Invalid date: ${n}`);let u=kZh(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new W0(`Unknown operator: ${a}`)}}function tWD(e,t){if(!(e in t))throw new N2t(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function t2h(e,t,r,i=!1){let n=String(e.value);tWD(n,r);let a=r[n];return r2h(a,t,r,i)}function r2h(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 d=r2h(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof N2t)throw d;if(d instanceof W0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new W0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=t2h(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=e2h(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof N2t)throw d;if(d instanceof W0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new W0("can't match cohort without a given cohort property value");return n==="AND"}function ZZh(e){try{return new RegExp(e),!0}catch{return!1}}function kZh(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 W0(`${e} is in an invalid date format`)}throw new W0(`The date provided ${e} must be a string, number, or date object`)}function rWD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{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()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var Enu=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var iWD=100,i2h=3e4,nWD=5e4,Snu=class extends K2a{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Enu,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,iWD):i2h,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new wnu({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new E5t(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||nWD}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return JZh}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{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=i2h){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 _getFeatureFlagResult(t,r,i={},n){let a=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let A=this._flagOverrides[t];if(A===void 0)return;let j=this._payloadOverrides?.[t];return{key:t,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:j}}let{groups:o,disableGeoip:c}=i,{onlyEvaluateLocally:d,personProperties:s,groupProperties:u}=i,f=this.addLocalPersonAndGroupProperties(r,o,s,u);s=f.allPersonProperties,u=f.allGroupProperties,d==null&&(d=this.options.strictLocalEvaluation??!1);let p,h=!1,_,y,b,v,O,m;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let A=this.featureFlagsPoller?.featureFlagsByKey[t];if(A)try{let j=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(A,r,o,s,u,n);if(j){h=!0;let S=j.value;v=A.id,m="Evaluated locally",p={key:t,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:j.payload??void 0}}}catch(j){if(j instanceof N2t||j instanceof W0)this._logger?.info(`${j.name} when computing flag locally: ${t}: ${j.message}`);else throw j}}if(!h&&!d){let A=await super.getFeatureFlagDetailsStateless(r,o,s,u,c,[t]);if(A===void 0)b=$2a.UNKNOWN_ERROR;else{_=A.requestId,y=A.evaluatedAt;let j=[];A.errorsWhileComputingFlags&&j.push($2a.ERRORS_WHILE_COMPUTING),A.quotaLimited?.includes("feature_flags")&&j.push($2a.QUOTA_LIMITED);let S=A.flags[t];if(S===void 0)j.push($2a.FLAG_MISSING);else{v=S.metadata?.id,O=S.metadata?.version,m=S.reason?.description??S.reason?.code;let w;if(S.metadata?.payload!==void 0)try{w=JSON.parse(S.metadata.payload)}catch{w=S.metadata.payload}p={key:t,enabled:S.enabled,variant:S.variant,payload:w}}j.length>0&&(b=j.join(","))}}if(a){let A=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,j=`${t}_${A}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(j)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(j):this.distinctIdHasSentFlagCalls[r]=[j];let S={$feature_flag:t,$feature_flag_response:A,$feature_flag_id:v,$feature_flag_version:O,$feature_flag_reason:m,locally_evaluated:h,[`$feature/${t}`]:A,$feature_flag_request_id:_,$feature_flag_evaluated_at:y};b&&(S.$feature_flag_error=b),this.capture({distinctId:r,event:"$feature_flag_called",properties:S,groups:o,disableGeoip:c})}}return p!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[t]}),p}async getFeatureFlag(t,r,i){let n=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n!==void 0)return n.enabled===!1?!1:n.variant??!0}async getFeatureFlagPayload(t,r,i,n){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let a=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:!1},i);if(a!==void 0)return a.payload??null}async getFeatureFlagResult(t,r,i){return this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}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,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=this.options.strictLocalEvaluation??!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},h=!0;if(u&&(f=u.response,p=u.payloads,h=u.fallbackToFlags),h&&!o){let _=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,..._.flags||{}},p={...p,..._.payloads||{}}}return this._flagOverrides!==void 0&&(f={...f,...this._flagOverrides}),this._payloadOverrides!==void 0&&(p={...p,...this._payloadOverrides}),{featureFlags:f,featureFlagPayloads:p}}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)}overrideFeatureFlags(t){let r=i=>Object.fromEntries(i.map(n=>[n,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let i=r.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in r){let i=r.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=OAn(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(lZh(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}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,n){if(!E5t.isPreviouslyCapturedError(t)){let a=new Error("PostHog syntheticException");this.addPendingPromise(E5t.buildEventMessage(t,{syntheticException:a},r,i).then(o=>this.capture({...o,uuid:n})))}}async captureExceptionImmediate(t,r,i){if(!E5t.isPreviouslyCapturedError(t)){let n=new Error("PostHog syntheticException");this.addPendingPromise(E5t.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=R2t(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let h=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!h)return Promise.reject(null);let _=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(h.distinctId,a,d,y)}return h.event,{}}).then(y=>{let b={};if(y)for(let[O,m]of Object.entries(y))b[`$feature/${O}`]=m;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,...h.properties||{},$groups:h.groups||a}));return h.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof _.$raw_user_agent=="string"&&nZh(_.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(h.event="$bot_pageview",_.$browser_type="bot"),{distinctId:h.distinctId,event:h.event,properties:_,options:{timestamp:h.timestamp,disableGeoip:h.disableGeoip,uuid:h.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var n2h=require("async_hooks"),Mnu=class{constructor(){this.storage=new n2h.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var a2h="posthog-node";function aWD(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[h8c.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],p=f.map(_=>({..._,stacktrace:_.stacktrace?{..._.stacktrace,type:"raw",frames:(_.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),h={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(h.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:h}),o}}var h8c=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=a2h,this.name=a2h,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(aWD(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};E5t.errorPropertiesBuilder=new IZ.ErrorPropertiesBuilder([new IZ.EventCoercer,new IZ.ErrorCoercer,new IZ.ObjectCoercer,new IZ.StringCoercer,new IZ.PrimitiveCoercer],IZ.createStackParser("node:javascript",IZ.nodeStackLineParser),[kXh(),xZh]);var ala=class extends Snu{getLibraryId(){return"posthog-node"}initializeContext(){return new Mnu}};var Dnu=class{posthog;constructor({posthogApiKey:t}){this.posthog=new ala(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.64.6",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var J2a=class{async sendEvent(){}async identify(){}async flush(){}};var ola=require("fs/promises"),c2h=require("os"),l2h=require("path");var o2h=ce(require("crypto")),Bnu=new Uint8Array(256),Inu=Bnu.length;function _8c(){return Inu>Bnu.length-16&&(o2h.default.randomFillSync(Bnu),Inu=0),Bnu.slice(Inu,Inu+=16)}var I3=[];for(let e=0;e<256;++e)I3.push((e+256).toString(16).slice(1));function u2h(e,t=0){return I3[e[t+0]]+I3[e[t+1]]+I3[e[t+2]]+I3[e[t+3]]+"-"+I3[e[t+4]]+I3[e[t+5]]+"-"+I3[e[t+6]]+I3[e[t+7]]+"-"+I3[e[t+8]]+I3[e[t+9]]+"-"+I3[e[t+10]]+I3[e[t+11]]+I3[e[t+12]]+I3[e[t+13]]+I3[e[t+14]]+I3[e[t+15]]}var s2h=ce(require("crypto")),y8c={randomUUID:s2h.default.randomUUID};function oWD(e,t,r){if(y8c.randomUUID&&!t&&!e)return y8c.randomUUID();e=e||{};let i=e.random||(e.rng||_8c)();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 u2h(i)}var Ume=oWD;var uWD="id",sWD=".fern",Y2a=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new ala(r),this.userId=t==null?void 0:kFc(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.64.6",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Fq({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=ut(vr.of((0,c2h.homedir)()),me.of(sWD),me.of(uWD));await ii(t)||(await(0,ola.mkdir)((0,l2h.dirname)(t),{recursive:!0}),await(0,ola.writeFile)(t,Ume())),this.persistedDistinctId=(await(0,ola.readFile)(t)).toString()}return this.persistedDistinctId}};var b8c;async function ula(){return b8c==null&&(b8c=await cWD()),b8c}async function cWD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new J2a;let r=await $Zo();return r!=null?new Y2a({token:r,posthogApiKey:e}):await y2t()!=null?new Dnu({posthogApiKey:e}):new Y2a({token:void 0,posthogApiKey:e})}catch{return new J2a}}var f2h=(e=0)=>t=>`\x1B[${t+e}m`,d2h=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,p2h=(e=0)=>(t,r,i)=>`\x1B[${38+e};2;${t};${r};${i}m`,KD={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},fw6=Object.keys(KD.modifier),lWD=Object.keys(KD.color),fWD=Object.keys(KD.bgColor),dw6=[...lWD,...fWD];function dWD(){let e=new Map;for(let[t,r]of Object.entries(KD)){for(let[i,n]of Object.entries(r))KD[i]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},r[i]=KD[i],e.set(n[0],n[1]);Object.defineProperty(KD,t,{value:r,enumerable:!1})}return Object.defineProperty(KD,"codes",{value:e,enumerable:!1}),KD.color.close="\x1B[39m",KD.bgColor.close="\x1B[49m",KD.color.ansi=f2h(),KD.color.ansi256=d2h(),KD.color.ansi16m=p2h(),KD.bgColor.ansi=f2h(10),KD.bgColor.ansi256=d2h(10),KD.bgColor.ansi16m=p2h(10),Object.defineProperties(KD,{rgbToAnsi256:{value(t,r,i){return t===r&&r===i?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(i/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r)return[0,0,0];let[i]=r;i.length===3&&(i=[...i].map(a=>a+a).join(""));let n=Number.parseInt(i,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:t=>KD.rgbToAnsi256(...KD.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,i,n;if(t>=232)r=((t-232)*10+8)/255,i=r,n=r;else{t-=16;let c=t%36;r=Math.floor(t/36)/5,i=Math.floor(c/6)/5,n=c%6/5}let a=Math.max(r,i,n)*2;if(a===0)return 30;let o=30+(Math.round(n)<<2|Math.round(i)<<1|Math.round(r));return a===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(t,r,i)=>KD.ansi256ToAnsi(KD.rgbToAnsi256(t,r,i)),enumerable:!1},hexToAnsi:{value:t=>KD.ansi256ToAnsi(KD.hexToAnsi256(t)),enumerable:!1}}),KD}var pWD=dWD(),S5t=pWD;var qnu=ce(require("process"),1),_2h=ce(require("os"),1),v8c=ce(require("tty"),1);function mDe(e,t=globalThis.Deno?globalThis.Deno.args:qnu.default.argv){let r=e.startsWith("-")?"":e.length===1?"-":"--",i=t.indexOf(r+e),n=t.indexOf("--");return i!==-1&&(n===-1||i<n)}var{env:IC}=qnu.default,Cnu;mDe("no-color")||mDe("no-colors")||mDe("color=false")||mDe("color=never")?Cnu=0:(mDe("color")||mDe("colors")||mDe("color=true")||mDe("color=always"))&&(Cnu=1);function hWD(){if("FORCE_COLOR"in IC)return IC.FORCE_COLOR==="true"?1:IC.FORCE_COLOR==="false"?0:IC.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(IC.FORCE_COLOR,10),3)}function _WD(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function yWD(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let i=hWD();i!==void 0&&(Cnu=i);let n=r?Cnu:i;if(n===0)return 0;if(r){if(mDe("color=16m")||mDe("color=full")||mDe("color=truecolor"))return 3;if(mDe("color=256"))return 2}if("TF_BUILD"in IC&&"AGENT_NAME"in IC)return 1;if(e&&!t&&n===void 0)return 0;let a=n||0;if(IC.TERM==="dumb")return a;if(qnu.default.platform==="win32"){let o=_2h.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in IC)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in IC)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in IC)||IC.CI_NAME==="codeship"?1:a;if("TEAMCITY_VERSION"in IC)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(IC.TEAMCITY_VERSION)?1:0;if(IC.COLORTERM==="truecolor"||IC.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in IC){let o=Number.parseInt((IC.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(IC.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(IC.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(IC.TERM)||"COLORTERM"in IC?1:a}function h2h(e,t={}){let r=yWD(e,{streamIsTTY:e&&e.isTTY,...t});return _WD(r)}var bWD={stdout:h2h({isTTY:v8c.default.isatty(1)}),stderr:h2h({isTTY:v8c.default.isatty(2)})},y2h=bWD;function b2h(e,t,r){let i=e.indexOf(t);if(i===-1)return e;let n=t.length,a=0,o="";do o+=e.slice(a,i)+t+r,a=i+n,i=e.indexOf(t,a);while(i!==-1);return o+=e.slice(a),o}function v2h(e,t,r,i){let n=0,a="";do{let o=e[i-1]==="\r";a+=e.slice(n,o?i-1:i)+t+(o?`\r
|
|
1358
|
+
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=TZh.test(c)?c.replace(TZh,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=RZh)break}}return zZh(n)}}var n8c=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=W2a(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return gAn(t,"DOMException")}isDOMError(t){return gAn(t,"DOMError")}};var a8c=class{match(t){return GWc(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var o8c=class{constructor(){}match(t){return cZh(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var F3D=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,u8c=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(F3D);return n&&(r=n[1],i=n[2]),[r,i]}};var FZh=["fatal","error","warning","log","info","debug"];function Pnu(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var s8c=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return fnu(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=Pnu(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return W2a(t)&&!uZh(t)&&FZh.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(PZh(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var c8c=class{match(t){return fnu(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Pnu(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var l8c=class{match(t){return x2a(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var f8c=class{match(t){return gAn(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return x2a(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(x2a(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var d8c=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var LZh=require("fs"),VZh=require("readline"),jnu=new IZ.ReduceableCache(25),WZh=new IZ.ReduceableCache(20),p8c=7,Q3D=1e3,U3D=1e4;async function xZh(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"||x3D(o)||H3D(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(WZh.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=K3D(a);if(o.every(d=>G3D(n,d)))continue;let c=$3D(jnu,n,{});i.push(L3D(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&V3D(e,jnu),jnu.reduce(),e}function L3D(e,t,r){return new Promise(i=>{let n=(0,LZh.createReadStream)(e),a=(0,VZh.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],f=s[1];function p(){WZh.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",h=>{if(c++,!(c<u)&&(r[c]=J3D(h,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let _=t[d];if(_===void 0){a.close(),a.removeAllListeners();return}u=_[0],f=_[1]}})})}function V3D(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;W3D(r.lineno,r,i)}}function W3D(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=HZh(e);n<e;n++){let a=r[n];if(a===void 0)return void QZh(t);t.pre_context.push(a)}if(r[e]===void 0)return void QZh(t);t.context_line=r[e];let i=GZh(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 QZh(e){delete e.pre_context,delete e.context_line,delete e.post_context}function x3D(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function H3D(e){return e.lineno!==void 0&&e.lineno>U3D||e.colno!==void 0&&e.colno>Q3D}function G3D(e,t){let r=jnu.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 K3D(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=UZh(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+p8c:(n.push(i),i=UZh(a)),t++}return n}function UZh(e){return[HZh(e),GZh(e)]}function HZh(e){return Math.max(1,e-p8c)}function GZh(e){return e+p8c}function $3D(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function J3D(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}function Y3D(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(i))},{_posthogErrorHandler:!0})}function KZh(e,t){globalThis.process?.on("uncaughtException",Y3D(e,t))}function $Zh(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var X3D=2e3,E5t=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new dnu({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return oZh(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||R2t(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(KZh(this.onException.bind(this),this.onFatalError.bind(this)),$Zh(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(X3D),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var JZh="5.24.7";var $2a={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function YZh(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var Z3D=6e4,k3D=1152921504606847e3,eWD=["is_not"],nla=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},W0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},N2t=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},wnu=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||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.strictLocalEvaluation=c.strictLocalEvaluation??!1,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;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof N2t||d instanceof W0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:h}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,h&&(c[f.key]=h)}catch(p){p instanceof N2t||p instanceof W0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new W0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new W0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new W0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new W0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new W0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new W0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new W0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new W0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new W0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof N2t)throw u;if(u instanceof W0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new W0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?t2h(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):e2h(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await XZh(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await XZh(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}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(i=>i.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(i=>i.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Z3D,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new nla(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new nla(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new nla(`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 i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(t){t instanceof nla&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=OAn(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function XZh(e,t,r=""){let i=await YZh(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/k3D}function e2h(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 W0("Operator is_not_set is not supported")}else throw new W0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!eWD.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(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}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 ZZh(String(n))&&String(o).match(String(n))!==null;case"not_regex":return ZZh(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?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new W0("Date operations cannot be performed on boolean values");let s=rWD(String(n));if(s==null&&(s=kZh(n)),s==null)throw new W0(`Invalid date: ${n}`);let u=kZh(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new W0(`Unknown operator: ${a}`)}}function tWD(e,t){if(!(e in t))throw new N2t(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function t2h(e,t,r,i=!1){let n=String(e.value);tWD(n,r);let a=r[n];return r2h(a,t,r,i)}function r2h(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 d=r2h(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof N2t)throw d;if(d instanceof W0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new W0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=t2h(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=e2h(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof N2t)throw d;if(d instanceof W0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new W0("can't match cohort without a given cohort property value");return n==="AND"}function ZZh(e){try{return new RegExp(e),!0}catch{return!1}}function kZh(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 W0(`${e} is in an invalid date format`)}throw new W0(`The date provided ${e} must be a string, number, or date object`)}function rWD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{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()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var Enu=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var iWD=100,i2h=3e4,nWD=5e4,Snu=class extends K2a{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Enu,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,iWD):i2h,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new wnu({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new E5t(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||nWD}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getLibraryVersion(){return JZh}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{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=i2h){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 _getFeatureFlagResult(t,r,i={},n){let a=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let A=this._flagOverrides[t];if(A===void 0)return;let j=this._payloadOverrides?.[t];return{key:t,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:j}}let{groups:o,disableGeoip:c}=i,{onlyEvaluateLocally:d,personProperties:s,groupProperties:u}=i,f=this.addLocalPersonAndGroupProperties(r,o,s,u);s=f.allPersonProperties,u=f.allGroupProperties,d==null&&(d=this.options.strictLocalEvaluation??!1);let p,h=!1,_,y,b,v,O,m;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let A=this.featureFlagsPoller?.featureFlagsByKey[t];if(A)try{let j=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(A,r,o,s,u,n);if(j){h=!0;let S=j.value;v=A.id,m="Evaluated locally",p={key:t,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:j.payload??void 0}}}catch(j){if(j instanceof N2t||j instanceof W0)this._logger?.info(`${j.name} when computing flag locally: ${t}: ${j.message}`);else throw j}}if(!h&&!d){let A=await super.getFeatureFlagDetailsStateless(r,o,s,u,c,[t]);if(A===void 0)b=$2a.UNKNOWN_ERROR;else{_=A.requestId,y=A.evaluatedAt;let j=[];A.errorsWhileComputingFlags&&j.push($2a.ERRORS_WHILE_COMPUTING),A.quotaLimited?.includes("feature_flags")&&j.push($2a.QUOTA_LIMITED);let S=A.flags[t];if(S===void 0)j.push($2a.FLAG_MISSING);else{v=S.metadata?.id,O=S.metadata?.version,m=S.reason?.description??S.reason?.code;let w;if(S.metadata?.payload!==void 0)try{w=JSON.parse(S.metadata.payload)}catch{w=S.metadata.payload}p={key:t,enabled:S.enabled,variant:S.variant,payload:w}}j.length>0&&(b=j.join(","))}}if(a){let A=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,j=`${t}_${A}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(j)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(j):this.distinctIdHasSentFlagCalls[r]=[j];let S={$feature_flag:t,$feature_flag_response:A,$feature_flag_id:v,$feature_flag_version:O,$feature_flag_reason:m,locally_evaluated:h,[`$feature/${t}`]:A,$feature_flag_request_id:_,$feature_flag_evaluated_at:y};b&&(S.$feature_flag_error=b),this.capture({distinctId:r,event:"$feature_flag_called",properties:S,groups:o,disableGeoip:c})}}return p!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[t]}),p}async getFeatureFlag(t,r,i){let n=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n!==void 0)return n.enabled===!1?!1:n.variant??!0}async getFeatureFlagPayload(t,r,i,n){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let a=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:!1},i);if(a!==void 0)return a.payload??null}async getFeatureFlagResult(t,r,i){return this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}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,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=this.options.strictLocalEvaluation??!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},h=!0;if(u&&(f=u.response,p=u.payloads,h=u.fallbackToFlags),h&&!o){let _=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,..._.flags||{}},p={...p,..._.payloads||{}}}return this._flagOverrides!==void 0&&(f={...f,...this._flagOverrides}),this._payloadOverrides!==void 0&&(p={...p,...this._payloadOverrides}),{featureFlags:f,featureFlagPayloads:p}}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)}overrideFeatureFlags(t){let r=i=>Object.fromEntries(i.map(n=>[n,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let i=r.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in r){let i=r.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=OAn(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(lZh(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}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,n){if(!E5t.isPreviouslyCapturedError(t)){let a=new Error("PostHog syntheticException");this.addPendingPromise(E5t.buildEventMessage(t,{syntheticException:a},r,i).then(o=>this.capture({...o,uuid:n})))}}async captureExceptionImmediate(t,r,i){if(!E5t.isPreviouslyCapturedError(t)){let n=new Error("PostHog syntheticException");this.addPendingPromise(E5t.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=R2t(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let h=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!h)return Promise.reject(null);let _=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(h.distinctId,a,d,y)}return h.event,{}}).then(y=>{let b={};if(y)for(let[O,m]of Object.entries(y))b[`$feature/${O}`]=m;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,...h.properties||{},$groups:h.groups||a}));return h.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof _.$raw_user_agent=="string"&&nZh(_.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(h.event="$bot_pageview",_.$browser_type="bot"),{distinctId:h.distinctId,event:h.event,properties:_,options:{timestamp:h.timestamp,disableGeoip:h.disableGeoip,uuid:h.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var n2h=require("async_hooks"),Mnu=class{constructor(){this.storage=new n2h.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var a2h="posthog-node";function aWD(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[h8c.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],p=f.map(_=>({..._,stacktrace:_.stacktrace?{..._.stacktrace,type:"raw",frames:(_.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),h={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(h.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:h}),o}}var h8c=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=a2h,this.name=a2h,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(aWD(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};E5t.errorPropertiesBuilder=new IZ.ErrorPropertiesBuilder([new IZ.EventCoercer,new IZ.ErrorCoercer,new IZ.ObjectCoercer,new IZ.StringCoercer,new IZ.PrimitiveCoercer],IZ.createStackParser("node:javascript",IZ.nodeStackLineParser),[kXh(),xZh]);var ala=class extends Snu{getLibraryId(){return"posthog-node"}initializeContext(){return new Mnu}};var Dnu=class{posthog;constructor({posthogApiKey:t}){this.posthog=new ala(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.65.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var J2a=class{async sendEvent(){}async identify(){}async flush(){}};var ola=require("fs/promises"),c2h=require("os"),l2h=require("path");var o2h=ce(require("crypto")),Bnu=new Uint8Array(256),Inu=Bnu.length;function _8c(){return Inu>Bnu.length-16&&(o2h.default.randomFillSync(Bnu),Inu=0),Bnu.slice(Inu,Inu+=16)}var I3=[];for(let e=0;e<256;++e)I3.push((e+256).toString(16).slice(1));function u2h(e,t=0){return I3[e[t+0]]+I3[e[t+1]]+I3[e[t+2]]+I3[e[t+3]]+"-"+I3[e[t+4]]+I3[e[t+5]]+"-"+I3[e[t+6]]+I3[e[t+7]]+"-"+I3[e[t+8]]+I3[e[t+9]]+"-"+I3[e[t+10]]+I3[e[t+11]]+I3[e[t+12]]+I3[e[t+13]]+I3[e[t+14]]+I3[e[t+15]]}var s2h=ce(require("crypto")),y8c={randomUUID:s2h.default.randomUUID};function oWD(e,t,r){if(y8c.randomUUID&&!t&&!e)return y8c.randomUUID();e=e||{};let i=e.random||(e.rng||_8c)();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 u2h(i)}var Ume=oWD;var uWD="id",sWD=".fern",Y2a=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new ala(r),this.userId=t==null?void 0:kFc(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.65.0",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Fq({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=ut(vr.of((0,c2h.homedir)()),me.of(sWD),me.of(uWD));await ii(t)||(await(0,ola.mkdir)((0,l2h.dirname)(t),{recursive:!0}),await(0,ola.writeFile)(t,Ume())),this.persistedDistinctId=(await(0,ola.readFile)(t)).toString()}return this.persistedDistinctId}};var b8c;async function ula(){return b8c==null&&(b8c=await cWD()),b8c}async function cWD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new J2a;let r=await $Zo();return r!=null?new Y2a({token:r,posthogApiKey:e}):await y2t()!=null?new Dnu({posthogApiKey:e}):new Y2a({token:void 0,posthogApiKey:e})}catch{return new J2a}}var f2h=(e=0)=>t=>`\x1B[${t+e}m`,d2h=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,p2h=(e=0)=>(t,r,i)=>`\x1B[${38+e};2;${t};${r};${i}m`,KD={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},fw6=Object.keys(KD.modifier),lWD=Object.keys(KD.color),fWD=Object.keys(KD.bgColor),dw6=[...lWD,...fWD];function dWD(){let e=new Map;for(let[t,r]of Object.entries(KD)){for(let[i,n]of Object.entries(r))KD[i]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},r[i]=KD[i],e.set(n[0],n[1]);Object.defineProperty(KD,t,{value:r,enumerable:!1})}return Object.defineProperty(KD,"codes",{value:e,enumerable:!1}),KD.color.close="\x1B[39m",KD.bgColor.close="\x1B[49m",KD.color.ansi=f2h(),KD.color.ansi256=d2h(),KD.color.ansi16m=p2h(),KD.bgColor.ansi=f2h(10),KD.bgColor.ansi256=d2h(10),KD.bgColor.ansi16m=p2h(10),Object.defineProperties(KD,{rgbToAnsi256:{value(t,r,i){return t===r&&r===i?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(i/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r)return[0,0,0];let[i]=r;i.length===3&&(i=[...i].map(a=>a+a).join(""));let n=Number.parseInt(i,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:t=>KD.rgbToAnsi256(...KD.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,i,n;if(t>=232)r=((t-232)*10+8)/255,i=r,n=r;else{t-=16;let c=t%36;r=Math.floor(t/36)/5,i=Math.floor(c/6)/5,n=c%6/5}let a=Math.max(r,i,n)*2;if(a===0)return 30;let o=30+(Math.round(n)<<2|Math.round(i)<<1|Math.round(r));return a===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(t,r,i)=>KD.ansi256ToAnsi(KD.rgbToAnsi256(t,r,i)),enumerable:!1},hexToAnsi:{value:t=>KD.ansi256ToAnsi(KD.hexToAnsi256(t)),enumerable:!1}}),KD}var pWD=dWD(),S5t=pWD;var qnu=ce(require("process"),1),_2h=ce(require("os"),1),v8c=ce(require("tty"),1);function mDe(e,t=globalThis.Deno?globalThis.Deno.args:qnu.default.argv){let r=e.startsWith("-")?"":e.length===1?"-":"--",i=t.indexOf(r+e),n=t.indexOf("--");return i!==-1&&(n===-1||i<n)}var{env:IC}=qnu.default,Cnu;mDe("no-color")||mDe("no-colors")||mDe("color=false")||mDe("color=never")?Cnu=0:(mDe("color")||mDe("colors")||mDe("color=true")||mDe("color=always"))&&(Cnu=1);function hWD(){if("FORCE_COLOR"in IC)return IC.FORCE_COLOR==="true"?1:IC.FORCE_COLOR==="false"?0:IC.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(IC.FORCE_COLOR,10),3)}function _WD(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function yWD(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let i=hWD();i!==void 0&&(Cnu=i);let n=r?Cnu:i;if(n===0)return 0;if(r){if(mDe("color=16m")||mDe("color=full")||mDe("color=truecolor"))return 3;if(mDe("color=256"))return 2}if("TF_BUILD"in IC&&"AGENT_NAME"in IC)return 1;if(e&&!t&&n===void 0)return 0;let a=n||0;if(IC.TERM==="dumb")return a;if(qnu.default.platform==="win32"){let o=_2h.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in IC)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in IC)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in IC)||IC.CI_NAME==="codeship"?1:a;if("TEAMCITY_VERSION"in IC)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(IC.TEAMCITY_VERSION)?1:0;if(IC.COLORTERM==="truecolor"||IC.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in IC){let o=Number.parseInt((IC.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(IC.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(IC.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(IC.TERM)||"COLORTERM"in IC?1:a}function h2h(e,t={}){let r=yWD(e,{streamIsTTY:e&&e.isTTY,...t});return _WD(r)}var bWD={stdout:h2h({isTTY:v8c.default.isatty(1)}),stderr:h2h({isTTY:v8c.default.isatty(2)})},y2h=bWD;function b2h(e,t,r){let i=e.indexOf(t);if(i===-1)return e;let n=t.length,a=0,o="";do o+=e.slice(a,i)+t+r,a=i+n,i=e.indexOf(t,a);while(i!==-1);return o+=e.slice(a),o}function v2h(e,t,r,i){let n=0,a="";do{let o=e[i-1]==="\r";a+=e.slice(n,o?i-1:i)+t+(o?`\r
|
|
1359
1359
|
`:`
|
|
1360
1360
|
`)+r,n=i+1,i=e.indexOf(`
|
|
1361
1361
|
`,n)}while(i!==-1);return a+=e.slice(n),a}var{stdout:g2h,stderr:O2h}=y2h,g8c=Symbol("GENERATOR"),sla=Symbol("STYLER"),X2a=Symbol("IS_EMPTY"),m2h=["ansi","ansi","ansi256","ansi16m"],cla=Object.create(null),vWD=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=g2h?g2h.level:0;e.level=t.level===void 0?r:t.level};var gWD=e=>{let t=(...r)=>r.join(" ");return vWD(t,e),Object.setPrototypeOf(t,Z2a.prototype),t};function Z2a(e){return gWD(e)}Object.setPrototypeOf(Z2a.prototype,Function.prototype);for(let[e,t]of Object.entries(S5t))cla[e]={get(){let r=Tnu(this,m8c(t.open,t.close,this[sla]),this[X2a]);return Object.defineProperty(this,e,{value:r}),r}};cla.visible={get(){let e=Tnu(this,this[sla],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var O8c=(e,t,r,...i)=>e==="rgb"?t==="ansi16m"?S5t[r].ansi16m(...i):t==="ansi256"?S5t[r].ansi256(S5t.rgbToAnsi256(...i)):S5t[r].ansi(S5t.rgbToAnsi(...i)):e==="hex"?O8c("rgb",t,r,...S5t.hexToRgb(...i)):S5t[r][e](...i),OWD=["rgb","hex","ansi256"];for(let e of OWD){cla[e]={get(){let{level:r}=this;return function(...i){let n=m8c(O8c(e,m2h[r],"color",...i),S5t.color.close,this[sla]);return Tnu(this,n,this[X2a])}}};let t="bg"+e[0].toUpperCase()+e.slice(1);cla[t]={get(){let{level:r}=this;return function(...i){let n=m8c(O8c(e,m2h[r],"bgColor",...i),S5t.bgColor.close,this[sla]);return Tnu(this,n,this[X2a])}}}}var mWD=Object.defineProperties(()=>{},{...cla,level:{enumerable:!0,get(){return this[g8c].level},set(e){this[g8c].level=e}}}),m8c=(e,t,r)=>{let i,n;return r===void 0?(i=e,n=t):(i=r.openAll+e,n=t+r.closeAll),{open:e,close:t,openAll:i,closeAll:n,parent:r}},Tnu=(e,t,r)=>{let i=(...n)=>AWD(i,n.length===1?""+n[0]:n.join(" "));return Object.setPrototypeOf(i,mWD),i[g8c]=e,i[sla]=t,i[X2a]=r,i},AWD=(e,t)=>{if(e.level<=0||!t)return e[X2a]?"":t;let r=e[sla];if(r===void 0)return t;let{openAll:i,closeAll:n}=r;if(t.includes("\x1B"))for(;r!==void 0;)t=b2h(t,r.close,r.open),r=r.parent;let a=t.indexOf(`
|
|
@@ -2476,7 +2476,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
|
|
|
2476
2476
|
Run ${Ke.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
2477
2477
|
Run ${Ke.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),gla(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function INp({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!XuS(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,d)=>c.generatorName.localeCompare(d.generatorName)||c.currentVersion.localeCompare(d.currentVersion));for(let c of o)n+=`
|
|
2478
2478
|
${await kF5(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Ke.dim(c.currentVersion)+Ke.reset(" \u2192 ")+Ke.green(c.latestVersion);return n+=`
|
|
2479
|
-
`,i?gla(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function kF5(e){let r=await new YuS.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 eQ5({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await kuS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=Qjn(u.name);if(p==null){f.logger.debug(`Skipping unknown generator: ${u.name}`);return}let h=await sHt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});h!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:h})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await kuS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let f=Qjn(s.name);if(f==null){u.logger.debug(`Skipping unknown generator: ${s.name}`);return}let p=await sHt({generatorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function kuS({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 cAe({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?DU(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function esS(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 d=p2(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function E_c({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await eQ5({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...esS(s,d,t.logger));else o.push(...esS(c.versions,void 0,t.logger))}return o}async function Kbn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:Pto(e.packageName,{version:t?"prerelease":"latest"})}var tsS=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],S_c=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Kn.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new IAn(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"3.
|
|
2479
|
+
`,i?gla(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function kF5(e){let r=await new YuS.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 eQ5({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await kuS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=Qjn(u.name);if(p==null){f.logger.debug(`Skipping unknown generator: ${u.name}`);return}let h=await sHt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});h!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:h})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await kuS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let f=Qjn(s.name);if(f==null){u.logger.debug(`Skipping unknown generator: ${s.name}`);return}let p=await sHt({generatorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function kuS({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 cAe({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?DU(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function esS(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 d=p2(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function E_c({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await eQ5({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...esS(s,d,t.logger));else o.push(...esS(c.versions,void 0,t.logger))}return o}async function Kbn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:Pto(e.packageName,{version:t?"prerelease":"latest"})}var tsS=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],S_c=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Kn.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new IAn(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"3.65.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ke.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new gS}failWithoutThrowing(t,r){this.didSucceed=!1,vka({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await ula()).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 ZuS({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
2480
2480
|
`)||(r+=`
|
|
2481
2481
|
`),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=kRc(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 S8o(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 gS}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await ula()).sendEvent(t)}logger=j7((t,...r)=>this.log(t,...r));stderr=j7((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=rsS(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?rsS(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=tsS[this.numTasks++%tsS.length],o=Ke.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===zA.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=>P3.indexOf(n.level)>=P3.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Kn.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 Kbn({cliEnvironment:this.environment,includePreReleases:t}),i=p2(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await E_c({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await MNp({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Ke.yellow("?"),style:{answer:n=>Ke.cyan(n),message:n=>Ke.bold(n),highlight:n=>Ke.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
|
|
2482
2482
|
Cancelled by user.`),new gS):i}}async getInput(t){return await wNp({message:t.message,default:t.default})}};function rsS(e){return`[${e}]:`}var isS=require("fs/promises");async function BNp({context:e,nameOverride:t,...r}){let i=await JM(t);return i==null?e.failAndThrow(`Directory "${t??ME}" not found.`):await nsS({absolutePathToFernDirectory:i,context:e,nameOverride:t,...r})}async function nsS({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n,context:a}){let o=[];(await ii(ut(e,me.of(F7)))||await ii(ut(e,me.of(HM)))||await ii(ut(e,me.of(GM)))||await ii(ut(e,me.of(kda)))||await ii(ut(e,me.of(Cto)))||await ii(ut(e,me.of(VYc))))&&(o=await asS({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n}));let c=await HPp({fernDirectory:e,context:a});return o.length===0&&c==null?a.failAndThrow(`No SDK specifications or docs specifications found. Please ensure one of the following .yml (not .yaml) files is present:
|
|
@@ -2512,7 +2512,7 @@ The generator configuration must be an object with a 'name' property, but the cu
|
|
|
2512
2512
|
|
|
2513
2513
|
Please check your generators.yml file and ensure the generator is properly configured.`);let o=n,c=await psS({generatorName:t,logger:a});if(c==null)return;let d=rQ5({migrations:c.migrations,from:r,to:i,logger:a});if(d.length!==0)return hsS({migrations:d,config:o,logger:a})}function _sS(e){return{"fernapi/fern-typescript-sdk":"https://buildwithfern.com/learn/sdks/generators/typescript/changelog","fernapi/fern-typescript-node-sdk":"https://buildwithfern.com/learn/sdks/generators/typescript/changelog","fernapi/fern-python-sdk":"https://buildwithfern.com/learn/sdks/generators/python/changelog","fernapi/fern-go-sdk":"https://buildwithfern.com/learn/sdks/generators/go/changelog","fernapi/fern-java-sdk":"https://buildwithfern.com/learn/sdks/generators/java/changelog","fernapi/fern-csharp-sdk":"https://buildwithfern.com/learn/sdks/generators/csharp/changelog","fernapi/fern-php-sdk":"https://buildwithfern.com/learn/sdks/generators/php/changelog","fernapi/fern-ruby-sdk":"https://buildwithfern.com/learn/sdks/generators/ruby/changelog","fernapi/fern-swift-sdk":"https://buildwithfern.com/learn/sdks/generators/swift/changelog"}[e]}async function nQ5({absolutePathToWorkspace:e,context:t,generatorFilter:r,groupFilter:i,includeMajor:n,channel:a,cliVersion:o}){let c=await kki({absolutePathToWorkspace:e});if(c==null||!await ii(c))return t.logger.debug("Generators configuration file was not found, no generators to upgrade."),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};let d=await(0,I_c.readFile)(c);t.logger.debug(`Found generators: ${d.toString()}`);let s=wGa.default.parseDocument(d.toString()),u=s.get("groups");if(u==null)return t.logger.debug("No groups were found within the generators configuration, no generators to upgrade."),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};if(!wGa.default.isMap(u))return t.failAndThrow(`Expected 'groups' to be a map in ${D8o.default.relative(process.cwd(),c)}`),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};t.logger.debug(`Groups found: ${u.toString()}`);let f=[],p=[],h=[];for(let _ of u.items){let y=_.key.value,b=_.value;if(!wGa.default.isMap(b)){t.failAndThrow(`Expected group ${y} to be a map in ${D8o.default.relative(process.cwd(),c)}`);continue}if(i!=null&&i!==y){t.logger.debug(`Skipping group ${y} as it does not match the filter: ${i}`);continue}let v=b.get("generators");if(!wGa.default.isSeq(v)){t.failAndThrow(`Expected group ${y} to have a 'generators' key in ${D8o.default.relative(process.cwd(),c)}`);continue}t.logger.debug(`Generators found: ${v.toString()}`);for(let O of v.items){wGa.default.isMap(O)||t.failAndThrow(`Expected generator in group ${y} to be a map in ${D8o.default.relative(process.cwd(),c)}`);let m=O.get("name"),g=Qjn(m);if(g==null){t.logger.warn(`Skipping unrecognized generator: ${m}. The generator will not be upgraded.`);continue}let A=r!=null?DU(r):void 0;if(A!=null&&g!==A){t.logger.debug(`Skipping generator ${m} as it does not match the filter: ${r}`);continue}let j=O.get("version"),S=await sHt({generatorName:g,cliVersion:o,currentGeneratorVersion:j,channel:a,includeMajor:n,context:t}),w=S??j;if(S!=null)if(S!==j){t.logger.debug(Ke.green(`Upgrading ${m} from ${j} to ${S}`)),O.set("version",S);let E=0,I=[],q=O.toJSON(),R=await CNp({generatorName:g,from:j,to:S,config:q,logger:t.logger});if(R!=null){E=R.migrationsApplied,I=R.appliedVersions;let T=new Set(Object.keys(q)),K=new Set(Object.keys(R.config));for(let G of T)K.has(G)||O.delete(G);for(let[G,z]of Object.entries(R.config))O.set(G,z);t.logger.debug(Ke.dim(`Applied ${E} migration(s): ${I.join(", ")}`))}p.push({generatorName:m,groupName:y,previousVersion:j,newVersion:S,migrationsApplied:E>0?E:void 0,migrationVersions:I.length>0?I:void 0})}else t.logger.debug(Ke.gray(`${m} is already on the latest version: ${j}`)),h.push({generatorName:m,groupName:y,version:j});if(!n){let E=await sHt({generatorName:g,cliVersion:o,currentGeneratorVersion:w,channel:a,includeMajor:!0,context:t});if(E!=null){let I=qNp.default.parse(w),q=qNp.default.parse(E);I!=null&&q!=null&&q.major>I.major&&f.push({generatorName:m,currentVersion:w,latestMajorVersion:E})}}}}return{updatedConfiguration:s.toString(),skippedMajorUpgrades:f,appliedUpgrades:p,alreadyUpToDate:h}}async function ysS({cliContext:e,generator:t,group:r,project:{apiWorkspaces:i},includeMajor:n,channel:a}){let o=[],c=[],d=[];if(await Promise.all(i.map(async s=>{await e.runTaskForWorkspace(s,async u=>{let f=await X_a({absolutePathToWorkspace:s.absoluteFilePath,context:u})??{};if(f==null||f.groups==null){u.logger.debug("No groups were found within the generators configuration, no generators to upgrade.");return}s.workspaceName==null?u.logger.info("Upgrading generators."):u.logger.info(`Upgrading generators in workspace: ${s.workspaceName}.`);let p=await nQ5({absolutePathToWorkspace:s.absoluteFilePath,context:u,generatorFilter:t,groupFilter:r,includeMajor:n,channel:a,cliVersion:e.environment.packageVersion}),h=await kki({absolutePathToWorkspace:s.absoluteFilePath});h!=null&&p.updatedConfiguration!=null&&await(0,I_c.writeFile)(h,p.updatedConfiguration),o.push(...p.skippedMajorUpgrades),p.appliedUpgrades.length>0&&c.push({workspace:s.workspaceName,upgrades:p.appliedUpgrades}),p.alreadyUpToDate.length>0&&d.push({workspace:s.workspaceName,upToDate:p.alreadyUpToDate})})})),c.length>0){e.logger.info(""),e.logger.info(Ke.green("Successfully upgraded generators:"));for(let{workspace:s,upgrades:u}of c){let f=new Map;for(let p of u){let h=f.get(p.groupName)??[];h.push(p),f.set(p.groupName,h)}for(let[p,h]of f){let _=s!=null?`[${s}] `:"";e.logger.info(Ke.green(`${_}Group ${p}:`));for(let y of h){e.logger.info(Ke.green(` - ${y.generatorName}: ${Ke.dim(y.previousVersion)} \u2192 ${y.newVersion}`)),y.migrationsApplied!=null&&y.migrationsApplied>0&&e.logger.info(Ke.dim(` Applied ${y.migrationsApplied} migration(s): ${y.migrationVersions?.join(", ")??""}`));let b=_sS(DU(y.generatorName));b!=null&&e.logger.info(Ke.dim(` Changelog: ${b}`))}}}}if(d.length>0){e.logger.info(""),e.logger.info(Ke.dim("Generators already on latest version:"));for(let{workspace:s,upToDate:u}of d){let f=new Map;for(let p of u){let h=f.get(p.groupName)??[];h.push(p),f.set(p.groupName,h)}for(let[p,h]of f){let _=s!=null?`[${s}] `:"";e.logger.info(Ke.dim(`${_}Group ${p}:`));for(let y of h)e.logger.info(Ke.dim(` - ${y.generatorName}: ${y.version} (latest)`))}}}if(c.length===0&&d.length===0){let s=r!=null?` for group ${r}`:t!=null?` for generator ${t}`:"";e.logger.info(""),e.logger.info(Ke.gray(`No generators found${s}.`))}if(o.length>0){e.logger.info(""),e.logger.info(Ke.yellow("Major version upgrades available:"));for(let s of o){e.logger.info(Ke.yellow(` - ${s.generatorName}: ${s.currentVersion} \u2192 ${s.latestMajorVersion}`));let u=t!=null?`fern generator upgrade --generator ${s.generatorName} --include-major`:"fern generator upgrade --include-major";e.logger.info(Ke.yellow(` Run: ${u}`));let f=_sS(DU(s.generatorName));f!=null&&e.logger.info(Ke.yellow(` Changelog: ${f}`))}}}function gsS(e,t){e.command("organization",!1,r=>r.option("output",{string:!0,alias:"o",description:"The location to output the organization name as a text file, defaults to standard out."}),async r=>{await t.instrumentPostHogEvent({command:"fern organization",properties:{outputLocation:r.output}}),await fsS({project:await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),context:t,outputLocation:r.output})})}function OsS(e,t){e.command("generator","Operate on the generators within your Fern configuration",r=>{r.command("list",!1,i=>i.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generators",{string:!0,type:"array",description:"The type of generator to include in the list, ex: `fern-typescript-node-sdk`. If omitted, all generators will be listed."}).option("groups",{type:"array",string:!0,description:"The groups to include generators from, if group is not specified, the all generators of the specified type will be listed."}).option("apis",{type:"array",string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("api-fallback",{string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("include-mode",{choices:Object.values(jGa),type:"array",description:"The generator output modes to include within the outputted list."}).option("exclude-mode",{choices:Object.values(jGa),type:"array",description:"The generator output modes to exclude within the outputted list."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator list",properties:{outputLocation:i.output}}),await ssS({project:await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),generatorFilter:i.generators?new Set(i.generators):void 0,groupFilter:i.groups?new Set(i.groups):void 0,apiFilter:i.apis?new Set(i.apis):void 0,apiKeyFallback:i.apiFallback,cliContext:t,outputLocation:i.output,includedModes:i["include-mode"]?new Set(i["include-mode"]):void 0,excludedModes:i["exclude-mode"]?new Set(i["exclude-mode"]):void 0})}).command("upgrade",`Upgrades the specified generator in ${GM} to the latest stable version.`,i=>i.option("generator",{string:!0,description:"The type of generator to upgrade, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,description:"The group in which the generator is located, if group is not specified, the all generators of the specified type will be upgraded."}).option("api",{string:!0,description:"The API to upgrade the generator for. If not specified, the generator will be upgraded for all APIs."}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to any prompts that may appear during the upgrade process."}).option("include-major",{boolean:!0,default:!1,description:"Whether or not to include major versions within the upgrade. Defaults to false, meaning major versions will be skipped."}).option("channel",{demandOption:!1,choices:Object.values(bsS.FernRegistry.generators.ReleaseType)}).option("list",{demandOption:!1,boolean:!0,default:!1,description:"When specified, a list of available upgrades will be displayed, but no upgrade will be taken."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator upgrade",properties:{generator:i.generator,version:i.version,api:i.api,group:i.group,includeMajor:i.includeMajor,rc:i.rc}});let n=await Em(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0});if(i.list){t.suppressUpgradeMessage();let a=await E_c({cliContext:t,project:n,generatorFilter:i.generator,groupFilter:i.group,includeMajor:i.includeMajor,channel:i.channel}),o=await INp({generatorUpgradeInfo:a,header:`Generator Upgrades
|
|
2514
2514
|
`,includeBoxen:!0});o!=null&&t.logger.info(o)}else await ysS({cliContext:t,generator:i.generator,group:i.group,project:await Em(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0}),includeMajor:i.includeMajor,channel:i.channel})}).command("get",!1,i=>i.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generator",{string:!0,demandOption:!0,description:"The name of the generator to get, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,demandOption:!0,description:"The group in which the generator is located."}).option("api",{string:!0,description:"The API in which the generator is located."}).option("version",{boolean:!0,default:!1,description:"Get the version of the specified generator."}).option("language",{boolean:!0,default:!1,description:"Get the language of the specified generator."}).option("repository",{boolean:!0,default:!1,description:"Get repository for the generator invocation, if one is specified."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator get",properties:{generator:i.generator,version:i.version,api:i.api,group:i.group,includeMajor:i.includeMajor}});let n=await csS({cliContext:t,generatorFilter:i.generator,groupFilter:i.group,apiFilter:i.api,project:await Em(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0})});if(n==null){let o=i.api?` for API ${i.api}`:"";t.failAndThrow(`Generator ${i.generator}, in group ${i.group}${o} was not found.`)}let a={};if(i.version&&(a.version=n.version,i.output==null)){process.stdout.write(n.version);return}if(i.language)if(n.language!=null){if(a.language=n.language,i.output==null){process.stdout.write(n.language);return}}else t.logger.warn(`Language information is not available for generator ${n.name} in group ${i.group}`);if(i.repository){let o=n.outputMode.type==="github"?n.outputMode.repo:n.outputMode.type==="githubV2"?n.outputMode.githubV2.repo:void 0;if(o!=null){if(a.repository=o,i.output==null){process.stdout.write(a.repository);return}}else t.logger.warn(`Repository information is not available for generator ${n.name} in group ${i.group}`)}if(i.output)try{await(0,vsS.writeFile)(i.output,JSON.stringify(a,null,2))}catch(o){t.failAndThrow(`Could not write file to the specified location: ${i.output}`,o)}})})}var msS=require("fs/promises");async function AsS({project:{apiWorkspaces:e},generatorName:t,groupName:r,cliContext:i}){await Promise.all(e.map(async n=>{await i.runTaskForWorkspace(n,async a=>{let o=await X_a({absolutePathToWorkspace:n.absoluteFilePath,context:a})??{},c=await anl({generatorName:t,generatorsConfiguration:o,groupName:r,context:a,cliVersion:i.environment.packageVersion}),d=n.generatorsConfiguration?.absolutePathToConfiguration??await kki({absolutePathToWorkspace:n.absoluteFilePath});d!=null&&(await(0,msS.writeFile)(d,`# yaml-language-server: $schema=https://schema.buildwithfern.dev/generators-yml.json
|
|
2515
|
-
`+Mi.dump(c)),a.logger.info(Ke.green(`Added ${t} generator`)))})}))}var jsS=require("fs/promises"),wsS=ce(_Z(),1);async function EsS({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new cno,o=aQ5(await a.check({from:await PsS({context:e,filepath:t,flagName:"from"}),to:await PsS({context:e,filepath:r,flagName:"to"})})),c=sQ5(e,n),{bump:d,errors:s}=oQ5(o,c);if(i==null)return{bump:d??"patch",errors:s};if(d==="no_change")return{bump:"no_change",nextVersion:i,errors:s};let u=d??"patch",f=wsS.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new gS;return{bump:u,nextVersion:f,errors:s}}async function PsS({context:e,filepath:t,flagName:r}){let i=vr.of(xo(AO(),t));if(!await ii(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new gS;let n=await(0,jsS.readFile)(i,"utf-8"),a=ca.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new gS;return a.value}function aQ5(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function oQ5(e,t){return{bump:uQ5(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function uQ5(e,t){if(!(e===void 0&&t===void 0))return e==="no_change"&&(t===void 0||t==="no_change")||t==="no_change"&&(e===void 0||e==="no_change")?"no_change":e===void 0?t:t===void 0?e:e==="no_change"?t:t==="no_change"?e:e==="major"||t==="major"?"major":e==="minor"||t==="minor"?"minor":"patch"}function sQ5(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=cQ5(Nzc(r,i)),a=[];return n==="major"&&a.push("Generator version changed by major version."),{bump:n,errors:a}}catch(n){throw e.failWithoutThrowing(`Error diffing generator versions ${r} and ${i}: ${n}`),new gS}}function cQ5(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}vE();var L_S=ce(zNp(),1),V_S=ce(_yc(),1),Jyc=require("fs/promises"),W_S=ce(require("http"),1),x_S=ce(require("path"),1);var ApS=require("events"),Oyc=ce(require("fs"),1),xra=ce(require("path"),1);var npS=ce(require("os"),1),apS=300,evn=20,exo=1e7,opS=npS.default.platform();var O85=opS==="darwin",tQp=opS==="win32",tvn=O85||tQp,upS=3e3,spS=2e4,rQp=1250;var n4i;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(n4i||(n4i={}));var Wra;(function(e){e.CHANGE="change",e.RENAME="rename"})(Wra||(Wra={}));var txo;(function(e){e.CHANGE="change",e.ERROR="error"})(txo||(txo={}));var zf;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(zf||(zf={}));var hX;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(hX||(hX={}));var m85=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),A=g-d,j=g-s,S=A>=t||j>=a;return[g,S]},f=g=>{if(s=g,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{O(0)},h=()=>{c&&(p(),f(Date.now()))},_=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,A]=u();return A?y(g):v(g)},v=g=>{let A=g-d,j=g-s,S=t-A,w=a-j,E=Math.min(S,w);return O(E)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},m=(...g)=>{let[A,j]=u(),S=!!c;if(o=g,d=A,(j||!c)&&O(t),j)return S?f(A):_(A)};return m.cancel=p,m.flush=h,m},yyc=m85;var oQp=ce(require("fs"),1),vyc=ce(require("path"),1);var EA=ce(require("fs"),1),Kx=require("util");var gJi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},a4i=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var iQp=ce(require("process"),1),cpS=iQp.default.getuid?!iQp.default.getuid():!1,lpS=1e4,YOe=()=>{};var rxo={isChangeErrorOk:e=>{if(!rxo.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!cpS&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!rxo.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!rxo.isNodeError(e))throw e;if(!rxo.isChangeErrorOk(e))throw e}},NT=rxo;var nQp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=lpS,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},fpS=new nQp;var OJi=(e,t)=>function(i){return function n(...a){return fpS.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},mJi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var A85={attempt:{chmod:gJi((0,Kx.promisify)(EA.default.chmod),NT.onChangeError),chown:gJi((0,Kx.promisify)(EA.default.chown),NT.onChangeError),close:gJi((0,Kx.promisify)(EA.default.close),YOe),fsync:gJi((0,Kx.promisify)(EA.default.fsync),YOe),mkdir:gJi((0,Kx.promisify)(EA.default.mkdir),YOe),realpath:gJi((0,Kx.promisify)(EA.default.realpath),YOe),stat:gJi((0,Kx.promisify)(EA.default.stat),YOe),unlink:gJi((0,Kx.promisify)(EA.default.unlink),YOe),chmodSync:a4i(EA.default.chmodSync,NT.onChangeError),chownSync:a4i(EA.default.chownSync,NT.onChangeError),closeSync:a4i(EA.default.closeSync,YOe),existsSync:a4i(EA.default.existsSync,YOe),fsyncSync:a4i(EA.default.fsync,YOe),mkdirSync:a4i(EA.default.mkdirSync,YOe),realpathSync:a4i(EA.default.realpathSync,YOe),statSync:a4i(EA.default.statSync,YOe),unlinkSync:a4i(EA.default.unlinkSync,YOe)},retry:{close:OJi((0,Kx.promisify)(EA.default.close),NT.isRetriableError),fsync:OJi((0,Kx.promisify)(EA.default.fsync),NT.isRetriableError),open:OJi((0,Kx.promisify)(EA.default.open),NT.isRetriableError),readFile:OJi((0,Kx.promisify)(EA.default.readFile),NT.isRetriableError),rename:OJi((0,Kx.promisify)(EA.default.rename),NT.isRetriableError),stat:OJi((0,Kx.promisify)(EA.default.stat),NT.isRetriableError),write:OJi((0,Kx.promisify)(EA.default.write),NT.isRetriableError),writeFile:OJi((0,Kx.promisify)(EA.default.writeFile),NT.isRetriableError),closeSync:mJi(EA.default.closeSync,NT.isRetriableError),fsyncSync:mJi(EA.default.fsyncSync,NT.isRetriableError),openSync:mJi(EA.default.openSync,NT.isRetriableError),readFileSync:mJi(EA.default.readFileSync,NT.isRetriableError),renameSync:mJi(EA.default.renameSync,NT.isRetriableError),statSync:mJi(EA.default.statSync,NT.isRetriableError),writeSync:mJi(EA.default.writeSync,NT.isRetriableError),writeFileSync:mJi(EA.default.writeFileSync,NT.isRetriableError)}},dpS=A85;var byc=ce(require("fs"),1),ixo=ce(require("path"),1);var aQp=()=>{};var P85=()=>{let e=aQp,t=aQp,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},ppS=P85;var j85=()=>{let{promise:e,resolve:t,isPending:r}=ppS(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return n(),queueMicrotask(a),{promise:e,isPending:r,increment:n,decrement:a}},hpS=j85;var _pS={then:e=>{e()}};var ypS=e=>Array.isArray(e)?e:[e],bpS=e=>typeof e=="function";var w85=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=ypS(a).map(L=>bpS(L)?L:Q=>L.test(Q)),c=L=>o.some(Q=>Q(L)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},h=[],_=new Set,y={},b=[],v=new Set,O={},m={},g=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:h,filesNames:_,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:m},{promise:S,increment:w,decrement:E}=hpS(),I=0,q=(L,Q,se,ae)=>{g.has(Q)||I>=n||(I+=1,L.directories.push(Q),L.directoriesNames.add(se),u.push(Q),f.add(se),p.propertyIsEnumerable(se)||(p[se]=[]),p[se].push(Q),g.add(Q),!(ae>=i)&&(I>=n||W(Q,ae+1)))},R=(L,Q,se)=>{g.has(Q)||I>=n||(I+=1,L.files.push(Q),L.filesNames.add(se),h.push(Q),_.add(se),y.propertyIsEnumerable(se)||(y[se]=[]),y[se].push(Q),g.add(Q))},T=(L,Q,se,ae)=>{g.has(Q)||I>=n||(I+=1,L.symlinks.push(Q),L.symlinksNames.add(se),b.push(Q),v.add(se),O.propertyIsEnumerable(se)||(O[se]=[]),O[se].push(Q),g.add(Q),r&&(ae>=i||I>=n||Oe(Q,ae+1)))},K=(L,Q,se,ae,de)=>{d.aborted||c(Q)||(ae.isDirectory()?q(L,Q,se,de):ae.isFile()?R(L,Q,se):ae.isSymbolicLink()&&T(L,Q,se,de))},G=(L,Q,se,ae)=>{if(d.aborted)return;let de=Q===ixo.default.sep?"":ixo.default.sep,ge=se.name,re=`${Q}${de}${ge}`;c(re)||(se.isDirectory()?q(L,re,ge,ae):se.isFile()?R(L,re,ge):se.isSymbolicLink()&&T(L,re,ge,ae))},z=(L,Q,se,ae)=>{for(let de=0,ge=se.length;de<ge;de++)G(L,Q,se[de],ae)},W=(L,Q)=>{d.aborted||Q>i||I>=n||(w(),byc.default.readdir(L,{withFileTypes:!0},(se,ae)=>{if(se||d.aborted||!ae.length)return E();(s(ae)||_pS).then(()=>{let ge=m[L]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(ge,L,ae,Q),E()})}))},Oe=(L,Q)=>{w(),byc.default.realpath(L,(se,ae)=>{if(se||d.aborted)return E();byc.default.stat(ae,(de,ge)=>{if(de||d.aborted)return E();let re=ixo.default.basename(ae),X=m[L]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};K(X,ae,re,ge,Q),E()})})};return(async(L,Q=1)=>(L=ixo.default.normalize(L),g.add(L),W(L,Q),await S,d.aborted?A:j))(e)},vpS=w85;var o4i={lang:{debounce:yyc,attempt:e=>{try{return e()}catch(t){return o4i.lang.castError(t)}},castArray:e=>o4i.lang.isArray(e)?e:[e],castError:e=>o4i.lang.isError(e)?e:o4i.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(o4i.lang.isNaN(e))return o4i.lang.isNaN(t);if(o4i.lang.isPrimitive(e)||o4i.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(vyc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?oQp.default.realpathSync.native(e):oQp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===vyc.default.sep&&t.length-e.length>vyc.default.sep.length,poll:(e,t=spS)=>dpS.retry.stat(t)(e,{bigint:!0}).catch(o4i.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await vpS(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},M_=o4i;var gyc=ce(require("path"),1);var uQp=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||M_.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=apS){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=M_.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===zf.CHANGE&&c===zf.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===zf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===zf.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??evn:Math.min(1,this.options.depth??evn),o=this.options.limit??exo,[c,d]=await M_.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())M_.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(zf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!tvn&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(zf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(zf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(gyc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(zf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(gyc.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(zf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===zf.ADD?this.onTargetAdd(i):r===zf.ADD_DIR?this.onTargetAddDir(i):r===zf.CHANGE?this.onTargetChange(i):r===zf.UNLINK?this.onTargetUnlink(i):r===zf.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Wra.CHANGE,r){if(this.watcher.isClosed())return;let i=gyc.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){tQp&&t.code==="EPERM"?this.onWatcherChange(Wra.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(txo.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(txo.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Wra.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&tvn&&this.options.native!==!1?this.options.depth??evn:Math.min(1,this.options.depth??evn),i=this.options.limit??exo,[n,a]=await M_.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(Wra.CHANGE,c,t)}))}}},gpS=uQp;var _X={interval:100,intervalId:void 0,fns:new Map,init:()=>{_X.intervalId||(_X.intervalId=setInterval(_X.resolve,_X.interval))},reset:()=>{_X.intervalId&&(clearInterval(_X.intervalId),delete _X.intervalId)},add:(e,t)=>{_X.fns.set(e,Date.now()+t),_X.init()},remove:e=>{_X.fns.delete(e)},resolve:()=>{if(!_X.fns.size)return _X.reset();let e=Date.now();for(let[t,r]of _X.fns)r>=e||(_X.remove(t),t())}},nxo=_X;var axo=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=rQp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(M_.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),nxo.remove(s)},s=()=>{d(),c()};nxo.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=rQp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),nxo.remove(s)},s=()=>{d(),c()};nxo.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,zf.ADD,n4i.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,zf.ADD_DIR,n4i.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,zf.UNLINK,n4i.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,zf.UNLINK_DIR,n4i.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};axo.DIR_EVENTS={add:zf.ADD_DIR,rename:zf.RENAME_DIR,unlink:zf.UNLINK_DIR};axo.FILE_EVENTS={add:zf.ADD,change:zf.CHANGE,rename:zf.RENAME,unlink:zf.UNLINK};var OpS=axo;var sQp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(M_.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(M_.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(M_.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(M_.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return M_.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);M_.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},cQp=sQp;var lQp=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},mpS=lQp;var fQp=class{constructor(){this.inos={},this.paths=new cQp,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await M_.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new mpS(i)}reset(){this.inos={},this.paths=new cQp,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,zf.ADD,n),[zf.ADD];if(n.isDirectory())return this.updateIno(t,zf.ADD_DIR,n),[zf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,zf.UNLINK,i),[zf.UNLINK];if(i.isDirectory())return this.updateIno(t,zf.UNLINK_DIR,i),[zf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,zf.CHANGE,n),[zf.CHANGE]);if(n.isDirectory())return this.updateIno(t,zf.UNLINK,i),this.updateIno(t,zf.ADD_DIR,n),[zf.UNLINK,zf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,zf.UNLINK_DIR,i),this.updateIno(t,zf.ADD,n),[zf.UNLINK_DIR,zf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,zf.UNLINK_DIR,i),this.updateIno(t,zf.ADD_DIR,n),[zf.UNLINK_DIR,zf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?n4i.FILE:n4i.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},dQp=fQp;var pQp=class e extends ApS.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(hX.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(hX.CLOSE,n)),this._readyWait=new Promise(n=>this.on(hX.READY,n)),this._locker=new OpS(this),this._roots=new Set,this._poller=new dQp,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(M_.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(hX.CLOSE))}error(t){if(this.isClosed())return!1;let r=M_.lang.castError(t);return this.emit(hX.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(hX.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(hX.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&M_.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&M_.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)M_.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new gpS(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=M_.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=xra.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??evn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&tvn&&u.options.native!==!1)))return!0;if(!tvn)break;let s=xra.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=M_.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||tvn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:Oyc.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let h={...r,ignoreInitial:!0,recursive:!1},_=xra.default.dirname(c),y=c;await this.watchDirectories([_],h,i,y,f)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||tvn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??evn,c=r.limit??exo,[d]=await M_.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=M_.fs.getDepth(t);for(let f of d){let p=M_.fs.getDepth(f),h=Math.max(0,o-(p-u)),_={...r,depth:h};await this.watchDirectories([f],_,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(hX.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(hX.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=xra.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new dQp,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return M_.lang.noop;if(this.pollerExists(t,r))return M_.lang.noop;let n={...r,interval:r.pollingInterval??upS},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(hX.CLOSE,c),Oyc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(hX.CLOSE,c),Oyc.default.unwatchFile(t,i)};return M_.lang.attempt(o),()=>M_.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=M_.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!M_.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=xra.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await M_.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=xra.default.dirname(t);return(await M_.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=M_.lang.noop){if(M_.lang.isFunction(t))return this.watch([],{},t);if(M_.lang.isUndefined(t))return this.watch([],r,i);if(M_.lang.isFunction(r))return this.watch(t,{},r);if(M_.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=M_.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==M_.lang.noop&&this.on(hX.ALL,i),r.readdirMap=void 0,this.ready())}},myc=pQp;tdc();var LGa=require("fs/promises"),PpS=require("os"),jpS=ce(require("path"),1),E85=".fern",S85="logs";function M85(){return"cli@3.64.6"}var oxo=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=ut(vr.of((0,PpS.homedir)()),me.of(E85)),r=ut(t,me.of(S85));await ii(r)||await(0,LGa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ut(r,me.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${jpS.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2515
|
+
`+Mi.dump(c)),a.logger.info(Ke.green(`Added ${t} generator`)))})}))}var jsS=require("fs/promises"),wsS=ce(_Z(),1);async function EsS({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new cno,o=aQ5(await a.check({from:await PsS({context:e,filepath:t,flagName:"from"}),to:await PsS({context:e,filepath:r,flagName:"to"})})),c=sQ5(e,n),{bump:d,errors:s}=oQ5(o,c);if(i==null)return{bump:d??"patch",errors:s};if(d==="no_change")return{bump:"no_change",nextVersion:i,errors:s};let u=d??"patch",f=wsS.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new gS;return{bump:u,nextVersion:f,errors:s}}async function PsS({context:e,filepath:t,flagName:r}){let i=vr.of(xo(AO(),t));if(!await ii(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new gS;let n=await(0,jsS.readFile)(i,"utf-8"),a=ca.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new gS;return a.value}function aQ5(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function oQ5(e,t){return{bump:uQ5(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function uQ5(e,t){if(!(e===void 0&&t===void 0))return e==="no_change"&&(t===void 0||t==="no_change")||t==="no_change"&&(e===void 0||e==="no_change")?"no_change":e===void 0?t:t===void 0?e:e==="no_change"?t:t==="no_change"?e:e==="major"||t==="major"?"major":e==="minor"||t==="minor"?"minor":"patch"}function sQ5(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=cQ5(Nzc(r,i)),a=[];return n==="major"&&a.push("Generator version changed by major version."),{bump:n,errors:a}}catch(n){throw e.failWithoutThrowing(`Error diffing generator versions ${r} and ${i}: ${n}`),new gS}}function cQ5(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}vE();var L_S=ce(zNp(),1),V_S=ce(_yc(),1),Jyc=require("fs/promises"),W_S=ce(require("http"),1),x_S=ce(require("path"),1);var ApS=require("events"),Oyc=ce(require("fs"),1),xra=ce(require("path"),1);var npS=ce(require("os"),1),apS=300,evn=20,exo=1e7,opS=npS.default.platform();var O85=opS==="darwin",tQp=opS==="win32",tvn=O85||tQp,upS=3e3,spS=2e4,rQp=1250;var n4i;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(n4i||(n4i={}));var Wra;(function(e){e.CHANGE="change",e.RENAME="rename"})(Wra||(Wra={}));var txo;(function(e){e.CHANGE="change",e.ERROR="error"})(txo||(txo={}));var zf;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(zf||(zf={}));var hX;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(hX||(hX={}));var m85=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),A=g-d,j=g-s,S=A>=t||j>=a;return[g,S]},f=g=>{if(s=g,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{O(0)},h=()=>{c&&(p(),f(Date.now()))},_=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,A]=u();return A?y(g):v(g)},v=g=>{let A=g-d,j=g-s,S=t-A,w=a-j,E=Math.min(S,w);return O(E)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},m=(...g)=>{let[A,j]=u(),S=!!c;if(o=g,d=A,(j||!c)&&O(t),j)return S?f(A):_(A)};return m.cancel=p,m.flush=h,m},yyc=m85;var oQp=ce(require("fs"),1),vyc=ce(require("path"),1);var EA=ce(require("fs"),1),Kx=require("util");var gJi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},a4i=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var iQp=ce(require("process"),1),cpS=iQp.default.getuid?!iQp.default.getuid():!1,lpS=1e4,YOe=()=>{};var rxo={isChangeErrorOk:e=>{if(!rxo.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!cpS&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!rxo.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!rxo.isNodeError(e))throw e;if(!rxo.isChangeErrorOk(e))throw e}},NT=rxo;var nQp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=lpS,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},fpS=new nQp;var OJi=(e,t)=>function(i){return function n(...a){return fpS.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},mJi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var A85={attempt:{chmod:gJi((0,Kx.promisify)(EA.default.chmod),NT.onChangeError),chown:gJi((0,Kx.promisify)(EA.default.chown),NT.onChangeError),close:gJi((0,Kx.promisify)(EA.default.close),YOe),fsync:gJi((0,Kx.promisify)(EA.default.fsync),YOe),mkdir:gJi((0,Kx.promisify)(EA.default.mkdir),YOe),realpath:gJi((0,Kx.promisify)(EA.default.realpath),YOe),stat:gJi((0,Kx.promisify)(EA.default.stat),YOe),unlink:gJi((0,Kx.promisify)(EA.default.unlink),YOe),chmodSync:a4i(EA.default.chmodSync,NT.onChangeError),chownSync:a4i(EA.default.chownSync,NT.onChangeError),closeSync:a4i(EA.default.closeSync,YOe),existsSync:a4i(EA.default.existsSync,YOe),fsyncSync:a4i(EA.default.fsync,YOe),mkdirSync:a4i(EA.default.mkdirSync,YOe),realpathSync:a4i(EA.default.realpathSync,YOe),statSync:a4i(EA.default.statSync,YOe),unlinkSync:a4i(EA.default.unlinkSync,YOe)},retry:{close:OJi((0,Kx.promisify)(EA.default.close),NT.isRetriableError),fsync:OJi((0,Kx.promisify)(EA.default.fsync),NT.isRetriableError),open:OJi((0,Kx.promisify)(EA.default.open),NT.isRetriableError),readFile:OJi((0,Kx.promisify)(EA.default.readFile),NT.isRetriableError),rename:OJi((0,Kx.promisify)(EA.default.rename),NT.isRetriableError),stat:OJi((0,Kx.promisify)(EA.default.stat),NT.isRetriableError),write:OJi((0,Kx.promisify)(EA.default.write),NT.isRetriableError),writeFile:OJi((0,Kx.promisify)(EA.default.writeFile),NT.isRetriableError),closeSync:mJi(EA.default.closeSync,NT.isRetriableError),fsyncSync:mJi(EA.default.fsyncSync,NT.isRetriableError),openSync:mJi(EA.default.openSync,NT.isRetriableError),readFileSync:mJi(EA.default.readFileSync,NT.isRetriableError),renameSync:mJi(EA.default.renameSync,NT.isRetriableError),statSync:mJi(EA.default.statSync,NT.isRetriableError),writeSync:mJi(EA.default.writeSync,NT.isRetriableError),writeFileSync:mJi(EA.default.writeFileSync,NT.isRetriableError)}},dpS=A85;var byc=ce(require("fs"),1),ixo=ce(require("path"),1);var aQp=()=>{};var P85=()=>{let e=aQp,t=aQp,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},ppS=P85;var j85=()=>{let{promise:e,resolve:t,isPending:r}=ppS(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return n(),queueMicrotask(a),{promise:e,isPending:r,increment:n,decrement:a}},hpS=j85;var _pS={then:e=>{e()}};var ypS=e=>Array.isArray(e)?e:[e],bpS=e=>typeof e=="function";var w85=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=ypS(a).map(L=>bpS(L)?L:Q=>L.test(Q)),c=L=>o.some(Q=>Q(L)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},h=[],_=new Set,y={},b=[],v=new Set,O={},m={},g=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:h,filesNames:_,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:m},{promise:S,increment:w,decrement:E}=hpS(),I=0,q=(L,Q,se,ae)=>{g.has(Q)||I>=n||(I+=1,L.directories.push(Q),L.directoriesNames.add(se),u.push(Q),f.add(se),p.propertyIsEnumerable(se)||(p[se]=[]),p[se].push(Q),g.add(Q),!(ae>=i)&&(I>=n||W(Q,ae+1)))},R=(L,Q,se)=>{g.has(Q)||I>=n||(I+=1,L.files.push(Q),L.filesNames.add(se),h.push(Q),_.add(se),y.propertyIsEnumerable(se)||(y[se]=[]),y[se].push(Q),g.add(Q))},T=(L,Q,se,ae)=>{g.has(Q)||I>=n||(I+=1,L.symlinks.push(Q),L.symlinksNames.add(se),b.push(Q),v.add(se),O.propertyIsEnumerable(se)||(O[se]=[]),O[se].push(Q),g.add(Q),r&&(ae>=i||I>=n||Oe(Q,ae+1)))},K=(L,Q,se,ae,de)=>{d.aborted||c(Q)||(ae.isDirectory()?q(L,Q,se,de):ae.isFile()?R(L,Q,se):ae.isSymbolicLink()&&T(L,Q,se,de))},G=(L,Q,se,ae)=>{if(d.aborted)return;let de=Q===ixo.default.sep?"":ixo.default.sep,ge=se.name,re=`${Q}${de}${ge}`;c(re)||(se.isDirectory()?q(L,re,ge,ae):se.isFile()?R(L,re,ge):se.isSymbolicLink()&&T(L,re,ge,ae))},z=(L,Q,se,ae)=>{for(let de=0,ge=se.length;de<ge;de++)G(L,Q,se[de],ae)},W=(L,Q)=>{d.aborted||Q>i||I>=n||(w(),byc.default.readdir(L,{withFileTypes:!0},(se,ae)=>{if(se||d.aborted||!ae.length)return E();(s(ae)||_pS).then(()=>{let ge=m[L]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(ge,L,ae,Q),E()})}))},Oe=(L,Q)=>{w(),byc.default.realpath(L,(se,ae)=>{if(se||d.aborted)return E();byc.default.stat(ae,(de,ge)=>{if(de||d.aborted)return E();let re=ixo.default.basename(ae),X=m[L]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};K(X,ae,re,ge,Q),E()})})};return(async(L,Q=1)=>(L=ixo.default.normalize(L),g.add(L),W(L,Q),await S,d.aborted?A:j))(e)},vpS=w85;var o4i={lang:{debounce:yyc,attempt:e=>{try{return e()}catch(t){return o4i.lang.castError(t)}},castArray:e=>o4i.lang.isArray(e)?e:[e],castError:e=>o4i.lang.isError(e)?e:o4i.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(o4i.lang.isNaN(e))return o4i.lang.isNaN(t);if(o4i.lang.isPrimitive(e)||o4i.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(vyc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?oQp.default.realpathSync.native(e):oQp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===vyc.default.sep&&t.length-e.length>vyc.default.sep.length,poll:(e,t=spS)=>dpS.retry.stat(t)(e,{bigint:!0}).catch(o4i.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await vpS(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},M_=o4i;var gyc=ce(require("path"),1);var uQp=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||M_.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=apS){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=M_.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===zf.CHANGE&&c===zf.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===zf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===zf.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??evn:Math.min(1,this.options.depth??evn),o=this.options.limit??exo,[c,d]=await M_.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())M_.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(zf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!tvn&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(zf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(zf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(gyc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(zf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(gyc.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(zf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===zf.ADD?this.onTargetAdd(i):r===zf.ADD_DIR?this.onTargetAddDir(i):r===zf.CHANGE?this.onTargetChange(i):r===zf.UNLINK?this.onTargetUnlink(i):r===zf.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Wra.CHANGE,r){if(this.watcher.isClosed())return;let i=gyc.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){tQp&&t.code==="EPERM"?this.onWatcherChange(Wra.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(txo.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(txo.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Wra.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&tvn&&this.options.native!==!1?this.options.depth??evn:Math.min(1,this.options.depth??evn),i=this.options.limit??exo,[n,a]=await M_.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(Wra.CHANGE,c,t)}))}}},gpS=uQp;var _X={interval:100,intervalId:void 0,fns:new Map,init:()=>{_X.intervalId||(_X.intervalId=setInterval(_X.resolve,_X.interval))},reset:()=>{_X.intervalId&&(clearInterval(_X.intervalId),delete _X.intervalId)},add:(e,t)=>{_X.fns.set(e,Date.now()+t),_X.init()},remove:e=>{_X.fns.delete(e)},resolve:()=>{if(!_X.fns.size)return _X.reset();let e=Date.now();for(let[t,r]of _X.fns)r>=e||(_X.remove(t),t())}},nxo=_X;var axo=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=rQp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(M_.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),nxo.remove(s)},s=()=>{d(),c()};nxo.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=rQp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),nxo.remove(s)},s=()=>{d(),c()};nxo.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,zf.ADD,n4i.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,zf.ADD_DIR,n4i.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,zf.UNLINK,n4i.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,zf.UNLINK_DIR,n4i.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};axo.DIR_EVENTS={add:zf.ADD_DIR,rename:zf.RENAME_DIR,unlink:zf.UNLINK_DIR};axo.FILE_EVENTS={add:zf.ADD,change:zf.CHANGE,rename:zf.RENAME,unlink:zf.UNLINK};var OpS=axo;var sQp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(M_.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(M_.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(M_.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(M_.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return M_.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);M_.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},cQp=sQp;var lQp=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},mpS=lQp;var fQp=class{constructor(){this.inos={},this.paths=new cQp,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await M_.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new mpS(i)}reset(){this.inos={},this.paths=new cQp,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,zf.ADD,n),[zf.ADD];if(n.isDirectory())return this.updateIno(t,zf.ADD_DIR,n),[zf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,zf.UNLINK,i),[zf.UNLINK];if(i.isDirectory())return this.updateIno(t,zf.UNLINK_DIR,i),[zf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,zf.CHANGE,n),[zf.CHANGE]);if(n.isDirectory())return this.updateIno(t,zf.UNLINK,i),this.updateIno(t,zf.ADD_DIR,n),[zf.UNLINK,zf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,zf.UNLINK_DIR,i),this.updateIno(t,zf.ADD,n),[zf.UNLINK_DIR,zf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,zf.UNLINK_DIR,i),this.updateIno(t,zf.ADD_DIR,n),[zf.UNLINK_DIR,zf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?n4i.FILE:n4i.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},dQp=fQp;var pQp=class e extends ApS.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(hX.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(hX.CLOSE,n)),this._readyWait=new Promise(n=>this.on(hX.READY,n)),this._locker=new OpS(this),this._roots=new Set,this._poller=new dQp,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(M_.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(hX.CLOSE))}error(t){if(this.isClosed())return!1;let r=M_.lang.castError(t);return this.emit(hX.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(hX.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(hX.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&M_.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&M_.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)M_.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new gpS(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=M_.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=xra.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??evn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&tvn&&u.options.native!==!1)))return!0;if(!tvn)break;let s=xra.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=M_.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||tvn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:Oyc.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let h={...r,ignoreInitial:!0,recursive:!1},_=xra.default.dirname(c),y=c;await this.watchDirectories([_],h,i,y,f)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||tvn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??evn,c=r.limit??exo,[d]=await M_.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=M_.fs.getDepth(t);for(let f of d){let p=M_.fs.getDepth(f),h=Math.max(0,o-(p-u)),_={...r,depth:h};await this.watchDirectories([f],_,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(hX.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(hX.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=xra.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new dQp,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return M_.lang.noop;if(this.pollerExists(t,r))return M_.lang.noop;let n={...r,interval:r.pollingInterval??upS},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(hX.CLOSE,c),Oyc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(hX.CLOSE,c),Oyc.default.unwatchFile(t,i)};return M_.lang.attempt(o),()=>M_.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=M_.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!M_.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=xra.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await M_.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=xra.default.dirname(t);return(await M_.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=M_.lang.noop){if(M_.lang.isFunction(t))return this.watch([],{},t);if(M_.lang.isUndefined(t))return this.watch([],r,i);if(M_.lang.isFunction(r))return this.watch(t,{},r);if(M_.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=M_.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==M_.lang.noop&&this.on(hX.ALL,i),r.readdirMap=void 0,this.ready())}},myc=pQp;tdc();var LGa=require("fs/promises"),PpS=require("os"),jpS=ce(require("path"),1),E85=".fern",S85="logs";function M85(){return"cli@3.65.0"}var oxo=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=ut(vr.of((0,PpS.homedir)()),me.of(E85)),r=ut(t,me.of(S85));await ii(r)||await(0,LGa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ut(r,me.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${jpS.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2516
2516
|
`);await(0,LGa.writeFile)(this.logFilePath,a,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
|
|
2517
2517
|
`;try{await(0,LGa.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let i={timestamp:t.timestamp,source:M85(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(i)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let i={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliDocsGeneration(t,r){let i={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliValidation(t,r){let i={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(i)}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var TQp=ce(AQp(),1),m_S=ce(UPp(),1),XOe=require("fs/promises"),A_S=require("os"),P_S=ce(GQ(),1),j_S=ce(g_S(),1),Qyc=process.platform==="win32",qQp=Ke.cyan("[docs]:"),k85="etag",ex5=23,O_S=e=>e.padEnd(ex5," "),tx5="preview",rx5="app-preview",ix5="bundle",nx5=".next",ax5="standalone",ox5=".fern",ux5="packages/fern-docs/bundle/.next/server/instrumentation.js",sx5=".npmrc",cx5=".pnpmfile.cjs",lx5="pnpm-workspace.yaml",fx5='Cannot find matching keyid: {"signatures":';function dx5(){return ut(vr.of((0,A_S.homedir)()),me.of(ox5))}function VGa({app:e=!1}){return ut(dx5(),me.of(e?rx5:tx5))}function nvn({app:e=!1}){return ut(VGa({app:e}),me.of(e?nx5:ix5))}function cxo({app:e=!1}){return ut(nvn({app:e}),me.of(ax5))}function px5({app:e=!1}){return ut(cxo({app:e}),me.of(ux5))}function hx5({app:e=!1}){return ut(cxo({app:e}),me.of(lx5))}function _x5({app:e=!1}){return ut(cxo({app:e}),me.of(cx5))}function yx5({app:e=!1}){return ut(cxo({app:e}),me.of(sx5))}function Kra(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function bx5({app:e=!1}){return ut(VGa({app:e}),me.of(k85))}var vx5=`module.exports = {
|
|
2518
2518
|
hooks: {
|
|
@@ -2603,7 +2603,7 @@ Found ${d.length} preview deployment(s):
|
|
|
2603
2603
|
`));for(let s of d){let u=new Date(s.updatedAt).toLocaleString();n.logger.info(` ${Ke.cyan(s.url)}`),n.logger.info(` Organization: ${s.organizationId}`),n.logger.info(` Updated: ${u}
|
|
2604
2604
|
`)}})}var QgS=require("fs/promises");var qgS=Symbol.for("immer-nothing"),SgS=Symbol.for("immer-draftable"),hSe=Symbol.for("immer-state"),o95=process.env.NODE_ENV!=="production"?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function kOe(e,...t){if(process.env.NODE_ENV!=="production"){let r=o95[e],i=typeof r=="function"?r.apply(null,t):r;throw new Error(`[Immer] ${i}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Axo=Object.getPrototypeOf;function n9a(e){return!!e&&!!e[hSe]}function iia(e){return e?TgS(e)||Array.isArray(e)||!!e[SgS]||!!e.constructor?.[SgS]||wxo(e)||Lbc(e):!1}var u95=Object.prototype.constructor.toString(),MgS=new WeakMap;function TgS(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(r===Object)return!0;if(typeof r!="function")return!1;let i=MgS.get(r);return i===void 0&&(i=Function.toString.call(r),MgS.set(r,i)),i===u95}function Nbc(e,t,r=!0){Ubc(e)===0?(r?Reflect.ownKeys(e):Object.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((i,n)=>t(n,i,e))}function Ubc(e){let t=e[hSe];return t?t.type_:Array.isArray(e)?1:wxo(e)?2:Lbc(e)?3:0}function hLp(e,t){return Ubc(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function RgS(e,t,r){let i=Ubc(e);i===2?e.set(t,r):i===3?e.add(r):e[t]=r}function s95(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function wxo(e){return e instanceof Map}function Lbc(e){return e instanceof Set}function ria(e){return e.copy_||e.base_}function _Lp(e,t){if(wxo(e))return new Map(e);if(Lbc(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=TgS(e);if(t===!0||t==="class_only"&&!r){let i=Object.getOwnPropertyDescriptors(e);delete i[hSe];let n=Reflect.ownKeys(i);for(let a=0;a<n.length;a++){let o=n[a],c=i[o];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(i[o]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[o]})}return Object.create(Axo(e),i)}else{let i=Axo(e);if(i!==null&&r)return{...e};let n=Object.create(i);return Object.assign(n,e)}}function OLp(e,t=!1){return Vbc(e)||n9a(e)||!iia(e)||(Ubc(e)>1&&Object.defineProperties(e,{set:zbc,add:zbc,clear:zbc,delete:zbc}),Object.freeze(e),t&&Object.values(e).forEach(r=>OLp(r,!0))),e}function c95(){kOe(2)}var zbc={value:c95};function Vbc(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}var l95={};function nia(e){let t=l95[e];return t||kOe(0,e),t}var Pxo;function zgS(){return Pxo}function f95(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function DgS(e,t){t&&(nia("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function yLp(e){bLp(e),e.drafts_.forEach(d95),e.drafts_=null}function bLp(e){e===Pxo&&(Pxo=e.parent_)}function IgS(e){return Pxo=f95(Pxo,e)}function d95(e){let t=e[hSe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function BgS(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[hSe].modified_&&(yLp(t),kOe(4)),iia(e)&&(e=Fbc(t,e),t.parent_||Qbc(t,e)),t.patches_&&nia("Patches").generateReplacementPatches_(r[hSe].base_,e,t.patches_,t.inversePatches_)):e=Fbc(t,r,[]),yLp(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==qgS?e:void 0}function Fbc(e,t,r){if(Vbc(t))return t;let i=e.immer_.shouldUseStrictIteration(),n=t[hSe];if(!n)return Nbc(t,(a,o)=>CgS(e,n,t,a,o,r),i),t;if(n.scope_!==e)return t;if(!n.modified_)return Qbc(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let a=n.copy_,o=a,c=!1;n.type_===3&&(o=new Set(a),a.clear(),c=!0),Nbc(o,(d,s)=>CgS(e,n,a,d,s,r,c),i),Qbc(e,a,!1),r&&e.patches_&&nia("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function CgS(e,t,r,i,n,a,o){if(n==null||typeof n!="object"&&!o)return;let c=Vbc(n);if(!(c&&!o)){if(process.env.NODE_ENV!=="production"&&n===r&&kOe(5),n9a(n)){let d=a&&t&&t.type_!==3&&!hLp(t.assigned_,i)?a.concat(i):void 0,s=Fbc(e,n,d);if(RgS(r,i,s),n9a(s))e.canAutoFreeze_=!1;else return}else o&&r.add(n);if(iia(n)&&!c){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[i]===n&&c)return;Fbc(e,n),(!t||!t.scope_.parent_)&&typeof i!="symbol"&&(wxo(r)?r.has(i):Object.prototype.propertyIsEnumerable.call(r,i))&&Qbc(e,n)}}}function Qbc(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&OLp(t,r)}function p95(e,t){let r=Array.isArray(e),i={type_:r?1:0,scope_:t?t.scope_:zgS(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=i,a=mLp;r&&(n=[i],a=jxo);let{revoke:o,proxy:c}=Proxy.revocable(n,a);return i.draft_=c,i.revoke_=o,c}var mLp={get(e,t){if(t===hSe)return e;let r=ria(e);if(!hLp(r,t))return h95(e,r,t);let i=r[t];return e.finalized_||!iia(i)?i:i===dLp(e.base_,t)?(pLp(e),e.copy_[t]=gLp(i,e)):i},has(e,t){return t in ria(e)},ownKeys(e){return Reflect.ownKeys(ria(e))},set(e,t,r){let i=NgS(ria(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){let n=dLp(ria(e),t),a=n?.[hSe];if(a&&a.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(s95(r,n)&&(r!==void 0||hLp(e.base_,t)))return!0;pLp(e),vLp(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return dLp(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,pLp(e),vLp(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=ria(e),i=Reflect.getOwnPropertyDescriptor(r,t);return i&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:i.enumerable,value:r[t]}},defineProperty(){kOe(11)},getPrototypeOf(e){return Axo(e.base_)},setPrototypeOf(){kOe(12)}},jxo={};Nbc(mLp,(e,t)=>{jxo[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});jxo.deleteProperty=function(e,t){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(t))&&kOe(13),jxo.set.call(this,e,t,void 0)};jxo.set=function(e,t,r){return process.env.NODE_ENV!=="production"&&t!=="length"&&isNaN(parseInt(t))&&kOe(14),mLp.set.call(this,e[0],t,r,e[0])};function dLp(e,t){let r=e[hSe];return(r?ria(r):e)[t]}function h95(e,t,r){let i=NgS(t,r);return i?"value"in i?i.value:i.get?.call(e.draft_):void 0}function NgS(e,t){if(!(t in e))return;let r=Axo(e);for(;r;){let i=Object.getOwnPropertyDescriptor(r,t);if(i)return i;r=Axo(r)}}function vLp(e){e.modified_||(e.modified_=!0,e.parent_&&vLp(e.parent_))}function pLp(e){e.copy_||(e.copy_=_Lp(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var _95=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,r,i)=>{if(typeof t=="function"&&typeof r!="function"){let a=r;r=t;let o=this;return function(d=a,...s){return o.produce(d,u=>r.call(this,u,...s))}}typeof r!="function"&&kOe(6),i!==void 0&&typeof i!="function"&&kOe(7);let n;if(iia(t)){let a=IgS(this),o=gLp(t,void 0),c=!0;try{n=r(o),c=!1}finally{c?yLp(a):bLp(a)}return DgS(a,i),BgS(n,a)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===qgS&&(n=void 0),this.autoFreeze_&&OLp(n,!0),i){let a=[],o=[];nia("Patches").generateReplacementPatches_(t,n,a,o),i(a,o)}return n}else kOe(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(o,...c)=>this.produceWithPatches(o,d=>t(d,...c));let i,n;return[this.produce(t,r,(o,c)=>{i=o,n=c}),i,n]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof e?.useStrictIteration=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){iia(e)||kOe(8),n9a(e)&&(e=y95(e));let t=IgS(this),r=gLp(e,void 0);return r[hSe].isManual_=!0,bLp(t),r}finishDraft(e,t){let r=e&&e[hSe];(!r||!r.isManual_)&&kOe(9);let{scope_:i}=r;return DgS(i,t),BgS(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let n=t[r];if(n.path.length===0&&n.op==="replace"){e=n.value;break}}r>-1&&(t=t.slice(r+1));let i=nia("Patches").applyPatches_;return n9a(e)?i(e,t):this.produce(e,n=>i(n,t))}};function gLp(e,t){let r=wxo(e)?nia("MapSet").proxyMap_(e,t):Lbc(e)?nia("MapSet").proxySet_(e,t):p95(e,t);return(t?t.scope_:zgS()).drafts_.push(r),r}function y95(e){return n9a(e)||kOe(10,e),FgS(e)}function FgS(e){if(!iia(e)||Vbc(e))return e;let t=e[hSe],r,i=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=_Lp(e,t.scope_.immer_.useStrictShallowCopy_),i=t.scope_.immer_.shouldUseStrictIteration()}else r=_Lp(e,!0);return Nbc(r,(n,a)=>{RgS(r,n,FgS(a))},i),t&&(t.finalized_=!1),r}var b95=new _95,Wbc=b95.produce;function v95(e){return e.endsWith(`
|
|
2605
2605
|
`)?e:e+`
|
|
2606
|
-
`}async function UgS({cliContext:e,targetVersion:t}){if(!t)return e.failAndThrow("Please specify a version to downgrade to using --version");let r=await JM();if(r==null)return e.failAndThrow(`Directory "${ME}" not found.`);let i=await e.runTask(a=>aAe({directory:r,context:a})),n=Wbc(i.rawConfig,a=>{a.version=t});await(0,QgS.writeFile)(i._absolutePath,v95(JSON.stringify(n,void 0,2))),e.logger.info(`Updated ${NC} to version ${t}`)}var $bc=require("fs/promises");var aia=ce(hIu(),1),WgS=ce(gO(),1);function LgS(e,t){let r=e.shape,i=e.docs??void 0;return{openApiSchema:Yl._visit(r,{alias:a=>g95({aliasTypeDeclaration:a,docs:i}),enum:a=>O95({enumTypeDeclaration:a,docs:i}),object:a=>{let o=e.userProvidedExamples[0],c=o==null?w95(t,e.name):void 0,d=o==null&&c==null?E95(t,e.name):void 0;return Hbc({properties:a.properties.map(s=>{let u;return o!=null&&o.shape.type==="object"?u=o.shape.properties.find(f=>f.name.wireValue===s.name.wireValue):c!=null?c.type==="reference"&&c.shape.type==="named"&&c.shape.shape.type==="object"&&(u=c.shape.shape.properties.find(f=>f.name.wireValue===s.name.wireValue)):d!=null&&d.type==="body"&&d.value?.shape.type==="named"&&d.value.shape.shape.type==="object"&&(u=d.value.shape.shape.properties.find(f=>f.name.wireValue===s.name.wireValue)),{docs:s.docs??void 0,name:s.name,valueType:s.valueType,example:u}}),extensions:a.extends,docs:i})},union:a=>m95({unionTypeDeclaration:a,docs:i}),undiscriminatedUnion:a=>A95({undiscriminatedUnionDeclaration:a,docs:i}),_other:()=>{throw new Error("Encountered unknown type: "+r.type)}}),schemaName:VgS(e.name)}}function g95({aliasTypeDeclaration:e,docs:t}){return{...QT(e.aliasOf),description:t}}function O95({enumTypeDeclaration:e,docs:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue),description:t}}function m95({unionTypeDeclaration:e,docs:t}){let i={oneOf:e.types.map(n=>{let a={[e.discriminant.wireValue]:{type:"string",enum:[n.discriminantValue.wireValue]}};return cU._visit(n.shape,{noProperties:()=>({type:"object",properties:a,required:[e.discriminant.wireValue]}),singleProperty:o=>({type:"object",properties:{...a,[o.name.wireValue]:QT(o.type)},required:[e.discriminant.wireValue]}),samePropertiesAsObject:o=>({type:"object",allOf:[{type:"object",properties:a},{$ref:xbc(o)}],required:[e.discriminant.wireValue]}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+n.shape.propertiesType)}})}),description:t};return e.baseProperties.length>0&&(i.properties=e.baseProperties.reduce((n,a)=>(n[a.name.wireValue]={description:a.docs??void 0,...QT(a.valueType)},a.valueType.type==="container"&&a.valueType.container.type==="optional"||(i.required=[...i.required??[],a.name.wireValue]),n),{})),i}function A95({undiscriminatedUnionDeclaration:e,docs:t}){return{oneOf:e.members.map(r=>({description:r.docs??void 0,...QT(r.type)})),description:t}}function QT(e){return hi._visit(e,{container:t=>j95(t),named:t=>({$ref:xbc(t)}),primitive:t=>P95(t),unknown:()=>({}),_other:()=>{throw new Error("Encountered unknown typeReference: "+e.type)}})}function P95(e){return e.v2==null?Ps._visit(e.v1,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:()=>({type:"string"}),uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),_other:()=>{throw new Error("Encountered unknown primitiveType: "+e.v1)}})??{}:Cn._visit(e.v2,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:t=>{let r={type:"string"};return t.validation?.format!=null&&(r.format=t.validation.format),t.validation?.pattern!=null&&(r.pattern=t.validation.pattern),r},uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),_other:()=>{throw new Error("Encountered unknown primitiveType: "+e.v2)}})}function j95(e){return Js._visit(e,{list:t=>({type:"array",items:QT(t)}),set:t=>({type:"array",items:QT(t)}),map:t=>t.keyType.type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType.type==="unknown"?{type:"object",additionalProperties:!0}:{type:"object",additionalProperties:QT(t.valueType)},optional:t=>({...QT(t),nullable:!0}),nullable:t=>({...QT(t),nullable:!0}),literal:t=>t._visit({boolean:r=>({type:"boolean",const:r}),string:r=>({type:"string",const:r}),_other:()=>({})}),_other:()=>{throw new Error("Encountered unknown containerType: "+e.type)}})}function xbc(e){return`#/components/schemas/${VgS(e)}`}function VgS(e){return[...e.fernFilepath.packagePath.map(t=>t.originalName),e.name.originalName].join("")}function w95(e,t){for(let r of Object.values(e.services))for(let i of r.endpoints)if(!(i.userSpecifiedExamples.length<=0)&&i.requestBody?.type==="reference"&&i.requestBody.requestBodyType.type==="named"&&S95(i.requestBody.requestBodyType,t))return i.userSpecifiedExamples[0]?.example?.request??void 0}function E95(e,t){for(let r of Object.values(e.services))for(let i of r.endpoints)if(!(i.userSpecifiedExamples.length<=0||i.response?.body?.type!=="json")&&i.response.body.value.responseBodyType.type==="named"&&i.response.body.value.responseBodyType.typeId===t.typeId){let n=i.userSpecifiedExamples.find(a=>a.example?.response.type==="ok");if(n!=null&&n.example?.response.type==="ok")return n.example.response.value}}function S95(e,t){return EC(e.fernFilepath,t.fernFilepath)&&EC(e.name,t.name)}function Hbc({docs:e,properties:t,extensions:r}){let i={},n=[];t.forEach(o=>{let c=QT(o.valueType),d;(o.example!=null&&o.valueType.type==="primitive"||o.example!=null&&o.valueType.type==="container"&&o.valueType.container.type==="list"&&o.valueType.container.list.type==="primitive")&&(d=o.example.value.jsonExample),i[o.name.wireValue]={...c,description:o.docs??void 0,example:d},o.valueType.type==="container"&&o.valueType.container.type==="optional"||n.push(o.name.wireValue)});let a={type:"object",description:e,properties:i};return n.length>0&&(a.required=n),r.length>0&&(a.allOf=r.map(o=>({$ref:xbc(o)}))),a}function xgS({ir:e,httpServices:t,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c}){let d={};return t.forEach(s=>{s.endpoints.forEach(u=>{let{fullPath:f,convertedHttpMethod:p,operationObject:h}=M95({ir:e,httpEndpoint:u,httpService:s,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c}),_=d[f]??={};if(_[p]!=null)throw new Error(`Duplicate ${p} endpoint at ${f}`);_[p]=h})}),d}function M95({httpEndpoint:e,httpService:t,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c,ir:d}){let s=(0,WgS.default)(d.basePath!=null?PLp(d.basePath):"",PLp(t.basePath),PLp(e.path));s=s.startsWith("/")?s:`/${s}`;let u=D95(e.method),f=d.pathParameters.map(m=>ALp({pathParameter:m,examples:e.userSpecifiedExamples.map(g=>g.example).filter($s)??[]})),p=t.pathParameters.map(m=>ALp({pathParameter:m,examples:e.userSpecifiedExamples.map(g=>g.example).filter($s)??[]})),h=e.pathParameters.map(m=>ALp({pathParameter:m,examples:e.userSpecifiedExamples.map(g=>g.example).filter($s)??[]})),_=e.queryParameters.map(m=>T95({queryParameter:m,typesByName:r,examples:e.userSpecifiedExamples.map(g=>g.example).filter($s)??[]})),y=e.headers.map(m=>R95({httpHeader:m,typesByName:r,examples:e.userSpecifiedExamples.map(g=>g.example).filter($s)??[]})),b=[...f,...p,...h,..._,...y],v=c==="stoplight"?t.displayName??t.name.fernFilepath.allParts.map(m=>m.originalName).join(" "):t.name.fernFilepath.allParts.map(m=>m.pascalCase.unsafeName).join(""),O={description:e.docs??void 0,operationId:[...t.name.fernFilepath.allParts.map(m=>m.camelCase.unsafeName),e.name.originalName].join("_"),tags:[v],parameters:b,responses:B95({httpResponse:e.response,responseErrors:e.errors,errorsByName:i,errorDiscriminationStrategy:n,examples:e.userSpecifiedExamples.map(m=>m.example).filter($s)??[]}),summary:e.displayName??void 0};if(e.baseUrl!=null){let m=e.baseUrl;if(o?.environments.type!=="multipleBaseUrls")throw new Error("baseUrl is defined environments are not multipleBaseUrls");O.servers=o.environments.environments.map(g=>{let A=g.urls[m];if(A==null)throw new Error("No URL defined for "+m);let j={url:A};return g.docs!=null&&(j.description=g.docs),j})}return e.auth&&(O.security=a),e.requestBody!=null&&(O.requestBody=I95({httpRequest:e.requestBody,typesByName:r,examples:e.userSpecifiedExamples.map(m=>m.example).filter($s)??[]})),{fullPath:s,convertedHttpMethod:u,operationObject:O}}function D95(e){return EE._visit(e,{get:()=>aia.OpenAPIV3.HttpMethods.GET,post:()=>aia.OpenAPIV3.HttpMethods.POST,put:()=>aia.OpenAPIV3.HttpMethods.PUT,patch:()=>aia.OpenAPIV3.HttpMethods.PATCH,delete:()=>aia.OpenAPIV3.HttpMethods.DELETE,head:()=>aia.OpenAPIV3.HttpMethods.HEAD,_other:()=>{throw new Error("Encountered unknown http method: "+e)}})}function I95({httpRequest:e,typesByName:t,examples:r}){let i={};for(let n of r)n.request!=null&&(n.name&&n.name.originalName!==""?i[n.name.originalName]={value:n.request.jsonExample}:i[`Example${tj(i)+1}`]={value:n.request.jsonExample});return FA._visit(e,{inlinedRequestBody:n=>{let a={schema:Hbc({docs:void 0,properties:n.properties.map(o=>{let c;return r.length>0&&r[0]?.request?.type==="inlinedRequestBody"&&(c=r[0]?.request.properties.find(d=>d.name.wireValue===o.name.wireValue)),{docs:o.docs??void 0,name:o.name,valueType:o.valueType,example:c}}),extensions:n.extends})};return tj(i)>0&&(a.examples=i),{required:!0,content:{"application/json":a}}},reference:n=>{let a={schema:QT(n.requestBodyType)};return tj(i)>0&&(a.examples=i),{description:n.docs??void 0,required:Gbc({typeReference:n.requestBodyType,typesByName:t}),content:{"application/json":a}}},fileUpload:n=>({required:!0,content:{"multipart/form-data":{schema:{type:"object",properties:n.properties.reduce((a,o)=>(dR._visit(o,{file:c=>{a[c.key.wireValue]={type:"string",format:"binary"}},bodyProperty:c=>{a[c.name.wireValue]={description:c.docs??void 0,...QT(c.valueType)}},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}}),{...a}),{})}}}}),bytes:()=>{throw new Error("bytes is not supported")},_other:()=>{throw new Error("Unknown HttpRequestBody type: "+e.type)}})}function B95({httpResponse:e,responseErrors:t,errorsByName:r,errorDiscriminationStrategy:i,examples:n}){let a={};if(e?.body?.type==="json"){let o={schema:QT(e.body.value.responseBodyType)},c={};for(let d of n)d.response.type==="ok"&&d.response.value.type==="body"&&d.response.value.value!=null&&(d.name&&d.name.originalName!==""?c[d.name.originalName]={value:d.response.value.value.jsonExample}:c[`Example${tj(c)+1}`]={value:d.response.value.value.jsonExample});tj(c)>0&&(o.examples=c),a[String(e.statusCode??200)]={description:e.body.value.docs??"",content:{"application/json":o}}}else a[204]={description:""};return Kme._visit(i,{statusCode:()=>{for(let o of t){let c=r[Kbc(o.error)];if(c==null)throw new Error("Encountered undefined error declaration: "+o.error.name.originalName);let d={description:o.docs??""};if(c.type!=null){let s={schema:QT(c.type)},u={};for(let f of n)f.response.type==="error"&&f.response.body!=null&&EC(o.error,f.response.error)&&(f.name&&f.name.originalName!==""?u[f.name.originalName]={value:f.response.body.jsonExample}:u[`Example${tj(u)+1}`]={value:f.response.body.jsonExample});tj(u)>0&&(s.examples=u),d.content={"application/json":s}}a[c.statusCode]=d}},property:o=>{let c=q95({responseErrors:t,errorsByName:r});for(let d of Object.keys(c)){let s=c[d];if(s==null||s.length===0)continue;let u={schema:{oneOf:s.map(p=>C95({errorInfo:p,property:o}))}},f={};for(let p of n)if(p.response.type==="error"&&p.response.body!=null){let h=p.response.error;s.some(_=>EC(_.errorDeclaration.name,h))&&(p.name&&p.name.originalName!==""?f[p.name.originalName]={value:p.response.body.jsonExample}:f[`Example${tj(f)+1}`]={value:p.response.body.jsonExample})}tj(f)>0&&(u.examples=f),a[d]={description:"",content:{"application/json":u}}}},_other:()=>{throw new Error("Unknown error discrimination strategy: "+i.type)}}),a}function C95({errorInfo:e,property:t}){let r=e.errorDeclaration.discriminantValue.wireValue,i=e.responseError.docs??void 0,n={[t.discriminant.wireValue]:{type:"string",enum:[r]}};return e.errorDeclaration.type!=null&&(n[t.contentProperty.wireValue]=QT(e.errorDeclaration.type)),{type:"object",description:i,properties:n}}function q95({responseErrors:e,errorsByName:t}){let r={};for(let i of e){let n=t[Kbc(i.error)];if(n==null)throw new Error("Encountered undefined error declaration: "+i.error.name.originalName);let a=n.statusCode,o=r[a];o==null?r[a]=[{responseError:i,errorDeclaration:n}]:o.push({responseError:i,errorDeclaration:n})}return r}function ALp({pathParameter:e,examples:t}){let r={name:e.name.originalName,in:"path",description:e.docs??void 0,required:!0,schema:QT(e.valueType)},i={};for(let n of t){let a=[...n.rootPathParameters,...n.servicePathParameters,...n.endpointPathParameters].find(o=>o.name.originalName===e.name.originalName);a!=null&&(n.name&&n.name.originalName!==""?i[n.name.originalName]={value:a.value.jsonExample}:i[`Example${tj(i)+1}`]={value:a.value.jsonExample},r.example==null&&(r.example=a.value.jsonExample))}return tj(i)>0&&(r.examples=i),r}function T95({queryParameter:e,typesByName:t,examples:r}){let i={name:e.name.wireValue,in:"query",description:e.docs??void 0,required:Gbc({typeReference:e.valueType,typesByName:t}),schema:e.allowMultiple?QT(hi.container(Js.list(e.valueType))):QT(e.valueType)},n={};for(let a of r){let o=a.queryParameters.find(c=>c.name.wireValue===e.name.wireValue);o!=null&&(a.name&&a.name.originalName!==""?n[a.name.originalName]={value:o.value.jsonExample}:n[`Example${tj(n)+1}`]={value:o.value.jsonExample},i.example==null&&(i.example=o.value.jsonExample))}return tj(n)>0&&(i.examples=n),i}function R95({httpHeader:e,typesByName:t,examples:r}){let i={name:e.name.wireValue,in:"header",description:e.docs??void 0,required:Gbc({typeReference:e.valueType,typesByName:t}),schema:QT(e.valueType)},n={};for(let a of r){let o=[...a.serviceHeaders,...a.endpointHeaders].find(c=>c.name.wireValue===e.name.wireValue);o!=null&&(a.name&&a.name.originalName!==""?n[a.name.originalName]={value:o.value.jsonExample}:n[`Example${tj(n)+1}`]={value:o.value.jsonExample},i.example==null&&(i.example=o.value.jsonExample))}return tj(n)>0&&(i.examples=n),i}function PLp(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return t}function Gbc({typeReference:e,typesByName:t}){if(e.type==="container"&&e.container.type==="optional")return!1;if(e.type==="named"){let r=jLp(e),i=t[r];if(i==null)throw new Error("Encountered non-existent type: "+e.name.originalName);if(i.shape.type==="alias")return Gbc({typeReference:i.shape.aliasOf,typesByName:t})}return!0}function HgS(e){return EN._visit(e.requirement,{all:()=>[e.schemes.reduce((t,r)=>({...t,[wLp(r)]:[]}),{})],any:()=>e.schemes.map(t=>({[wLp(t)]:[]})),endpointSecurity:()=>[],_other:()=>{throw new Error("Unknown auth scheme requirement: "+e.requirement)}})}function GgS(e){let t={};for(let r of e.schemes){let i=AP._visit(r,{bearer:()=>({type:"http",scheme:"bearer"}),basic:()=>({type:"http",scheme:"basic"}),header:n=>({type:"apiKey",in:"header",name:n.name.wireValue}),oauth:()=>({type:"http",scheme:"bearer"}),inferred:()=>{},_other:()=>{throw new Error("Unknown auth scheme: "+r.type)}});i&&(t[wLp(r)]=i)}return t}function wLp(e){return AP._visit(e,{bearer:()=>"BearerAuth",inferred:()=>"InferredAuth",basic:()=>"BasicAuth",oauth:()=>"BearerAuth",header:t=>`${t.name.name.pascalCase.unsafeName}Auth`,_other:()=>{throw new Error("Unknown auth scheme: "+e.type)}})}function KgS({apiName:e,ir:t,mode:r}){let i={},n={};Object.values(t.types).forEach(u=>{let f=LgS(u,t);i[f.schemaName]={title:f.schemaName,...f.openApiSchema},n[jLp(u.name)]=u});let a={};Object.values(t.errors).forEach(u=>{a[Kbc(u.name)]=u});let o=HgS(t.auth),c=xgS({ir:t,httpServices:Object.values(t.services),typesByName:n,errorsByName:a,errorDiscriminationStrategy:t.errorDiscriminationStrategy,security:o,environments:t.environments??void 0,mode:r}),d={title:t.apiDisplayName??e,version:""};t.apiDocs!=null&&(d.description=t.apiDocs);let s={openapi:"3.0.1",info:d,paths:c,components:{schemas:i,securitySchemes:GgS(t.auth)}};return t.environments!=null&&t.environments.environments.type==="singleBaseUrl"&&(s.servers=t.environments.environments.environments.map(u=>({url:u.url,description:u.docs!=null?`${u.name.originalName} (${u.docs})`:u.name.originalName}))),s}function jLp(e){return[...e.fernFilepath.allParts.map(t=>t.originalName),e.name.originalName].join("-")}function Kbc(e){return[...e.fernFilepath.allParts.map(t=>t.originalName),e.name.originalName].join("-")}async function $gS({project:e,cliContext:t,outputPath:r,indent:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await t.runTaskForWorkspace(n,async a=>{let o=await n.toFernWorkspace({context:a}),c=BE({workspace:o,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!0},readme:void 0,version:void 0,packageName:void 0,context:a,sourceResolver:new TE(a,o)}),d=KgS({apiName:n.workspaceName??"api",ir:c,mode:"openapi"});await(0,$bc.mkdir)(rn(r),{recursive:!0}),await(0,$bc.writeFile)(r,r.endsWith(".json")?JSON.stringify(d,void 0,i):Mi.dump(d,{indent:i}))})}))}async function JgS({project:e,cliContext:t,shouldFix:r}){await Promise.all(e.apiWorkspaces.map(async i=>{i instanceof CP||await t.runTaskForWorkspace(i,async n=>{await WSp({workspace:await i.toFernWorkspace({context:n}),context:n,shouldFix:r})})}))}var YgS="group";var XgS=".preview",ZgS="approved-output-directories",kgS=".fern";var aOS=require("fs/promises");var tOS=require("fs/promises");var eOS=require("os");function Exo(){return ut(vr.of((0,eOS.homedir)()),me.of(kgS),me.of(ZgS))}async function rOS(){let e=Exo();if(!await ii(e))return[];let r=await(0,tOS.readFile)(e,{encoding:"utf-8"});return JSON.parse(r)}var Jbc=require("fs/promises"),iOS=ce(require("path"),1);async function nOS(e){await(0,Jbc.mkdir)(iOS.default.dirname(Exo()),{recursive:!0}),await(0,Jbc.writeFile)(Exo(),JSON.stringify(e,null,2))}async function oOS(e,t,r){if(!e||tRc()||r)return{shouldProceed:!0};let i=await rOS();return i?.includes(e)?{shouldProceed:!0}:await ii(e)?(await(0,aOS.readdir)(e)).length===0?{shouldProceed:!0}:await t.confirmPrompt(`Directory ${e} contains existing files that may be overwritten. Continue?`,!1)?(await nOS([...i??[],e]),{shouldProceed:!0}):{shouldProceed:!1}:{shouldProceed:!0}}var hOS=ce(w3i(),1);async function uOS({groups:e,visitor:t,nodePath:r,cliVersion:i}){if(e!=null)for(let[n,a]of Object.entries(e))await z95({group:a,visitor:t,nodePath:[...r,n],cliVersion:i})}async function z95({group:e,visitor:t,nodePath:r,cliVersion:i}){await Promise.all(e.generators.map(async(n,a)=>await t.generatorInvocation?.({invocation:n,cliVersion:i},[...r,"generators",a.toString(),n.name])))}async function sOS(e,t,r){await r.file?.(e,[]),await a5t(e,{"auth-schemes":mt,api:mt,whitelabel:mt,metadata:mt,readme:mt,"default-group":mt,aliases:mt,reviewers:mt,openapi:mt,"openapi-overrides":mt,"spec-origin":mt,"async-api":mt,"api-settings":mt,ai:mt,autorelease:mt,groups:async i=>{await uOS({groups:i,visitor:r,nodePath:["groups"],cliVersion:t})}})}function cOS({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let o=async(c,d)=>{for(let s of r){let u=s.generatorsYml?.[a];if(u!=null){let f=await u(c,{relativeFilepath:e,contents:t});i(f.map(p=>({severity:p.severity,relativeFilepath:e,nodePath:d,message:p.message})))}}};return{[a]:o}}return{...n("file"),...n("generatorInvocation")}}function N95(e,t,r){if(!p2(r,t))return[{severity:"fatal",message:`The generator ${e} requires CLI version ${t} or later (current version: ${r}). Please run \`fern upgrade\` to upgrade your CLI version and use this generator.`}]}function F95(e){return Number(e.replace("v",""))}var ELp={name:"compatible-ir-version",create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e,cliVersion:t})=>{let r=rJo({token:void 0});if(t==null)return[];let i=await r.generators.cli.getCliRelease(t);if(!i.ok)return[];let n=i.body.irVersion,a;if(e["ir-version"]!=null)a=F95(e["ir-version"]);else{let c={...e,name:DU(e.name)},d=await WOn(c);if(d==null)return[];a=d}if(a<=n)return[];let o=await r.generators.cli.getMinCliForIr(a);return o.ok?N95(e.name,o.body.version,t)??[]:[]}}})};var SLp={name:"valid-alias-group-references",create:async()=>({generatorsYml:{file:async e=>{let t=[],r=e.aliases,i=e.groups??{};if(r==null)return t;let n=new Set(Object.keys(i));for(let[a,o]of Object.entries(r))if(Array.isArray(o))for(let c of o)n.has(c)||t.push({severity:"error",message:`Alias "${a}" references unknown group "${c}". Available groups: ${[...n].join(", ")||"none"}`});return t}}})};function lOS(){return[ELp,SLp]}async function Ybc(e,t){return Q95({workspace:e,rules:lOS(),logger:t})}async function Q95({workspace:e,rules:t,logger:r}){let i=[],n=await Promise.all(t.map(a=>a.create({workspace:e,logger:r})));if(e.generatorsConfiguration?.rawConfiguration){let a=await U95({contents:e.generatorsConfiguration.rawConfiguration,allRuleVisitors:n,cliVersion:e.cliVersion});i.push(...a)}return i}async function U95({contents:e,allRuleVisitors:t,cliVersion:r}){let i=[],n=cOS({relativeFilepath:me.of(GM),contents:e,allRuleVisitors:t,addViolations:a=>{i.push(...a)}});return await sOS(e,r,n),i}var MLp=ce(dOS(),1);async function pOS({workspace:e,context:t,ossWorkspace:r}){(0,MLp.default)(e.definition.rootApiFile.contents.name).validForNewPackages||t.failAndThrow("API name is not valid.");let i=performance.now(),n=nwn(e,t.logger),a=await Ybc(e,t.logger),o=[...n,...a];r&&o.push(...await _ba(r,t));let c=performance.now()-i,d=o.some(s=>s.severity==="fatal"||s.severity==="error");return{apiName:e.definition.rootApiFile.contents.name,violations:o,elapsedMillis:c,hasErrors:d}}async function H95({workspace:e,context:t,logWarnings:r,logSummary:i=!0,ossWorkspace:n}){let a=performance.now(),o=nwn(e,t.logger),c=await Ybc(e,t.logger),d=[...o,...c];n&&d.push(...await _ba(n,t));let s=performance.now()-a,{hasErrors:u}=kGa({violations:d,context:t,logWarnings:r,logSummary:i,elapsedMillis:s});return{hasErrors:u}}async function fvn({workspace:e,context:t,logWarnings:r,ossWorkspace:i}){(0,MLp.default)(e.definition.rootApiFile.contents.name).validForNewPackages||t.failAndThrow("API name is not valid.");let{hasErrors:n}=await H95({workspace:e,context:t,logWarnings:r,ossWorkspace:i});n&&t.failAndThrow()}async function _OS({organization:e,workspace:t,projectConfig:r,context:i,groupName:n,version:a,shouldLogS3Url:o,token:c,useLocalDocker:d,keepDocker:s,absolutePathToPreview:u,mode:f,runner:p,inspect:h,lfsOverride:_,fernignorePath:y,dynamicIrOnly:b}){if(t.generatorsConfiguration==null){i.logger.warn("This workspaces has no generators.yml");return}if(t.generatorsConfiguration.groups.length===0){i.logger.warn(`This workspace has no groups specified in ${GM}`);return}let v=n??t.generatorsConfiguration.defaultGroup;if(v==null)return i.failAndThrow(`No group specified. Use the --${YgS} option, or set "${epa}" in ${GM}`);let O=G95(v,t.generatorsConfiguration.groupAliases,t.generatorsConfiguration.groups.map(g=>g.groupName),i),{ai:m}=t.generatorsConfiguration;if(!d&&!c)return i.failAndThrow("Please run fern login");await fvn({workspace:await t.toFernWorkspace({context:i}),context:i,logWarnings:!1}),await Promise.all(O.map(async g=>{let A=t.generatorsConfiguration?.groups.find(j=>j.groupName===g);if(A==null)return i.failAndThrow(`Group '${g}' does not exist.`);_!=null&&(A=K95(A,_,i)),O.length>1&&i.logger.info(`Running generation for group '${g}'...`),d?await eHE({token:c,projectConfig:r,workspace:t,generatorGroup:A,version:a,keepDocker:s,context:i,runner:p,absolutePathToPreview:u,inspect:h,ai:m}):c!=null&&await C4o({projectConfig:r,organization:e,workspace:t,context:i,generatorGroup:A,version:a,shouldLogS3Url:o,token:c,whitelabel:t.generatorsConfiguration?.whitelabel,absolutePathToPreview:u,mode:f,fernignorePath:y,dynamicIrOnly:b})}))}function G95(e,t,r,i){let n=t[e];if(n!=null){for(let c of n)r.includes(c)||i.failAndThrow(`Group alias '${e}' references non-existent group '${c}'. Available groups: ${r.join(", ")}`);return n}if(r.includes(e))return[e];let a=Object.keys(t),o=[...r,...a];return i.failAndThrow(`'${e}' is not a valid group or alias. Available groups: ${r.join(", ")}`+(a.length>0?`. Available aliases: ${a.join(", ")}`:"")),[]}function K95(e,t,r){let i=vr.of(xo(AO(),t)),n={},a=[];for(let o of e.generators){let c=o.language??$95(o.name),d;if(e.generators.length===1)d=i;else{let u=c||"unknown";n[u]==null&&(n[u]=0),n[u]++;let f=n[u]===1?u:`${u}-${n[u]}`;d=ut(i,me.of(f))}let s={...o,outputMode:hOS.FernFiddle.remoteGen.OutputMode.downloadFiles({}),absolutePathToLocalOutput:d};a.push(s),r.logger.info(`Overriding output for generator '${o.name}' to local-file-system at: ${d}`)}return{...e,generators:a}}function $95(e){return e.includes("typescript")||e.includes("ts")?"typescript":e.includes("python")||e.includes("py")?"python":e.includes("java")?"java":e.includes("go")?"go":e.includes("ruby")?"ruby":e.includes("csharp")||e.includes("c#")?"csharp":e.includes("swift")?"swift":e.includes("php")?"php":e.includes("rust")?"rust":e.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}var bOS={PullRequest:"pull-request"};async function DLp({project:e,cliContext:t,version:r,groupName:i,shouldLogS3Url:n,keepDocker:a,useLocalDocker:o,preview:c,mode:d,force:s,runner:u,inspect:f,lfsOverride:p,fernignorePath:h,dynamicIrOnly:_,outputDir:y}){let b;if(!o){let v=await t.runTask(async O=>tU(O));v.type==="user"&&await t.runTask(async O=>{await Sme({organization:e.config.organization,token:v,context:O})}),b=v}for(let v of e.apiWorkspaces){let O=yOS(i,v.generatorsConfiguration);for(let m of v.generatorsConfiguration?.groups.filter(g=>O==null||O.includes(g.groupName)).flatMap(g=>g.generators)??[]){let{shouldProceed:g}=await oOS(m.absolutePathToLocalOutput,t,s);g||t.failAndThrow("Generation cancelled")}}await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate",properties:{workspaces:e.apiWorkspaces.map(v=>{let O=yOS(i,v.generatorsConfiguration);return{name:v.workspaceName,group:i,generators:v.generatorsConfiguration?.groups.filter(m=>O==null||O.includes(m.groupName)).map(m=>m.generators.map(g=>({name:g.name,version:g.version,outputMode:g.outputMode.type,config:g.config})))}})}}),await Promise.all(e.apiWorkspaces.map(async v=>{await t.runTaskForWorkspace(v,async O=>{let m=c?y!=null?vr.of(xo(AO(),y)):ut(v.absoluteFilePath,me.of(XgS)):void 0;m!=null&&O.logger.info(`Writing preview to ${m}`),await _OS({organization:e.config.organization,workspace:v,projectConfig:e.config,context:O,version:r,groupName:i,shouldLogS3Url:n,token:b,useLocalDocker:o,keepDocker:a,absolutePathToPreview:m,mode:d,runner:u,inspect:f,lfsOverride:p,fernignorePath:h,dynamicIrOnly:_})})}))}function yOS(e,t){if(e==null)return null;if(t==null)return[e];let r=t.groupAliases[e];return r??[e]}function vOS(){return!!(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.CIRCLECI||process.env.TRAVIS||process.env.JENKINS_URL||process.env.JENKINS_HOME||process.env.TF_BUILD||process.env.BUILDKITE||process.env.CODEBUILD_BUILD_ID||process.env.TEAMCITY_VERSION||process.env.BITBUCKET_BUILD_NUMBER||process.env.DRONE||process.env.SEMAPHORE||process.env.APPVEYOR||process.env.BUDDY_WORKSPACE_ID||process.env.WERCKER_RUN_ID)}async function gOS({project:e,cliContext:t,instance:r,preview:i,brokenLinks:n,strictBrokenLinks:a,disableTemplates:o,noPrompt:c,skipUpload:d}){let s=e.docsWorkspaces;if(s==null){t.failAndThrow("No docs.yml file found. Please make sure your project has one.");return}let u=process.env.FERN_SELF_HOSTED==="true";if(!i&&!vOS()&&!c){let p=r??s.config.instances[0]?.url,h=p?` (${Ke.cyan(`https://${p}`)})`:"";if(!await t.confirmPrompt(`This will affect a production site${h}. Run with --preview to generate docs for a preview instance.
|
|
2606
|
+
`}async function UgS({cliContext:e,targetVersion:t}){if(!t)return e.failAndThrow("Please specify a version to downgrade to using --version");let r=await JM();if(r==null)return e.failAndThrow(`Directory "${ME}" not found.`);let i=await e.runTask(a=>aAe({directory:r,context:a})),n=Wbc(i.rawConfig,a=>{a.version=t});await(0,QgS.writeFile)(i._absolutePath,v95(JSON.stringify(n,void 0,2))),e.logger.info(`Updated ${NC} to version ${t}`)}var $bc=require("fs/promises");var aia=ce(hIu(),1),WgS=ce(gO(),1);function LgS(e,t){let r=e.shape,i=e.docs??void 0;return{openApiSchema:Yl._visit(r,{alias:a=>g95({aliasTypeDeclaration:a,docs:i}),enum:a=>O95({enumTypeDeclaration:a,docs:i}),object:a=>{let o=e.userProvidedExamples[0],c=o==null?w95(t,e.name):void 0,d=o==null&&c==null?E95(t,e.name):void 0;return Hbc({properties:a.properties.map(s=>{let u;return o!=null&&o.shape.type==="object"?u=o.shape.properties.find(f=>f.name.wireValue===s.name.wireValue):c!=null?c.type==="reference"&&c.shape.type==="named"&&c.shape.shape.type==="object"&&(u=c.shape.shape.properties.find(f=>f.name.wireValue===s.name.wireValue)):d!=null&&d.type==="body"&&d.value?.shape.type==="named"&&d.value.shape.shape.type==="object"&&(u=d.value.shape.shape.properties.find(f=>f.name.wireValue===s.name.wireValue)),{docs:s.docs??void 0,name:s.name,valueType:s.valueType,example:u}}),extensions:a.extends,docs:i})},union:a=>m95({unionTypeDeclaration:a,docs:i}),undiscriminatedUnion:a=>A95({undiscriminatedUnionDeclaration:a,docs:i}),_other:()=>{throw new Error("Encountered unknown type: "+r.type)}}),schemaName:VgS(e.name)}}function g95({aliasTypeDeclaration:e,docs:t}){return{...QT(e.aliasOf),description:t}}function O95({enumTypeDeclaration:e,docs:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue),description:t}}function m95({unionTypeDeclaration:e,docs:t}){let i={oneOf:e.types.map(n=>{let a={[e.discriminant.wireValue]:{type:"string",enum:[n.discriminantValue.wireValue]}};return cU._visit(n.shape,{noProperties:()=>({type:"object",properties:a,required:[e.discriminant.wireValue]}),singleProperty:o=>({type:"object",properties:{...a,[o.name.wireValue]:QT(o.type)},required:[e.discriminant.wireValue]}),samePropertiesAsObject:o=>({type:"object",allOf:[{type:"object",properties:a},{$ref:xbc(o)}],required:[e.discriminant.wireValue]}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+n.shape.propertiesType)}})}),description:t};return e.baseProperties.length>0&&(i.properties=e.baseProperties.reduce((n,a)=>(n[a.name.wireValue]={description:a.docs??void 0,...QT(a.valueType)},a.valueType.type==="container"&&a.valueType.container.type==="optional"||(i.required=[...i.required??[],a.name.wireValue]),n),{})),i}function A95({undiscriminatedUnionDeclaration:e,docs:t}){return{oneOf:e.members.map(r=>({description:r.docs??void 0,...QT(r.type)})),description:t}}function QT(e){return hi._visit(e,{container:t=>j95(t),named:t=>({$ref:xbc(t)}),primitive:t=>P95(t),unknown:()=>({}),_other:()=>{throw new Error("Encountered unknown typeReference: "+e.type)}})}function P95(e){return e.v2==null?Ps._visit(e.v1,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:()=>({type:"string"}),uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),_other:()=>{throw new Error("Encountered unknown primitiveType: "+e.v1)}})??{}:Cn._visit(e.v2,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:t=>{let r={type:"string"};return t.validation?.format!=null&&(r.format=t.validation.format),t.validation?.pattern!=null&&(r.pattern=t.validation.pattern),r},uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),_other:()=>{throw new Error("Encountered unknown primitiveType: "+e.v2)}})}function j95(e){return Js._visit(e,{list:t=>({type:"array",items:QT(t)}),set:t=>({type:"array",items:QT(t)}),map:t=>t.keyType.type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType.type==="unknown"?{type:"object",additionalProperties:!0}:{type:"object",additionalProperties:QT(t.valueType)},optional:t=>({...QT(t),nullable:!0}),nullable:t=>({...QT(t),nullable:!0}),literal:t=>t._visit({boolean:r=>({type:"boolean",const:r}),string:r=>({type:"string",const:r}),_other:()=>({})}),_other:()=>{throw new Error("Encountered unknown containerType: "+e.type)}})}function xbc(e){return`#/components/schemas/${VgS(e)}`}function VgS(e){return[...e.fernFilepath.packagePath.map(t=>t.originalName),e.name.originalName].join("")}function w95(e,t){for(let r of Object.values(e.services))for(let i of r.endpoints)if(!(i.userSpecifiedExamples.length<=0)&&i.requestBody?.type==="reference"&&i.requestBody.requestBodyType.type==="named"&&S95(i.requestBody.requestBodyType,t))return i.userSpecifiedExamples[0]?.example?.request??void 0}function E95(e,t){for(let r of Object.values(e.services))for(let i of r.endpoints)if(!(i.userSpecifiedExamples.length<=0||i.response?.body?.type!=="json")&&i.response.body.value.responseBodyType.type==="named"&&i.response.body.value.responseBodyType.typeId===t.typeId){let n=i.userSpecifiedExamples.find(a=>a.example?.response.type==="ok");if(n!=null&&n.example?.response.type==="ok")return n.example.response.value}}function S95(e,t){return EC(e.fernFilepath,t.fernFilepath)&&EC(e.name,t.name)}function Hbc({docs:e,properties:t,extensions:r}){let i={},n=[];t.forEach(o=>{let c=QT(o.valueType),d;(o.example!=null&&o.valueType.type==="primitive"||o.example!=null&&o.valueType.type==="container"&&o.valueType.container.type==="list"&&o.valueType.container.list.type==="primitive")&&(d=o.example.value.jsonExample),i[o.name.wireValue]={...c,description:o.docs??void 0,example:d},o.valueType.type==="container"&&o.valueType.container.type==="optional"||n.push(o.name.wireValue)});let a={type:"object",description:e,properties:i};return n.length>0&&(a.required=n),r.length>0&&(a.allOf=r.map(o=>({$ref:xbc(o)}))),a}function xgS({ir:e,httpServices:t,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c}){let d={};return t.forEach(s=>{s.endpoints.forEach(u=>{let{fullPath:f,convertedHttpMethod:p,operationObject:h}=M95({ir:e,httpEndpoint:u,httpService:s,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c}),_=d[f]??={};if(_[p]!=null)throw new Error(`Duplicate ${p} endpoint at ${f}`);_[p]=h})}),d}function M95({httpEndpoint:e,httpService:t,typesByName:r,errorsByName:i,errorDiscriminationStrategy:n,security:a,environments:o,mode:c,ir:d}){let s=(0,WgS.default)(d.basePath!=null?PLp(d.basePath):"",PLp(t.basePath),PLp(e.path));s=s.startsWith("/")?s:`/${s}`;let u=D95(e.method),f=d.pathParameters.map(m=>ALp({pathParameter:m,examples:e.userSpecifiedExamples.map(g=>g.example).filter($s)??[]})),p=t.pathParameters.map(m=>ALp({pathParameter:m,examples:e.userSpecifiedExamples.map(g=>g.example).filter($s)??[]})),h=e.pathParameters.map(m=>ALp({pathParameter:m,examples:e.userSpecifiedExamples.map(g=>g.example).filter($s)??[]})),_=e.queryParameters.map(m=>T95({queryParameter:m,typesByName:r,examples:e.userSpecifiedExamples.map(g=>g.example).filter($s)??[]})),y=e.headers.map(m=>R95({httpHeader:m,typesByName:r,examples:e.userSpecifiedExamples.map(g=>g.example).filter($s)??[]})),b=[...f,...p,...h,..._,...y],v=c==="stoplight"?t.displayName??t.name.fernFilepath.allParts.map(m=>m.originalName).join(" "):t.name.fernFilepath.allParts.map(m=>m.pascalCase.unsafeName).join(""),O={description:e.docs??void 0,operationId:[...t.name.fernFilepath.allParts.map(m=>m.camelCase.unsafeName),e.name.originalName].join("_"),tags:[v],parameters:b,responses:B95({httpResponse:e.response,responseErrors:e.errors,errorsByName:i,errorDiscriminationStrategy:n,examples:e.userSpecifiedExamples.map(m=>m.example).filter($s)??[]}),summary:e.displayName??void 0};if(e.baseUrl!=null){let m=e.baseUrl;if(o?.environments.type!=="multipleBaseUrls")throw new Error("baseUrl is defined environments are not multipleBaseUrls");O.servers=o.environments.environments.map(g=>{let A=g.urls[m];if(A==null)throw new Error("No URL defined for "+m);let j={url:A};return g.docs!=null&&(j.description=g.docs),j})}return e.auth&&(O.security=a),e.requestBody!=null&&(O.requestBody=I95({httpRequest:e.requestBody,typesByName:r,examples:e.userSpecifiedExamples.map(m=>m.example).filter($s)??[]})),{fullPath:s,convertedHttpMethod:u,operationObject:O}}function D95(e){return EE._visit(e,{get:()=>aia.OpenAPIV3.HttpMethods.GET,post:()=>aia.OpenAPIV3.HttpMethods.POST,put:()=>aia.OpenAPIV3.HttpMethods.PUT,patch:()=>aia.OpenAPIV3.HttpMethods.PATCH,delete:()=>aia.OpenAPIV3.HttpMethods.DELETE,head:()=>aia.OpenAPIV3.HttpMethods.HEAD,_other:()=>{throw new Error("Encountered unknown http method: "+e)}})}function I95({httpRequest:e,typesByName:t,examples:r}){let i={};for(let n of r)n.request!=null&&(n.name&&n.name.originalName!==""?i[n.name.originalName]={value:n.request.jsonExample}:i[`Example${tj(i)+1}`]={value:n.request.jsonExample});return FA._visit(e,{inlinedRequestBody:n=>{let a={schema:Hbc({docs:void 0,properties:n.properties.map(o=>{let c;return r.length>0&&r[0]?.request?.type==="inlinedRequestBody"&&(c=r[0]?.request.properties.find(d=>d.name.wireValue===o.name.wireValue)),{docs:o.docs??void 0,name:o.name,valueType:o.valueType,example:c}}),extensions:n.extends})};return tj(i)>0&&(a.examples=i),{required:!0,content:{"application/json":a}}},reference:n=>{let a={schema:QT(n.requestBodyType)};return tj(i)>0&&(a.examples=i),{description:n.docs??void 0,required:Gbc({typeReference:n.requestBodyType,typesByName:t}),content:{"application/json":a}}},fileUpload:n=>({required:!0,content:{"multipart/form-data":{schema:{type:"object",properties:n.properties.reduce((a,o)=>(dR._visit(o,{file:c=>{a[c.key.wireValue]={type:"string",format:"binary"}},bodyProperty:c=>{a[c.name.wireValue]={description:c.docs??void 0,...QT(c.valueType)}},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}}),{...a}),{})}}}}),bytes:()=>{throw new Error("bytes is not supported")},_other:()=>{throw new Error("Unknown HttpRequestBody type: "+e.type)}})}function B95({httpResponse:e,responseErrors:t,errorsByName:r,errorDiscriminationStrategy:i,examples:n}){let a={};if(e?.body?.type==="json"){let o={schema:QT(e.body.value.responseBodyType)},c={};for(let d of n)d.response.type==="ok"&&d.response.value.type==="body"&&d.response.value.value!=null&&(d.name&&d.name.originalName!==""?c[d.name.originalName]={value:d.response.value.value.jsonExample}:c[`Example${tj(c)+1}`]={value:d.response.value.value.jsonExample});tj(c)>0&&(o.examples=c),a[String(e.statusCode??200)]={description:e.body.value.docs??"",content:{"application/json":o}}}else a[204]={description:""};return Kme._visit(i,{statusCode:()=>{for(let o of t){let c=r[Kbc(o.error)];if(c==null)throw new Error("Encountered undefined error declaration: "+o.error.name.originalName);let d={description:o.docs??""};if(c.type!=null){let s={schema:QT(c.type)},u={};for(let f of n)f.response.type==="error"&&f.response.body!=null&&EC(o.error,f.response.error)&&(f.name&&f.name.originalName!==""?u[f.name.originalName]={value:f.response.body.jsonExample}:u[`Example${tj(u)+1}`]={value:f.response.body.jsonExample});tj(u)>0&&(s.examples=u),d.content={"application/json":s}}a[c.statusCode]=d}},property:o=>{let c=q95({responseErrors:t,errorsByName:r});for(let d of Object.keys(c)){let s=c[d];if(s==null||s.length===0)continue;let u={schema:{oneOf:s.map(p=>C95({errorInfo:p,property:o}))}},f={};for(let p of n)if(p.response.type==="error"&&p.response.body!=null){let h=p.response.error;s.some(_=>EC(_.errorDeclaration.name,h))&&(p.name&&p.name.originalName!==""?f[p.name.originalName]={value:p.response.body.jsonExample}:f[`Example${tj(f)+1}`]={value:p.response.body.jsonExample})}tj(f)>0&&(u.examples=f),a[d]={description:"",content:{"application/json":u}}}},_other:()=>{throw new Error("Unknown error discrimination strategy: "+i.type)}}),a}function C95({errorInfo:e,property:t}){let r=e.errorDeclaration.discriminantValue.wireValue,i=e.responseError.docs??void 0,n={[t.discriminant.wireValue]:{type:"string",enum:[r]}};return e.errorDeclaration.type!=null&&(n[t.contentProperty.wireValue]=QT(e.errorDeclaration.type)),{type:"object",description:i,properties:n}}function q95({responseErrors:e,errorsByName:t}){let r={};for(let i of e){let n=t[Kbc(i.error)];if(n==null)throw new Error("Encountered undefined error declaration: "+i.error.name.originalName);let a=n.statusCode,o=r[a];o==null?r[a]=[{responseError:i,errorDeclaration:n}]:o.push({responseError:i,errorDeclaration:n})}return r}function ALp({pathParameter:e,examples:t}){let r={name:e.name.originalName,in:"path",description:e.docs??void 0,required:!0,schema:QT(e.valueType)},i={};for(let n of t){let a=[...n.rootPathParameters,...n.servicePathParameters,...n.endpointPathParameters].find(o=>o.name.originalName===e.name.originalName);a!=null&&(n.name&&n.name.originalName!==""?i[n.name.originalName]={value:a.value.jsonExample}:i[`Example${tj(i)+1}`]={value:a.value.jsonExample},r.example==null&&(r.example=a.value.jsonExample))}return tj(i)>0&&(r.examples=i),r}function T95({queryParameter:e,typesByName:t,examples:r}){let i={name:e.name.wireValue,in:"query",description:e.docs??void 0,required:Gbc({typeReference:e.valueType,typesByName:t}),schema:e.allowMultiple?QT(hi.container(Js.list(e.valueType))):QT(e.valueType)},n={};for(let a of r){let o=a.queryParameters.find(c=>c.name.wireValue===e.name.wireValue);o!=null&&(a.name&&a.name.originalName!==""?n[a.name.originalName]={value:o.value.jsonExample}:n[`Example${tj(n)+1}`]={value:o.value.jsonExample},i.example==null&&(i.example=o.value.jsonExample))}return tj(n)>0&&(i.examples=n),i}function R95({httpHeader:e,typesByName:t,examples:r}){let i={name:e.name.wireValue,in:"header",description:e.docs??void 0,required:Gbc({typeReference:e.valueType,typesByName:t}),schema:QT(e.valueType)},n={};for(let a of r){let o=[...a.serviceHeaders,...a.endpointHeaders].find(c=>c.name.wireValue===e.name.wireValue);o!=null&&(a.name&&a.name.originalName!==""?n[a.name.originalName]={value:o.value.jsonExample}:n[`Example${tj(n)+1}`]={value:o.value.jsonExample},i.example==null&&(i.example=o.value.jsonExample))}return tj(n)>0&&(i.examples=n),i}function PLp(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return t}function Gbc({typeReference:e,typesByName:t}){if(e.type==="container"&&e.container.type==="optional")return!1;if(e.type==="named"){let r=jLp(e),i=t[r];if(i==null)throw new Error("Encountered non-existent type: "+e.name.originalName);if(i.shape.type==="alias")return Gbc({typeReference:i.shape.aliasOf,typesByName:t})}return!0}function HgS(e){return EN._visit(e.requirement,{all:()=>[e.schemes.reduce((t,r)=>({...t,[wLp(r)]:[]}),{})],any:()=>e.schemes.map(t=>({[wLp(t)]:[]})),endpointSecurity:()=>[],_other:()=>{throw new Error("Unknown auth scheme requirement: "+e.requirement)}})}function GgS(e){let t={};for(let r of e.schemes){let i=AP._visit(r,{bearer:()=>({type:"http",scheme:"bearer"}),basic:()=>({type:"http",scheme:"basic"}),header:n=>({type:"apiKey",in:"header",name:n.name.wireValue}),oauth:()=>({type:"http",scheme:"bearer"}),inferred:()=>{},_other:()=>{throw new Error("Unknown auth scheme: "+r.type)}});i&&(t[wLp(r)]=i)}return t}function wLp(e){return AP._visit(e,{bearer:()=>"BearerAuth",inferred:()=>"InferredAuth",basic:()=>"BasicAuth",oauth:()=>"BearerAuth",header:t=>`${t.name.name.pascalCase.unsafeName}Auth`,_other:()=>{throw new Error("Unknown auth scheme: "+e.type)}})}function KgS({apiName:e,ir:t,mode:r}){let i={},n={};Object.values(t.types).forEach(u=>{let f=LgS(u,t);i[f.schemaName]={title:f.schemaName,...f.openApiSchema},n[jLp(u.name)]=u});let a={};Object.values(t.errors).forEach(u=>{a[Kbc(u.name)]=u});let o=HgS(t.auth),c=xgS({ir:t,httpServices:Object.values(t.services),typesByName:n,errorsByName:a,errorDiscriminationStrategy:t.errorDiscriminationStrategy,security:o,environments:t.environments??void 0,mode:r}),d={title:t.apiDisplayName??e,version:""};t.apiDocs!=null&&(d.description=t.apiDocs);let s={openapi:"3.0.1",info:d,paths:c,components:{schemas:i,securitySchemes:GgS(t.auth)}};return t.environments!=null&&t.environments.environments.type==="singleBaseUrl"&&(s.servers=t.environments.environments.environments.map(u=>({url:u.url,description:u.docs!=null?`${u.name.originalName} (${u.docs})`:u.name.originalName}))),s}function jLp(e){return[...e.fernFilepath.allParts.map(t=>t.originalName),e.name.originalName].join("-")}function Kbc(e){return[...e.fernFilepath.allParts.map(t=>t.originalName),e.name.originalName].join("-")}async function $gS({project:e,cliContext:t,outputPath:r,indent:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await t.runTaskForWorkspace(n,async a=>{let o=await n.toFernWorkspace({context:a}),c=BE({workspace:o,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!0},readme:void 0,version:void 0,packageName:void 0,context:a,sourceResolver:new TE(a,o)}),d=KgS({apiName:n.workspaceName??"api",ir:c,mode:"openapi"});await(0,$bc.mkdir)(rn(r),{recursive:!0}),await(0,$bc.writeFile)(r,r.endsWith(".json")?JSON.stringify(d,void 0,i):Mi.dump(d,{indent:i}))})}))}async function JgS({project:e,cliContext:t,shouldFix:r}){await Promise.all(e.apiWorkspaces.map(async i=>{i instanceof CP||await t.runTaskForWorkspace(i,async n=>{await WSp({workspace:await i.toFernWorkspace({context:n}),context:n,shouldFix:r})})}))}var YgS="group";var XgS=".preview",ZgS="approved-output-directories",kgS=".fern";var aOS=require("fs/promises");var tOS=require("fs/promises");var eOS=require("os");function Exo(){return ut(vr.of((0,eOS.homedir)()),me.of(kgS),me.of(ZgS))}async function rOS(){let e=Exo();if(!await ii(e))return[];let r=await(0,tOS.readFile)(e,{encoding:"utf-8"});return JSON.parse(r)}var Jbc=require("fs/promises"),iOS=ce(require("path"),1);async function nOS(e){await(0,Jbc.mkdir)(iOS.default.dirname(Exo()),{recursive:!0}),await(0,Jbc.writeFile)(Exo(),JSON.stringify(e,null,2))}async function oOS(e,t,r){if(!e||tRc()||r)return{shouldProceed:!0};let i=await rOS();return i?.includes(e)?{shouldProceed:!0}:await ii(e)?(await(0,aOS.readdir)(e)).length===0?{shouldProceed:!0}:await t.confirmPrompt(`Directory ${e} contains existing files that may be overwritten. Continue?`,!1)?(await nOS([...i??[],e]),{shouldProceed:!0}):{shouldProceed:!1}:{shouldProceed:!0}}var hOS=ce(w3i(),1);async function uOS({groups:e,visitor:t,nodePath:r,cliVersion:i}){if(e!=null)for(let[n,a]of Object.entries(e))await z95({group:a,visitor:t,nodePath:[...r,n],cliVersion:i})}async function z95({group:e,visitor:t,nodePath:r,cliVersion:i}){await Promise.all(e.generators.map(async(n,a)=>await t.generatorInvocation?.({invocation:n,cliVersion:i},[...r,"generators",a.toString(),n.name])))}async function sOS(e,t,r){await r.file?.(e,[]),await a5t(e,{"auth-schemes":mt,api:mt,whitelabel:mt,metadata:mt,readme:mt,"default-group":mt,aliases:mt,reviewers:mt,openapi:mt,"openapi-overrides":mt,"spec-origin":mt,"async-api":mt,"api-settings":mt,ai:mt,autorelease:mt,groups:async i=>{await uOS({groups:i,visitor:r,nodePath:["groups"],cliVersion:t})}})}function cOS({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let o=async(c,d)=>{for(let s of r){let u=s.generatorsYml?.[a];if(u!=null){let f=await u(c,{relativeFilepath:e,contents:t});i(f.map(p=>({severity:p.severity,relativeFilepath:e,nodePath:d,message:p.message})))}}};return{[a]:o}}return{...n("file"),...n("generatorInvocation")}}function N95(e,t,r){if(!p2(r,t))return[{severity:"fatal",message:`The generator ${e} requires CLI version ${t} or later (current version: ${r}). Please run \`fern upgrade\` to upgrade your CLI version and use this generator.`}]}function F95(e){return Number(e.replace("v",""))}var ELp={name:"compatible-ir-version",create:async()=>({generatorsYml:{generatorInvocation:async({invocation:e,cliVersion:t})=>{let r=rJo({token:void 0});if(t==null)return[];let i=await r.generators.cli.getCliRelease(t);if(!i.ok)return[];let n=i.body.irVersion,a;if(e["ir-version"]!=null)a=F95(e["ir-version"]);else{let c={...e,name:DU(e.name)},d=await WOn(c);if(d==null)return[];a=d}if(a<=n)return[];let o=await r.generators.cli.getMinCliForIr(a);return o.ok?N95(e.name,o.body.version,t)??[]:[]}}})};var SLp={name:"valid-alias-group-references",create:async()=>({generatorsYml:{file:async e=>{let t=[],r=e.aliases,i=e.groups??{};if(r==null)return t;let n=new Set(Object.keys(i));for(let[a,o]of Object.entries(r))if(Array.isArray(o))for(let c of o)n.has(c)||t.push({severity:"error",message:`Alias "${a}" references unknown group "${c}". Available groups: ${[...n].join(", ")||"none"}`});return t}}})};function lOS(){return[ELp,SLp]}async function Ybc(e,t){return Q95({workspace:e,rules:lOS(),logger:t})}async function Q95({workspace:e,rules:t,logger:r}){let i=[],n=await Promise.all(t.map(a=>a.create({workspace:e,logger:r})));if(e.generatorsConfiguration?.rawConfiguration){let a=await U95({contents:e.generatorsConfiguration.rawConfiguration,allRuleVisitors:n,cliVersion:e.cliVersion});i.push(...a)}return i}async function U95({contents:e,allRuleVisitors:t,cliVersion:r}){let i=[],n=cOS({relativeFilepath:me.of(GM),contents:e,allRuleVisitors:t,addViolations:a=>{i.push(...a)}});return await sOS(e,r,n),i}var MLp=ce(dOS(),1);async function pOS({workspace:e,context:t,ossWorkspace:r}){(0,MLp.default)(e.definition.rootApiFile.contents.name).validForNewPackages||t.failAndThrow("API name is not valid.");let i=performance.now(),n=nwn(e,t.logger),a=await Ybc(e,t.logger),o=[...n,...a];r&&o.push(...await _ba(r,t));let c=performance.now()-i,d=o.some(s=>s.severity==="fatal"||s.severity==="error");return{apiName:e.definition.rootApiFile.contents.name,violations:o,elapsedMillis:c,hasErrors:d}}async function H95({workspace:e,context:t,logWarnings:r,logSummary:i=!0,ossWorkspace:n}){let a=performance.now(),o=nwn(e,t.logger),c=await Ybc(e,t.logger),d=[...o,...c];n&&d.push(...await _ba(n,t));let s=performance.now()-a,{hasErrors:u}=kGa({violations:d,context:t,logWarnings:r,logSummary:i,elapsedMillis:s});return{hasErrors:u}}async function fvn({workspace:e,context:t,logWarnings:r,ossWorkspace:i}){(0,MLp.default)(e.definition.rootApiFile.contents.name).validForNewPackages||t.failAndThrow("API name is not valid.");let{hasErrors:n}=await H95({workspace:e,context:t,logWarnings:r,ossWorkspace:i});n&&t.failAndThrow()}async function _OS({organization:e,workspace:t,projectConfig:r,context:i,groupName:n,generatorName:a,version:o,shouldLogS3Url:c,token:d,useLocalDocker:s,keepDocker:u,absolutePathToPreview:f,mode:p,runner:h,inspect:_,lfsOverride:y,fernignorePath:b,dynamicIrOnly:v}){if(t.generatorsConfiguration==null){i.logger.warn("This workspaces has no generators.yml");return}if(t.generatorsConfiguration.groups.length===0){i.logger.warn(`This workspace has no groups specified in ${GM}`);return}let O=n??t.generatorsConfiguration.defaultGroup;if(O==null)return i.failAndThrow(`No group specified. Use the --${YgS} option, or set "${epa}" in ${GM}`);let m=G95(O,t.generatorsConfiguration.groupAliases,t.generatorsConfiguration.groups.map(A=>A.groupName),i),{ai:g}=t.generatorsConfiguration;if(!s&&!d)return i.failAndThrow("Please run fern login");await fvn({workspace:await t.toFernWorkspace({context:i}),context:i,logWarnings:!1}),await Promise.all(m.map(async A=>{let j=t.generatorsConfiguration?.groups.find(S=>S.groupName===A);if(j==null)return i.failAndThrow(`Group '${A}' does not exist.`);if(a!=null){let S=j.generators.filter(w=>w.name===a);if(S.length===0){let w=j.generators.map(E=>E.name);return i.failAndThrow(`Generator '${a}' not found in group '${A}'. Available generators: ${w.join(", ")}`)}j={...j,generators:S}}y!=null&&(j=K95(j,y,i)),m.length>1&&i.logger.info(`Running generation for group '${A}'...`),s?await eHE({token:d,projectConfig:r,workspace:t,generatorGroup:j,version:o,keepDocker:u,context:i,runner:h,absolutePathToPreview:f,inspect:_,ai:g}):d!=null&&await C4o({projectConfig:r,organization:e,workspace:t,context:i,generatorGroup:j,version:o,shouldLogS3Url:c,token:d,whitelabel:t.generatorsConfiguration?.whitelabel,absolutePathToPreview:f,mode:p,fernignorePath:b,dynamicIrOnly:v})}))}function G95(e,t,r,i){let n=t[e];if(n!=null){for(let c of n)r.includes(c)||i.failAndThrow(`Group alias '${e}' references non-existent group '${c}'. Available groups: ${r.join(", ")}`);return n}if(r.includes(e))return[e];let a=Object.keys(t),o=[...r,...a];return i.failAndThrow(`'${e}' is not a valid group or alias. Available groups: ${r.join(", ")}`+(a.length>0?`. Available aliases: ${a.join(", ")}`:"")),[]}function K95(e,t,r){let i=vr.of(xo(AO(),t)),n={},a=[];for(let o of e.generators){let c=o.language??$95(o.name),d;if(e.generators.length===1)d=i;else{let u=c||"unknown";n[u]==null&&(n[u]=0),n[u]++;let f=n[u]===1?u:`${u}-${n[u]}`;d=ut(i,me.of(f))}let s={...o,outputMode:hOS.FernFiddle.remoteGen.OutputMode.downloadFiles({}),absolutePathToLocalOutput:d};a.push(s),r.logger.info(`Overriding output for generator '${o.name}' to local-file-system at: ${d}`)}return{...e,generators:a}}function $95(e){return e.includes("typescript")||e.includes("ts")?"typescript":e.includes("python")||e.includes("py")?"python":e.includes("java")?"java":e.includes("go")?"go":e.includes("ruby")?"ruby":e.includes("csharp")||e.includes("c#")?"csharp":e.includes("swift")?"swift":e.includes("php")?"php":e.includes("rust")?"rust":e.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}var bOS={PullRequest:"pull-request"};async function DLp({project:e,cliContext:t,version:r,groupName:i,generatorName:n,shouldLogS3Url:a,keepDocker:o,useLocalDocker:c,preview:d,mode:s,force:u,runner:f,inspect:p,lfsOverride:h,fernignorePath:_,dynamicIrOnly:y,outputDir:b}){let v;if(!c){let O=await t.runTask(async m=>tU(m));O.type==="user"&&await t.runTask(async m=>{await Sme({organization:e.config.organization,token:O,context:m})}),v=O}for(let O of e.apiWorkspaces){let m=yOS(i,O.generatorsConfiguration);for(let g of O.generatorsConfiguration?.groups.filter(A=>m==null||m.includes(A.groupName)).flatMap(A=>A.generators).filter(A=>n==null||A.name===n)??[]){let{shouldProceed:A}=await oOS(g.absolutePathToLocalOutput,t,u);A||t.failAndThrow("Generation cancelled")}}await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate",properties:{workspaces:e.apiWorkspaces.map(O=>{let m=yOS(i,O.generatorsConfiguration);return{name:O.workspaceName,group:i,generators:O.generatorsConfiguration?.groups.filter(g=>m==null||m.includes(g.groupName)).map(g=>g.generators.filter(A=>n==null||A.name===n).map(A=>({name:A.name,version:A.version,outputMode:A.outputMode.type,config:A.config})))}})}}),await Promise.all(e.apiWorkspaces.map(async O=>{await t.runTaskForWorkspace(O,async m=>{let g=d?b!=null?vr.of(xo(AO(),b)):ut(O.absoluteFilePath,me.of(XgS)):void 0;g!=null&&m.logger.info(`Writing preview to ${g}`),await _OS({organization:e.config.organization,workspace:O,projectConfig:e.config,context:m,version:r,groupName:i,generatorName:n,shouldLogS3Url:a,token:v,useLocalDocker:c,keepDocker:o,absolutePathToPreview:g,mode:s,runner:f,inspect:p,lfsOverride:h,fernignorePath:_,dynamicIrOnly:y})})}))}function yOS(e,t){if(e==null)return null;if(t==null)return[e];let r=t.groupAliases[e];return r??[e]}function vOS(){return!!(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.CIRCLECI||process.env.TRAVIS||process.env.JENKINS_URL||process.env.JENKINS_HOME||process.env.TF_BUILD||process.env.BUILDKITE||process.env.CODEBUILD_BUILD_ID||process.env.TEAMCITY_VERSION||process.env.BITBUCKET_BUILD_NUMBER||process.env.DRONE||process.env.SEMAPHORE||process.env.APPVEYOR||process.env.BUDDY_WORKSPACE_ID||process.env.WERCKER_RUN_ID)}async function gOS({project:e,cliContext:t,instance:r,preview:i,brokenLinks:n,strictBrokenLinks:a,disableTemplates:o,noPrompt:c,skipUpload:d}){let s=e.docsWorkspaces;if(s==null){t.failAndThrow("No docs.yml file found. Please make sure your project has one.");return}let u=process.env.FERN_SELF_HOSTED==="true";if(!i&&!vOS()&&!c){let p=r??s.config.instances[0]?.url,h=p?` (${Ke.cyan(`https://${p}`)})`:"";if(!await t.confirmPrompt(`This will affect a production site${h}. Run with --preview to generate docs for a preview instance.
|
|
2607
2607
|
${Ke.yellow("?")} Are you sure you want to continue?`,!1)){t.logger.info("Docs generation cancelled.");return}}let f=null;if(u){let p=process.env.FERN_TOKEN;if(!p){t.failAndThrow("No token found. Please set the FERN_TOKEN environment variable.");return}f={type:"organization",value:p}}else if(f=await t.runTask(async p=>tU(p)),f.type==="user"){let p=f;await t.runTask(async h=>{await Sme({organization:e.config.organization,token:p,context:h})})}u||await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate --docs"}),await t.runTaskForWorkspace(s,async p=>{await jvS({workspace:s,context:p,logWarnings:!1,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:await Ux(e),errorOnBrokenLinks:a,excludeRules:J95(n,a,u)}),p.logger.info("Validation complete, starting remote docs generation...");let h=performance.now(),_=await Ux(e),y=performance.now()-h;p.logger.debug(`Filtered OSS workspaces (${_.length} workspaces) in ${y.toFixed(0)}ms`);let b=performance.now();await cSp({organization:e.config.organization,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:_,docsWorkspace:s,context:p,token:f,instanceUrl:r,preview:i,disableTemplates:o,skipUpload:d});let v=performance.now()-b;p.logger.debug(`Remote docs generation completed in ${v.toFixed(0)}ms`)})}function J95(e,t,r){let i=[];return!e&&!t&&i.push(Oxo.ValidMarkdownLinks.name),r&&i.push(Oxo.ValidFileTypes.name),i}var OOS=ce(require("path"),1);async function a9a({workspace:e,context:t,generationLanguage:r,keywords:i,smartCasing:n,disableExamples:a,audiences:o,readme:c,disableDynamicExamples:d}){return await fvn({workspace:e,context:t,logWarnings:!1}),BE({workspace:e,generationLanguage:r,keywords:i,smartCasing:n,exampleGeneration:{disabled:a},audiences:o,readme:c,version:void 0,packageName:void 0,context:t,sourceResolver:new TE(t,e),disableDynamicExamples:d})}async function mOS({project:e,irFilepath:t,cliContext:r,generationLanguage:i,audiences:n,version:a,keywords:o,smartCasing:c,disableDynamicExamples:d}){await Promise.all(e.apiWorkspaces.map(async s=>{await r.runTaskForWorkspace(s,async u=>{r.logger.info(`Generating IR for workspace ${s.workspaceName??"api"}`);let f=await s.toFernWorkspace({context:u}),p=await a9a({workspace:f,context:u,generationLanguage:i,keywords:o,smartCasing:c,disableExamples:!1,audiences:n,readme:void 0,disableDynamicExamples:d});if(p.dynamic==null)throw new Error("Internal error; dynamic IR was not generated");let h=OOS.default.resolve(t);await y7(vr.of(h),p.dynamic),u.logger.info(`Wrote IR to ${h}`)})}))}var AOS=ce(require("path"),1);async function POS({project:e,outputFilepath:t,cliContext:r,audiences:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await r.runTaskForWorkspace(n,async a=>{let o=await n.toFernWorkspace({context:a}),c=await a9a({workspace:o,context:a,generationLanguage:void 0,audiences:i,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,disableDynamicExamples:!0}),d=VY({ir:c,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},context:a}),s=vr.of(AOS.default.resolve(t));await y7(s,d,{pretty:!0}),a.logger.info(`Wrote FDR API definition to ${s}`)})}))}var jOS=ce(require("path"),1);async function wOS({project:e,irFilepath:t,cliContext:r,generationLanguage:i,audiences:n,version:a,keywords:o,smartCasing:c,readme:d,directFromOpenapi:s,disableExamples:u}){await Promise.all(e.apiWorkspaces.map(async f=>{await r.runTaskForWorkspace(f,async p=>{r.logger.info(`Generating IR for workspace ${f.workspaceName??"api"}`);let h=await Y95({workspace:f,context:p,generationLanguage:i,keywords:o,smartCasing:c,disableExamples:u,audiences:n,version:a,readme:d,directFromOpenapi:s}),_=vr.of(jOS.default.resolve(t));await y7(_,h,{pretty:!0}),p.logger.info(`Wrote IR to ${_}`)})}))}async function Y95({workspace:e,context:t,generationLanguage:r,audiences:i,keywords:n,smartCasing:a,disableExamples:o,version:c,readme:d,directFromOpenapi:s}){let u;if(s&&e instanceof CP)u=await e.getIntermediateRepresentation({context:t,audiences:i,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});else{let f=await e.toFernWorkspace({context:t});u=await a9a({workspace:f,context:t,generationLanguage:r,audiences:i,keywords:n,smartCasing:a,disableExamples:o,readme:d,disableDynamicExamples:!0})}return c==null?ca.IntermediateRepresentation.jsonOrThrow(u,{unrecognizedObjectKeys:"strip"}):r4o({intermediateRepresentation:u,version:c,context:t})}var EOS=ce(require("path"),1);async function ILp({project:e,outputFilepath:t,cliContext:r,directFromOpenapi:i,audiences:n}){await Promise.all(e.apiWorkspaces.map(async a=>{await r.runTaskForWorkspace(a,async o=>{let c=i?await Y0p(a,o,n):await FEp(a,o),d=vr.of(EOS.default.resolve(t));await y7(d,c,{pretty:!0}),o.logger.info(`Wrote FDR API definition to ${d}`)})}))}var SOS=ce(require("path"),1);async function MOS({project:e,irFilepath:t,cliContext:r,sdkLanguage:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await r.runTaskForWorkspace(n,async a=>{if(n instanceof k5){a.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(n instanceof CP))return;let o=new PHt(n.absoluteFilePath),c=await AIe({context:a,specs:n.specs}),d=ejn({context:a,documents:await o.loadDocuments({context:a,specs:c})}),s=vr.of(SOS.default.resolve(t)),u=Dc.OpenApiIntermediateRepresentation.jsonOrThrow(d,{skipValidation:!0});await y7(s,u,{pretty:!0}),a.logger.info(`Wrote IR to ${s}`)})}))}var Xbc=require("fs/promises");async function IOS({originalPath:e,modifiedPath:t,outputPath:r,cliContext:i}){await i.runTask(async n=>{if(!await ii(e))return n.failAndThrow(`Original file does not exist: ${e}`);if(!await ii(t))return n.failAndThrow(`Modified file does not exist: ${t}`);n.logger.info(`Comparing ${e} with ${t}`);let a=await DOS(e,n),o=await DOS(t,n),c=X95(a,o);if(Object.keys(c).length===0){n.logger.info("No differences found between the two specs.");return}let d;if(r!=null)d=r;else{let s=S3i(e),u="openapi-overrides.yml";if(s!=null){let f=s.lastIndexOf(".");f>0&&(u=`${s.substring(0,f)}-overrides.yml`)}d=ut(rn(e),me.of(u))}await(0,Xbc.writeFile)(d,Mi.dump(c,{lineWidth:-1,noRefs:!0})),n.logger.info(`Overrides written to ${d}`)})}async function DOS(e,t){let r=await(0,Xbc.readFile)(e,"utf8");try{return JSON.parse(r)}catch{try{return Mi.load(r)}catch{return t.failAndThrow(`Failed to parse file as JSON or YAML: ${e}`)}}}function X95(e,t){let r={};for(let i of Object.keys(t))if(t[i]!==void 0){let n=BOS(e[i],t[i],i);n!==void 0&&Object.keys(n).length>0&&(r[i]=n)}return r}function BOS(e,t,r){if(t===void 0)return;if(e==null)return t;if(typeof t!="object"||t===null)return e!==t?t:void 0;if(Array.isArray(t))return BLp(e,t)?void 0:t;if(typeof e!="object"||e===null||Array.isArray(e))return t;let i={};for(let n of Object.keys(t)){let a=BOS(e[n],t[n],`${r}.${n}`);a!==void 0&&(i[n]=a)}if(Object.keys(i).length!==0)return i}function BLp(e,t){if(e===t)return!0;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(typeof e!=typeof t)return!1;if(typeof e!="object")return e===t;if(Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!BLp(e[n],t[n]))return!1;return!0}let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r)if(!Object.hasOwn(t,n)||!BLp(e[n],t[n]))return!1;return!0}var Zbc=require("fs/promises");async function CLp({project:e,includeModels:t,cliContext:r}){await Promise.all(e.apiWorkspaces.map(async i=>{await r.runTaskForWorkspace(i,async n=>{i instanceof CP?await k95({workspace:i,context:n,includeModels:t}):n.logger.warn("Skipping fern workspace definition generation")})}))}async function Z95(e,t){let r=null;try{let i=(await(0,Zbc.readFile)(e,"utf8")).toString();try{r=JSON.parse(i)}catch{r=Mi.load(i,{json:!0})}}catch{return t.failAndThrow(`Failed to read OpenAPI overrides from file ${e}`)}return r}async function k95({workspace:e,includeModels:t,context:r}){let i=new PHt(e.absoluteFilePath),n=await AIe({context:r,specs:e.specs});for(let a of n){let o=ejn({context:r,documents:await i.loadDocuments({context:r,specs:[a]})}),c={};a.absoluteFilepathToOverrides!==void 0&&(c=await Z95(a.absoluteFilepathToOverrides,r));let d="path"in c?c.path:{};for(let h of o.endpoints){let _=lro(h);h.path in d||(d[h.path]={});let y=d[h.path];if(y!=null&&y[h.method]==null){let b=_.file.split("/").map(O=>O.replace(".yml","")).filter(O=>O!=="__package__"),v={};b.length>0&&(v["x-fern-sdk-group-name"]=b),v["x-fern-sdk-method-name"]=_.endpointId,y[h.method.toLowerCase()]=v}else c==null&&r.logger.warn(`Endpoint ${h.path} ${h.method} is defined multiple times`)}let s="path"in c?c.path:{};if(t){COS(s,o.groupedSchemas.rootSchemas);for(let[h,_]of Object.entries(o.groupedSchemas.namespacedSchemas))COS(s,_)}let u={schemas:s},f=S3i(a.absoluteFilepath),p="openapi-overrides.yml";if(f!=null){let h=f.lastIndexOf(".");if(h>0){let _=f.substring(0,h),y=f.substring(h);p=`${_}-overrides${y}`}}await(0,Zbc.writeFile)(ut(rn(a.absoluteFilepath),me.of(p)),Mi.dump({paths:d,components:u}))}}function COS(e,t){for(let[r,i]of Object.entries(t)){if(r in e)continue;let n={};n["x-fern-type-name"]="nameOverride"in i?i.nameOverride??r:r,e[r]=n}}function qOS({enum:e,context:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue)}}function TOS({container:e,context:t}){switch(e.type){case"list":return{type:"array",items:vX({typeReference:e.list,context:t})};case"map":return{type:"object",additionalProperties:vX({typeReference:e.valueType,context:t})};case"optional":return e.optional.type==="container"&&e.optional.container.type==="nullable"?{oneOf:[vX({typeReference:e.optional.container.nullable,context:t}),{type:"null"}]}:{oneOf:[vX({typeReference:e.optional,context:t}),{type:"null"}]};case"nullable":return{oneOf:[vX({typeReference:e.nullable,context:t}),{type:"null"}]};case"set":return{type:"array",items:vX({typeReference:e.set,context:t}),uniqueItems:!0};case"literal":switch(e.literal.type){case"string":return{const:e.literal.string};case"boolean":return{const:e.literal.boolean};default:fe(e.literal)}default:fe(e)}}function vX({typeReference:e,context:t}){switch(e.type){case"named":{let r=t.getTypeDeclarationForId({typeId:e.typeId});if(!t.hasDefinition(e.typeId)&&!t.isBuildingTypeDeclaration(e.typeId)){t.buildingTypeDeclaration(e.typeId);let i=o9a({typeDeclaration:r,context:t});t.registerDefinition(e.typeId,i),t.finishedBuildingTypeDeclaration(e.typeId)}return{$ref:`#/definitions/${t.getDefinitionKey(r)}`}}case"container":return TOS({container:e.container,context:t});case"primitive":return e75(e.primitive.v1);case"unknown":return{type:["string","number","boolean","object","array","null"]};default:fe(e)}}function e75(e){switch(e){case Ps.String:return{type:"string"};case Ps.Integer:return{type:"integer"};case Ps.Long:return{type:"integer"};case Ps.Uint:return{type:"integer",minimum:0};case Ps.Uint64:return{type:"integer",minimum:0};case Ps.Float:return{type:"number"};case Ps.Double:return{type:"number"};case Ps.Boolean:return{type:"boolean"};case Ps.Date:return{type:"string",format:"date"};case Ps.DateTime:return{type:"string",format:"date-time"};case Ps.Uuid:return{type:"string",format:"uuid"};case Ps.Base64:return{type:"string",contentEncoding:"base64"};case Ps.BigInteger:return{type:"string",pattern:"^-?[0-9]+$"};default:fe(e)}}function ROS({object:e,context:t}){let r={type:"object"},i=[...e.extendedProperties??[],...e.properties],n=i.map(o=>{let c=o.name.wireValue,d=vX({typeReference:o.valueType,context:t});return[c,d]}),a=i.filter(o=>!t.isOptional(o.valueType)).map(o=>o.name.wireValue);return n.length>0&&(r.properties=Object.fromEntries(n)),a.length>0&&(r.required=a),r.additionalProperties=e.extraProperties,r}function zOS({undiscriminatedUnion:e,context:t}){return{anyOf:e.members.map(r=>{let i=vX({typeReference:r.type,context:t});return r.docs&&(i.description=r.docs),i})}}function NOS({union:e,context:t}){let r=e.discriminant.wireValue;return{type:"object",properties:{[r]:{type:"string",enum:e.types.map(i=>i.discriminantValue.wireValue)}},oneOf:e.types.map(i=>{let n={},a=[];switch(i.shape.propertiesType){case"samePropertiesAsObject":{let o=t.getTypeDeclarationForId({typeId:i.shape.typeId}),c=o9a({typeDeclaration:o,context:t});n=c.properties??{},a=Array.isArray(c.required)?c.required:[];break}case"singleProperty":n.value=vX({typeReference:i.shape.type,context:t});break;case"noProperties":break;default:fe(i.shape)}return{properties:{[r]:{const:i.discriminantValue.wireValue},...n},required:[r,...a]}})}}function o9a({typeDeclaration:e,context:t}){switch(e.shape.type){case"object":return ROS({object:e.shape,context:t});case"alias":return vX({typeReference:e.shape.aliasOf,context:t});case"enum":return qOS({enum:e.shape,context:t});case"union":return NOS({union:e.shape,context:t});case"undiscriminatedUnion":return zOS({undiscriminatedUnion:e.shape,context:t});default:fe(e.shape)}}var kbc=class{context;ir;buildingTypeIds=new Set;definitions={};constructor(t,r){this.context=t,this.ir=r}getTypeDeclarationForId({typeName:t,typeId:r}){let i=this.ir.types[r];return i??(t!=null&&this.context.logger.error(`Type ${t} not found`),this.context.failAndThrow())}isOptional(t){if(t.type==="container"&&t.container.type==="optional")return!0;if(t.type==="named"){let r=this.getTypeDeclarationForId({typeId:t.typeId});if(r.shape.type==="alias")return this.isOptional(r.shape.aliasOf)}return!1}registerDefinition(t,r){let i=this.getTypeDeclarationForId({typeId:t});this.definitions[this.getDefinitionKey(i)]=r}getDefinitions(){return this.definitions}hasDefinition(t){let r=this.getTypeDeclarationForId({typeId:t});return this.getDefinitionKey(r)in this.definitions}getDefinitionKey(t){return[...t.name.fernFilepath.allParts.map(r=>r.originalName),t.name.name.originalName].join(".")}buildingTypeDeclaration(t){this.buildingTypeIds.add(t)}finishedBuildingTypeDeclaration(t){this.buildingTypeIds.delete(t)}isBuildingTypeDeclaration(t){return this.buildingTypeIds.has(t)}};function qLp(e){let t=new kbc(e.context,e.ir),r=t.getTypeDeclarationForId({typeId:e.typeId,typeName:e.typeName});return{...o9a({typeDeclaration:r,context:t}),definitions:t.getDefinitions()}}var evc=require("fs/promises");async function FOS({typeLocator:e,project:t,jsonschemaFilepath:r,cliContext:i}){await Promise.all(t.apiWorkspaces.map(async n=>{await i.runTaskForWorkspace(n,async a=>{let o=await n.toFernWorkspace({context:a}),c=BE({workspace:o,context:a,generationLanguage:void 0,audiences:{type:"all"},keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!0},disableDynamicExamples:!0,version:void 0,packageName:void 0,readme:void 0,sourceResolver:new TE(a,o)}),d=e.split("."),s=Z7({generationLanguage:void 0,keywords:void 0,smartCasing:!1}),u=d[d.length-1]??e,f=d.length>1?`${d.slice(0,-1).join("/")}.yml`:Gv,p=Dh.generateTypeId({fernFilepath:f2({relativeFilepath:me.of(`${d.slice(0,-1).join("/")}.yml`),casingsGenerator:s}),name:s.generateName(u),displayName:void 0}),h=qLp({ir:c,typeName:u,typeId:p,context:a});await ii(rn(r))||await(0,evc.mkdir)(rn(r),{recursive:!0}),await(0,evc.writeFile)(r,JSON.stringify(h,null,2)),a.logger.info(Ke.green(`Wrote JSON Schema to ${r}`))})}))}var TLp=ce(_yc(),1);var tvc=ce(gO(),1);function QOS({request:e,example:t}){if(t.request==null&&Object.entries(e.body??{}).length===0)return{type:"equal"};if(typeof t.request?.jsonExample=="object"){if(c2t(JSON.stringify(e.body),JSON.stringify(t.request?.jsonExample??{})))return{type:"equal"};for(let[r,i]of Object.entries(t.request?.jsonExample??{})){let n=e.body[r];if(!EC(n,i))return{type:"notEqual",parameter:[r],actualValue:n,expectedValue:i,location:"body"}}return{type:"equal"}}return c2t(JSON.stringify(e.body),JSON.stringify(t.request?.jsonExample??{}))?{type:"equal"}:{type:"notEqual",parameter:[],actualValue:e.body,expectedValue:t.request?.jsonExample,location:"body"}}function UOS({request:e,example:t}){for(let r of[...t.serviceHeaders,...t.endpointHeaders]){let i=e.headers[r.name.wireValue.toLowerCase()];if(!c2t(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.wireValue],actualValue:i,expectedValue:r.value.jsonExample,location:"header"}}return{type:"equal"}}function LOS({request:e,example:t}){for(let r of[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters]){let i=e.params[r.name.originalName];if(!c2t(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.originalName],actualValue:i,expectedValue:r.value.jsonExample,location:"path"}}return{type:"equal"}}function VOS({request:e,example:t}){for(let r of[...t.queryParameters]){let i=e.query[r.name.wireValue];if(!c2t(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.wireValue],actualValue:i,expectedValue:r.value.jsonExample,location:"query"}}return{type:"equal"}}function WOS({request:e,example:t}){let r=LOS({request:e,example:t});if(r.type==="notEqual")return r;let i=VOS({request:e,example:t});if(i.type==="notEqual")return i;let n=UOS({request:e,example:t});if(n.type==="notEqual")return n;let a=QOS({request:e,example:t});return a.type==="notEqual"?a:{type:"equal"}}var oia=class{app=(0,TLp.default)();context;server=void 0;port=void 0;constructor({context:t,ir:r,port:i}){this.context=t,this.app.use(TLp.default.json({limit:"50mb",strict:!1})),this.port=i;let n=new Map;for(let d of Object.values(r.services))for(let s of d.endpoints){let u=t75(s);t.logger.debug(`Registering ${s.method} ${u} ...`);let f=n.get(u)??new Map,p=f.get(s.method)??[];n.set(u,f.set(s.method,[...p,s]))}let a=(d,s)=>{let u=d[0],f=s[0],p=u.split("/"),h=f.split("/");if(p.length!==h.length)return p.length-h.length;for(let _=0;_<Math.min(p.length,h.length);_++){let y=p[_],b=h[_];if(y===b)continue;if(y==null||b==null)return y==null?-1:1;let v=y.startsWith(":"),O=b.startsWith(":");return v&&!O?1:!v&&O?-1:y.localeCompare(b)}return 0},c=Array.from(n).sort(a);for(let[d,s]of c)for(let[u,f]of s)switch(u){case"GET":this.app.get(d,Mxo(f));break;case"POST":this.app.post(d,Mxo(f));break;case"PUT":this.app.put(d,Mxo(f));break;case"PATCH":this.app.patch(d,Mxo(f));break;case"DELETE":this.app.delete(d,Mxo(f));break}}stop(){this.server?.close()}async start(){return this.port=this.port??await pGa(),this.server=this.app.listen(this.port),this.context.logger.info(`Running Fern mock server on localhost: ${this.port}`),this.port}async keepAlive(){await new Promise(()=>{})}};function t75(e){let t="";e.fullPath.head.length>0&&(t=(0,tvc.default)(t,e.fullPath.head));for(let r of e.fullPath.parts)t=(0,tvc.default)(t,":"+r.pathParameter),r.tail.length>0&&(t=(0,tvc.default)(t,r.tail));return t.startsWith("/")?t:`/${t}`}function Mxo(e){let t=!1;return(r,i)=>{let n=[];for(let a of e)for(let o of[...a.userSpecifiedExamples,...a.autogeneratedExamples])if(t=!0,o.example!=null){let c=WOS({request:r,example:o.example});if(c.type==="notEqual"){n.push(c);continue}o.example.response?._visit({ok:d=>{d._visit({body:s=>{if(s==null){i.sendStatus(a.response?.statusCode??204);return}if(a.response?.body?.type==="text"){i.contentType("text/plain"),i.send(s.jsonExample);return}i.json(s.jsonExample)},stream:s=>{s.forEach(u=>{i.write(u.jsonExample)}),i.end()},sse:s=>{i.setHeader("Content-Type","text/event-stream"),s.forEach(u=>{i.write(`event: ${u.event}
|
|
2608
2608
|
`),i.write(`data: ${JSON.stringify(u.data.jsonExample)}
|
|
2609
2609
|
|
|
@@ -2647,7 +2647,7 @@ ${Ke.dim(a.summary)}`}));r.push("Do you wish to continue?");let{[t]:i}=await w5t
|
|
|
2647
2647
|
`)[0];if(!o)return{version:null,failureReason:"config-not-tracked"};let{stdout:c,failed:d}=await Q_(t,"git",["show",`HEAD:${o}`],{cwd:n,doNotPipeOutput:!0,reject:!1});if(d||!c.trim())return{version:null,failureReason:"no-git-history"};let u=JSON.parse(c).version??null;return u==null?{version:null,failureReason:"no-version-field"}:{version:u}}catch(r){return t.debug(`Failed to retrieve version from git: ${r}`),{version:null,failureReason:"parse-error"}}}async function $0S({fromVersion:e,fromGit:t,cliContext:r,fernDirectory:i,projectConfig:n,isLocalDev:a}){let o=e?.trim(),c=process.env[Agc]?.trim(),d=Y0S({cliVersion:r.environment.packageVersion,fromVersion:e,isLocalDev:a});if(!o&&c&&c!=="0.0.0"&&!d&&!t&&(o=c),!o||d||t){let s=await xY5(i,r.logger);if(s.version!=null)d&&r.logger.debug(`Detected faulty upgrade (FERN_PRE_UPGRADE_VERSION=${process.env[Agc]}). Using version from git history: ${s.version}`),o=s.version;else if(d){let u=K0S(s.failureReason);r.logger.warn(`Detected potential faulty upgrade but could not retrieve version from git history${u}. Using current config version: ${n.version}`),o=n.version}else if(t){let u=K0S(s.failureReason);r.logger.debug(`Could not retrieve version from git${u}. Falling back to config.`),o=o||n.version}else o=o||n.version}return o}function HY5({cliContext:e,targetVersion:t,currentVersion:r}){p2(t,r)||e.failAndThrow(`Cannot upgrade because target version (${t}) is not ahead of existing version ${r}`)}function GY5(e){let t=new Set(["--version","--to","--from","--from-git"]),r=[],i=0;for(;i<e.length;){let n=e[i];if(i===0&&n==="upgrade"){i++;continue}let a=t.has(n??""),o=Array.from(t).some(c=>n?.startsWith(`${c}=`));a?(i++,i<e.length&&!e[i]?.startsWith("-")&&i++):(o||n!=null&&r.push(n),i++)}return r}async function X0S({cliContext:e,includePreReleases:t,targetVersion:r,fromVersion:i,fromGit:n,yes:a}){let o=e.environment.packageVersion==="0.0.0",c=r?.trim();if(!c){let _=(await e.isUpgradeAvailable({includePreReleases:t})).cliUpgradeInfo;if(_!=null&&_.isUpgradeAvailable)c=_.latestVersion;else{if(o){e.logger.info("No upgrade available.");return}let b=await JM();if(b==null)return e.failAndThrow(`Directory "${ME}" not found.`);let v=await e.runTask(m=>aAe({directory:b,context:m})),O=Y0S({cliVersion:e.environment.packageVersion,fromVersion:i,isLocalDev:o});if(v.version!==e.environment.packageVersion||O)c=e.environment.packageVersion,O?e.logger.info(`Detected faulty upgrade. Config version is ${v.version}, CLI version is ${e.environment.packageVersion}`):e.logger.info(`No newer version available, but config version (${v.version}) differs from CLI version (${e.environment.packageVersion})`);else{e.logger.info("No upgrade available.");return}}}if(e.environment.packageVersion===c||o){let h=await JM();if(h==null)return e.failAndThrow(`Directory "${ME}" not found.`);let _=await e.runTask(v=>aAe({directory:h,context:v})),y=await $0S({fromVersion:i,fromGit:n,cliContext:e,fernDirectory:h,projectConfig:_,isLocalDev:o});e.logger.info(`Running migrations from ${Ke.dim(y)} \u2192 ${Ke.green(c)}`),await e.runTask(async v=>{await N4p({fromVersion:y,toVersion:c,context:v,yes:a??!1})}),await e.exitIfFailed();let b=Wbc(_.rawConfig,v=>{v.version=c});await(0,J0S.writeFile)(_._absolutePath,WY5(JSON.stringify(b,void 0,2))),e.logger.info(`Updated fern.config.json to version ${Ke.green(c)}`);return}HY5({cliContext:e,targetVersion:c,currentVersion:e.environment.packageVersion});let d=await JM();if(d==null)return e.failAndThrow(`Directory "${ME}" not found.`);let s=await e.runTask(h=>aAe({directory:d,context:h})),u=await $0S({fromVersion:i,fromGit:n,cliContext:e,fernDirectory:d,projectConfig:s,isLocalDev:o});e.logger.info(`Upgrading from ${Ke.dim(e.environment.packageVersion)} \u2192 ${Ke.green(c)}`);let f=GY5(process.argv.slice(2)),p=["upgrade","--from",u,"--to",c,...f];a&&!f.some(h=>h==="--yes"||h==="-y")&&p.push("--yes");try{await Uxo({version:c,cliContext:e,env:{[Agc]:u},args:p,throwOnError:!0})}catch(h){if(h instanceof Qxo){e.logger.debug(`Rerun CLI failed with stdout: ${h.stdout}`),e.logger.debug(`Rerun CLI failed with stderr: ${h.stderr}`);let _=(h.stderr??"")+(h.stdout??"");if(_.includes("ETARGET")||_.includes("E404")||_.includes("404 Not Found")||_.includes("No matching version found")||_.includes("version not found"))return e.failAndThrow(`Failed to upgrade to ${c} because it does not exist. See https://www.npmjs.com/package/${e.environment.packageName}?activeTab=versions.`)}throw h}}async function Z0S({project:e,cliContext:t,errorOnBrokenLinks:r}){let i=e.docsWorkspaces;if(i==null){t.failAndThrow("No docs workspace found");return}await t.runTaskForWorkspace(i,async n=>{let a=performance.now(),o=await Ux(e),c=await ZGa(i,n,e.apiWorkspaces,o,!0),d=performance.now()-a;kGa({violations:c,context:n,logWarnings:!0,logSummary:!0,logBreadcrumbs:!1,elapsedMillis:d}),c.length>0&&r&&n.failAndThrow()})}function tES({apiResults:e,docsResult:t,logWarnings:r,context:i}){let n=performance.now(),a=!1;if(e.filter(u=>{let f=Lxo(u.violations);return f.numErrors>0||r&&f.numWarnings>0}).length>0){let u=ZY5(e.map(p=>p.violations).flat());if(e.length>1){i.logger.info(Ke.cyan(Ke.bold("[sdk]")));for(let p of e){let h=Lxo(p.violations);(h.numErrors>0||r&&h.numWarnings>0)&&(a=a||h.numErrors>0,$Y5({apiName:p.apiName,violations:p.violations,stats:h,logWarnings:r,context:i,indent:" "}))}}else a=a||u.numErrors>0,KY5({violations:e[0]?.violations??[],stats:u,logWarnings:r,context:i})}if(t!=null){let u=Lxo(t.violations);(u.numErrors>0||r&&u.numWarnings>0)&&(a=a||u.numErrors>0,JY5({violations:t.violations,stats:u,logWarnings:r,context:i}))}let c=performance.now()-n,d=[...e.map(u=>u.violations).flat(),...t?.violations??[]],s=Lxo(d);return kY5({stats:s,logWarnings:r,elapsedMillis:c,context:i}),{hasErrors:a}}function KY5({violations:e,stats:t,logWarnings:r,context:i}){let n=Q4p(t,r);i.logger.info(Ke.cyan(Ke.bold("[sdk]"))+` ${n}`),F4p({violations:e,logWarnings:r,context:i,indent:" "})}function $Y5({apiName:e,violations:t,stats:r,logWarnings:i,context:n,indent:a}){let o=Q4p(r,i);n.logger.info(`${a}${Ke.bold(`[${e}]`)} ${o}`),F4p({violations:t,logWarnings:i,context:n,indent:a+" "})}function JY5({violations:e,stats:t,logWarnings:r,context:i}){let n=Q4p(t,r);i.logger.info(Ke.magenta(Ke.bold("[docs]"))+` ${n}`),F4p({violations:e,logWarnings:r,context:i,indent:" "})}function F4p({violations:e,logWarnings:t,context:r,indent:i}){let n=e.filter(o=>o.severity==="fatal"||o.severity==="error"),a=e.filter(o=>o.severity==="warning");if(t)for(let o of a.sort(eES))k0S({violation:o,context:r,indent:i});for(let o of n.sort(eES))k0S({violation:o,context:r,indent:i})}function k0S({violation:e,context:t,indent:r}){let i=XY5(e.severity),n=YY5(e);n===""?t.logger.info(`${r}${i} ${e.message}`):(t.logger.info(`${r}${i}`),t.logger.info(`${r} path: ${Ke.blue(n)}`),t.logger.info(`${r} issue: ${e.message}`)),t.logger.info("")}function YY5(e){let t=[];e.relativeFilepath!==""&&t.push(e.relativeFilepath);for(let r of e.nodePath){let i=typeof r=="string"?r:r.key;typeof r!="string"&&r.arrayIndex!=null&&(i+=`[${r.arrayIndex}]`),t.push(i)}return t.join(" -> ")}function XY5(e){switch(e){case"fatal":return Ke.red("[error]");case"error":return Ke.red("[error]");case"warning":return Ke.yellow("[warning]");default:fe(e)}}function Q4p(e,t){let r=[];return e.numErrors>0&&r.push(`${e.numErrors} error${e.numErrors!==1?"s":""}`),t&&e.numWarnings>0&&r.push(`${e.numWarnings} warning${e.numWarnings!==1?"s":""}`),r.join(", ")}function Lxo(e){let t=0,r=0;for(let i of e)switch(i.severity){case"fatal":case"error":t+=1;break;case"warning":r+=1;break;default:fe(i.severity)}return{numErrors:t,numWarnings:r}}function ZY5(e){return Lxo(e)}function eES(e,t){let r=e.relativeFilepath.localeCompare(t.relativeFilepath);return r!==0?r:JSON.stringify(e.nodePath).localeCompare(JSON.stringify(t.nodePath))}function kY5({stats:e,logWarnings:t,elapsedMillis:r,context:i}){let n=r>0?` in ${(r/1e3).toFixed(3)} seconds.`:".",a=`Found ${e.numErrors} error${e.numErrors!==1?"s":""} and ${e.numWarnings} warning${e.numWarnings!==1?"s":""}`+n;!t&&e.numWarnings>0&&(a+=" Run fern check --warnings to print out the warnings not shown."),e.numErrors>0?i.logger.error(a):e.numWarnings>0?i.logger.warn(a):i.logger.info(Ke.green("All checks passed"))}async function rES({project:e,cliContext:t,logWarnings:r,brokenLinks:i,errorOnBrokenLinks:n,isLocal:a,directFromOpenapi:o}){let c=[],d,s=!1,u=e.docsWorkspaces;if(u!=null){let p=i||n?[]:["valid-markdown-links"],h=await Ux(e),_;await t.runTaskForWorkspace(u,async y=>{_=await PvS({workspace:u,context:y,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:h,errorOnBrokenLinks:n,excludeRules:p})}),_!=null&&(d={violations:_.violations,elapsedMillis:_.elapsedMillis},_.hasErrors&&(s=!0))}await Promise.all(e.apiWorkspaces.map(async p=>{if(p.generatorsConfiguration?.groups.length===0&&p.type!=="fern")return;if(p instanceof CP&&o){await t.runTaskForWorkspace(p,async _=>{await p.getIntermediateRepresentation({context:_,audiences:{type:"all"},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,logWarnings:r})});return}if(p instanceof k5){let _=ut(p.absoluteFilePath,me.of(HM),me.of(zC));if(!await ii(_)){await t.runTask(async b=>(b.logger.error(`Missing file: ${zC}`),b.failAndThrow()));return}}let h;await t.runTaskForWorkspace(p,async _=>{let y=await p.toFernWorkspace({context:_});h=await pOS({workspace:y,context:_,ossWorkspace:p instanceof CP?p:void 0})}),h!=null&&(c.push({apiName:h.apiName,violations:h.violations,elapsedMillis:h.elapsedMillis}),h.hasErrors&&(s=!0))}));let{hasErrors:f}=await t.runTask(p=>tES({apiResults:c,docsResult:d,logWarnings:r,context:p}));(f||s)&&t.failAndThrow()}var S4i=require("fs/promises");var U4p=ce(require("path"),1);async function iES({project:e,cliContext:t,sdkLanguage:r,preserveSchemaIds:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await t.runTaskForWorkspace(n,async a=>{n instanceof xZ?await eX5({workspace:n,context:a}):await tX5({workspace:await n.toFernWorkspace({context:a},{preserveSchemaIds:i}),context:a})})}))}async function eX5({workspace:e,context:t}){for(let[r,i]of Object.entries(e.definition.importedDefinitions)){let n=ut(e.absoluteFilePath,me.of(HM),me.of(r),me.of(`.${HM}`));await nES({definition:i.definition,absolutePathToOutputDirectory:n}),t.logger.info(Ke.green(`Wrote imported definition at ${U4p.default.relative(process.cwd(),n)}`))}}async function tX5({workspace:e,context:t}){let r=ut(e.absoluteFilePath,me.of(`.${HM}`));await nES({definition:e.definition,absolutePathToOutputDirectory:r}),t.logger.info(Ke.green(`Wrote definition to ${U4p.default.relative(process.cwd(),r)}`))}async function nES({definition:e,absolutePathToOutputDirectory:t}){let r=(i,n)=>{let a={imports:0,types:1,services:2},o=i in a?a[i]:Object.keys(a).length,c=n in a?a[n]:Object.keys(a).length;return o==null?-1:c==null?1:o!==c?o-c:i.localeCompare(n)};await ii(t)&&await(0,S4i.rm)(t,{recursive:!0}),await(0,S4i.mkdir)(t,{recursive:!0}),await(0,S4i.writeFile)(ut(t,me.of(zC)),Mi.dump(e.rootApiFile.contents,{sortKeys:r}));for(let[i,n]of Object.entries(e.packageMarkers)){let a=ut(t,me.of(i));await(0,S4i.mkdir)(rn(a),{recursive:!0}),await(0,S4i.writeFile)(a,Mi.dump(n.contents,{sortKeys:r}))}for(let[i,n]of Object.entries(e.namedDefinitionFiles)){let a=ut(t,me.of(i));await(0,S4i.mkdir)(rn(a),{recursive:!0}),await(0,S4i.writeFile)(a,Mi.dump(n.contents,{sortKeys:r}))}}var aES=require("fs/promises");async function oES({project:e,outputPath:t,cliContext:r}){let i=e.docsWorkspaces;i!=null&&await r.runTaskForWorkspace(i,async n=>{let a=await Ux(e),o=await Promise.all(e.apiWorkspaces.map(async s=>s.toFernWorkspace({context:n},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),d=await new h$t({domain:i.config.instances[0]?.url??"http://localhost:8080",docsWorkspace:i,ossWorkspaces:a,apiWorkspaces:o,taskContext:n,editThisPage:void 0,uploadFiles:void 0,registerApi:void 0,targetAudiences:i.config.instances[0]?.audiences?Array.isArray(i.config.instances[0].audiences)?i.config.instances[0].audiences:[i.config.instances[0].audiences]:void 0}).resolve();await(0,aES.writeFile)(vr.of(t),JSON.stringify(d,null,2)),n.logger.info(Ke.green(`Docs definition written to ${t}`))})}var PES=ce(AQp(),1),P9a=require("fs"),C8t=require("fs/promises"),jES=ce(Nxc(),1),G4p=ce(require("path"),1);var rX5="https://r88yjrnw5k.execute-api.us-east-1.amazonaws.com/dev2/translate",iX5=3,nX5=1e3,aX5=3e4,oX5=3e4;function uES(e,t){if(e.name==="AbortError"||e.code==="ECONNRESET"||e.code==="ENOTFOUND"||e.code==="ECONNREFUSED"||e.code==="ETIMEDOUT")return!0;if(e.cause instanceof Error){let r=e.cause;if(r.code==="ECONNRESET"||r.code==="ENOTFOUND"||r.code==="ECONNREFUSED"||r.code==="ETIMEDOUT")return!0}if(t){let r=t.status;if(r>=500&&r<600||r===429||r===408)return!0}return!1}function sES(e,t,r){let i=t*Math.pow(2,e-1),n=Math.random()*.1*i;return Math.min(i+n,r)}function uX5(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r);return fetch(e,{...t,signal:i.signal}).finally(()=>{clearTimeout(n)})}async function Vxo({text:e,language:t,sourceLanguage:r,fileType:i,cliContext:n,retryConfig:a={}}){if(t===r)return e;let o=await Tmn();if(o==null)throw n.logger.error("Authentication required. Please run 'fern login' or set the FERN_TOKEN environment variable."),new Error("Authentication required for translation service");let c={maxRetries:a.maxRetries??iX5,baseDelay:a.baseDelay??nX5,maxDelay:a.maxDelay??aX5,timeout:a.timeout??oX5},d;for(let u=1;u<=c.maxRetries+1;u++)try{let f=await uX5(rX5,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.value}`},body:JSON.stringify({text:e,source_language:r,target_language:t,...i!==void 0&&{file_type:i}})},c.timeout);if(!f.ok){let h="";try{let y=await f.json();h=y.detail||JSON.stringify(y)}catch{h=await f.text()}if(f.status===403)throw new Error(`403: ${h}`);let _=new Error(`HTTP ${f.status}: ${h}`);if(!uES(_,f))return n.logger.debug(`[TRANSLATE] Non-retriable error ${f.status}: ${h}`),e;if(d=_,u<=c.maxRetries){n.logger.debug(`[TRANSLATE] Attempt ${u} failed with status ${f.status}: ${h}. Retrying...`);let y=sES(u,c.baseDelay,c.maxDelay);await new Promise(b=>setTimeout(b,y));continue}else return n.logger.debug(`[TRANSLATE] All ${c.maxRetries+1} attempts failed. Final error: ${h}`),e}let p=await f.json();return u>1&&n.logger.debug(`[TRANSLATE] Succeeded on attempt ${u} after ${u-1} retries`),await new Promise(h=>setTimeout(h,500)),p.translated_text??e}catch(f){if(d=f,f instanceof Error&&f.message.includes("403"))throw f;if(f instanceof Error&&!uES(f)){let _=f instanceof Error?f.message:String(f);return n.logger.debug(`[TRANSLATE] Non-retriable error: ${_}`),e}if(u>c.maxRetries){let _=f instanceof Error?f.message:String(f);return n.logger.debug(`[TRANSLATE] All ${c.maxRetries+1} attempts failed. Final error: ${_}`),e}let p=f instanceof Error?f.message:String(f);n.logger.debug(`[TRANSLATE] Attempt ${u} failed: ${p}. Retrying...`);let h=sES(u,c.baseDelay,c.maxDelay);await new Promise(_=>setTimeout(_,h))}let s=d instanceof Error?d.message:d?String(d):"Unknown error";return n.logger.debug(`[TRANSLATE] Unexpected end of retry loop. Last error: ${s}`),e}var sX5=new Set(["title","display-name","page","section","text","link","message","subtitle","search-text","system-prompt","summary","description","docs","tags","api"]);function cES(e,t){return typeof t!="string"||t==="string"||t.startsWith("./")?!1:!!sX5.has(e)}function hia({name:e}){let t=e.replace(/\.(md|mdx)$/i,"");return U0(t)}function cX5(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.page=="string"&&typeof t.path=="string"}function lX5(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.section=="string"&&Array.isArray(t.contents)}function fX5(e){return typeof e!="object"||e===null?!1:typeof e.api=="string"}function dX5(e){return typeof e!="object"||e===null?!1:typeof e.changelog=="string"}function pX5(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t["display-name"]=="string"||typeof t.displayName=="string"}function hX5(e){if(typeof e!="object"||e===null)return!1;let t=e;return(typeof t["display-name"]=="string"||typeof t.displayName=="string")&&typeof t.path=="string"}function _X5(e){if(typeof e!="object"||e===null)return;let t=e;if(typeof t.slug=="string")return t.slug;if(t["skip-slug"]!==!0){if(cX5(e))return hia({name:e.page});if(lX5(e))return hia({name:e.section});if(fX5(e)){let r=e["api-name"],i=e.api;return hia({name:typeof r=="string"?r:i})}if(dX5(e)){let r=e.title;if(typeof r=="string")return hia({name:r});let i=e.changelog;if(typeof i=="string"){let n=i.split("/").pop()||i;return hia({name:n})}}if(pX5(e)){let r=e["display-name"]||e.displayName;if(typeof r=="string")return hia({name:r})}if(hX5(e)){let r=e["display-name"]||e.displayName;if(typeof r=="string")return hia({name:r})}}}async function L4p({obj:e,language:t,sourceLanguage:r,filePath:i,cliContext:n,stub:a,sourceObj:o}){if(e==null||typeof e=="string")return e;if(Array.isArray(e)){let c=Array.isArray(o)?o:void 0;return await Promise.all(e.map((d,s)=>L4p({obj:d,language:t,sourceLanguage:r,filePath:i,cliContext:n,stub:a,sourceObj:c?.[s]})))}if(typeof e=="object"){let c={},d=typeof o=="object"&&o!==null?o:void 0,s;s=_X5(e);for(let[u,f]of Object.entries(e))if(u!=="slug")if(cES(u,f)){if(a){c[u]=f;continue}c[u]=await Vxo({text:f,language:t,sourceLanguage:r,cliContext:n})}else c[u]=await L4p({obj:f,language:t,sourceLanguage:r,filePath:i,cliContext:n,stub:a,sourceObj:d?.[u]});return s!==void 0&&(c.slug=s),c}return e}async function lES({yamlContent:e,language:t,sourceLanguage:r,filePath:i,cliContext:n,stub:a=!1}){if(t===r)return e;try{let o=ofa(e);if(!o)return e;let c=await L4p({obj:o,language:t,sourceLanguage:r,filePath:i,cliContext:n,stub:a,sourceObj:o});return VAn(c,{indent:2,lineWidth:-1,quotingType:'"',forceQuotes:!1})}catch(o){if(o instanceof Error&&o.message.includes("403"))throw o;return n.logger.error(` [ERROR] Failed to process YAML file ${i}: ${o}`),e}}async function Pgc({transformation:e,cliContext:t,stub:r=!1}){let{filePath:i,language:n,sourceLanguage:a,originalContent:o}=e;if(r&&!i.endsWith(".yml")&&!i.endsWith(".yaml"))return t.logger.debug(`[STUB] Returning content as-is for ${i} (stub mode enabled)`),o;t.logger.debug(`[PROCESSING] ${i} for language: ${n} (source: ${a})`);try{return(i.endsWith(".yml")||i.endsWith(".yaml"))&&!i.includes("generators.yml")?await lES({yamlContent:o,language:n,sourceLanguage:a,filePath:i,cliContext:t,stub:r}):i.endsWith(".md")||i.endsWith(".mdx")?Vxo({text:o,language:n,sourceLanguage:a,fileType:"MDX",cliContext:t}):i.endsWith(".json")&&!i.includes("fern.config.json")?Vxo({text:o,language:n,sourceLanguage:a,cliContext:t}):(t.logger.debug(`[SKIP] Skipping file "${i}" - unsupported file type for translation.`),o)}catch(c){if(c instanceof Error&&c.message.includes("403"))throw c;return o}}function fES(e){let t=[".png",".jpg",".jpeg",".gif",".svg",".webp",".ico",".bmp",".tiff",".tif",".woff",".woff2",".ttf",".otf",".eot",".pdf",".doc",".docx",".mp4",".webm",".ogg",".mp3",".wav",".zip",".tar",".gz",".bin"],r=e.toLowerCase();return t.some(i=>r.endsWith(i))}function dES(e,t){return e.endsWith(".yaml")||e.endsWith(".yml")?!0:e.endsWith(".md")||e.endsWith(".mdx")||e.endsWith(".json")&&!e.includes("fern.config.json")?!t:!1}var wgc=require("fs/promises");function jgc(e,t){try{let r=new URL(e),i=r.hostname,n=e.endsWith("/");if(i.includes(".docs.buildwithfern.com")){let o=i.split(".")[0];r.hostname=`${o}-${t}.docs.buildwithfern.com`,r.pathname=`/${t}${r.pathname}`}else r.hostname=`${t}.${i}`,r.pathname=`/${t}${r.pathname}`;let a=r.toString();return!n&&a.endsWith("/")&&r.pathname===`/${t}/`&&(a=a.slice(0,-1)),a}catch{let r=e.endsWith("/");if(e.includes("://")){let[i,n]=e.split("://"),[a,...o]=n?.split("#")??[],[c,...d]=a?.split("?")??[],[s,...u]=c?.split("/")??[];if(!s)return e;let f;s.includes(".docs.buildwithfern.com")?f=`${s.split(".")[0]}-${t}.docs.buildwithfern.com/${t}`:f=`${t}.${s}/${t}`;let p=`${i}://${f}`;return u.length>0?p+="/"+u.join("/"):r&&(p+="/"),d.length>0&&(p+="?"+d.join("?")),o.length>0&&(p+="#"+o.join("#")),p}else if(e.includes("/")){let i=e.split("/"),n=i[0],a=i.slice(1),o;return n?.includes(".docs.buildwithfern.com")?o=`${n.split(".")[0]}-${t}.docs.buildwithfern.com/${t}`:o=`${t}.${n}/${t}`,a.length>0||a.some(c=>c!=="")?`${o}/${a.join("/")}`:r?`${o}/`:o}else return e.includes(".docs.buildwithfern.com")?`${e.split(".")[0]}-${t}.docs.buildwithfern.com/${t}`:`${t}.${e}/${t}`}}function yX5(e,t){let r=bX5({docsConfig:e,language:t});return vX5({docsConfig:r,language:t})}function bX5({docsConfig:e,language:t}){let r=structuredClone(e);return r.settings?(r.settings.language=t,r.settings["search-text"]=pES[t]):r.settings={language:t,"search-text":pES[t]},r}var pES={en:"Search",es:"Buscar",fr:"Rechercher",de:"Suchen",it:"Cerca",pt:"Pesquisar",ja:"\u691C\u7D22",zh:"\u641C\u7D22",ko:"\uAC80\uC0C9",el:"\u0391\u03BD\u03B1\u03B6\u03AE\u03C4\u03B7\u03C3\u03B7",no:"S\xF8k",pl:"Szukaj",ru:"\u041F\u043E\u0438\u0441\u043A",sv:"S\xF6k",tr:"Ara"};function vX5({docsConfig:e,language:t}){let r=structuredClone(e);return r.instances&&Array.isArray(r.instances)&&(r.instances=r.instances.map(i=>{let n={...i};if(n.url&&(n.url=jgc(n.url,t)),n["custom-domain"]){let a=n["custom-domain"];typeof a=="string"?n["custom-domain"]=jgc(a,t):Array.isArray(a)&&(n["custom-domain"]=a.map(o=>jgc(o,t)))}return n})),r}async function hES({originalDocsConfigPath:e,targetDirectory:t,language:r,sourceLanguage:i,context:n,stub:a=!1}){try{let o=await(0,wgc.readFile)(e,"utf-8"),d=await Pgc({transformation:{filePath:G0,language:r,sourceLanguage:i,originalContent:o},cliContext:n,stub:a}),s=Mi.load(d),u=yX5(s,r),f=ut(t,me.of(G0)),p=Mi.dump(u,{sortKeys:!1});await(0,wgc.writeFile)(f,p,"utf-8"),n.logger.debug(`Created language-specific docs config: ${f}`)}catch(o){if(o instanceof Error&&o.message.includes("403"))throw o;n.logger.warn(`Failed to create language-specific docs config for ${r}: ${o}`)}}var _ES=require("fs"),yES=require("fs/promises"),bES=ce(require("path"),1);async function V4p(e,t){let r={},i=await(0,yES.readdir)(e);for(let n of i){if(n==="translations")continue;let a=bES.default.join(e,n),o=t?ut(t,me.of(n)):me.of(n),c=(0,_ES.statSync)(a);if(c.isDirectory()){let d=await V4p(a,o);for(let[s,u]of Object.entries(d))r[s]=u}else c.isFile()&&(r[a]=o)}return r}var vES=require("crypto"),gES=require("fs"),Wxo=require("fs/promises"),W4p=ce(require("path"),1);function OES(e){return(0,vES.createHash)("sha256").update(e,"utf-8").digest("hex")}async function mES(e){let t=W4p.default.join(e,"hashes");if(!(0,gES.existsSync)(t))return{};try{let r=await(0,Wxo.readFile)(t,"utf-8"),i=JSON.parse(r),{_comment:n,...a}=i;return a}catch{return{}}}async function x4p(e,t){let r=W4p.default.join(e,"hashes"),i={};Object.keys(t).sort().forEach(a=>{let o=t[a];o!==void 0&&(i[a]=o)});let n={_comment:"This file is auto-generated by Fern to track source file changes for translation purposes. Do not edit manually - it will be overwritten on the next translation update.",...i};await(0,Wxo.writeFile)(r,JSON.stringify(n,null,2),"utf-8")}async function Egc(e,t,r){try{let i=await(0,Wxo.readFile)(e,"utf-8"),n=OES(i),a=r[t];return n!==a}catch{return!0}}function gX5(e,t,r){let i=OES(r);e[t]=i}async function H4p(e,t,r,i){gX5(t,r,i),await x4p(e,t)}function AES(e,t){let r={};for(let[i,n]of Object.entries(e))t.has(i)&&(r[i]=n);return r}async function wES({project:e,cliContext:t,stub:r=!1}){let i=e.docsWorkspaces;if(i==null){t.logger.error("No docs workspace found. Please ensure you have a docs.yml file configured.");return}let n=i.config.languages;if(n==null||n.length===0){t.logger.error("No languages found in docs.yml configuration. Please add a 'languages' field with the desired languages.");return}await t.runTaskForWorkspace(i,async a=>{let o=i.absoluteFilePath,c=ut(o,me.of("translations")),d=n[0];if(!d)throw new Error("Unexpected error - first element of languages array is invalid");(0,P9a.existsSync)(c)||(a.logger.debug(`Creating translations directory at: ${c}`),await(0,C8t.mkdir)(c,{recursive:!0}));let s={},u=n.filter(y=>y!==d),f=ut(o,me.of(G0)),p=(0,P9a.existsSync)(f);for(let y of u){let b=ut(c,me.of(y),me.of("fern"));(0,P9a.existsSync)(b)||await(0,C8t.mkdir)(b,{recursive:!0}),s[y]={filesProcessed:0,filesSkipped:0}}s[d]={filesProcessed:0,filesSkipped:0};let h={filesProcessed:0,filesSkipped:0};try{let y=await mES(c),b=await V4p(o,""),v=Object.entries(b),O=new Set(Object.values(b)),m=AES(y,O);Object.keys(m).length!==Object.keys(y).length&&await x4p(c,m),y=m;let g=[];for(let[T,K]of v)p&&K===G0||dES(T,r)&&await Egc(T,K,y)&&g.push([T,K]);let A=!1;p&&(A=await Egc(f,me.of(G0),y));let j=g.length+(A?1:0),S=j*u.length,w=process.stdout.isTTY&&!jES.default&&S>0,E;w&&(E=new PES.default.SingleBar({format:"Processing files [{bar}] {percentage}% | {value}/{total} files",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,clearOnComplete:!1,stopOnComplete:!0}),E.start(S,0));let I=0,q=0;try{if(p)if(A){for(let G of u){I++,q++,w||a.logger.info(Ke.gray(`[${q}/${j+1}] Processing: ${G0} (docs config) for language: ${G}`)),t.logger.debug(`[PROCESSING] ${G0} (docs config) for language: ${G}`);let z=ut(c,me.of(G),me.of("fern"));await hES({originalDocsConfigPath:f,targetDirectory:z,language:G,sourceLanguage:d,context:t,stub:r});let W=s[G];E&&E.update(I),W&&W.filesProcessed++,t.logger.debug(`[COMPLETED] ${G0} -> ${G}/${G0}`)}let T=await(0,C8t.readFile)(f,"utf-8");await H4p(c,y,me.of(G0),T);let K=s[d];K&&K.filesProcessed++,t.logger.debug(`[HASH UPDATED] ${G0} -> ${d} (source language - hash updated)`)}else{for(let T of n){let K=s[T];K&&K.filesSkipped++}t.logger.debug(`[SKIPPED] ${G0} (no changes since last translation)`)}for(let[T,K]of v){if(p&&K===G0){t.logger.debug(`[SKIPPED] ${K} (already handled by docs config processing)`);continue}if(!await Egc(T,K,y)){for(let Oe of n){let Ae=s[Oe];Ae&&Ae.filesSkipped++}t.logger.debug(`[SKIPPED] ${K} (no changes since last translation)`);continue}t.logger.debug(`[PROCESSING] ${K} (detected changes)`);let z=await(0,C8t.readFile)(T,"utf-8");await H4p(c,y,K,z);let W=s[d];W&&W.filesProcessed++,t.logger.debug(`[HASH UPDATED] ${K} -> ${d} (source language - hash only)`);for(let Oe of u){q++,I++,w||a.logger.info(Ke.gray(`[${q}/${j}] Processing: ${K}`));let Ae=ut(c,me.of(Oe),me.of("fern")),L=ut(Ae,K),Q=G4p.default.dirname(L);(0,P9a.existsSync)(Q)||await(0,C8t.mkdir)(Q,{recursive:!0});let ae=await Pgc({transformation:{filePath:K,language:Oe,sourceLanguage:d,originalContent:z},cliContext:t,stub:r});await(0,C8t.writeFile)(L,ae,"utf-8");let de=s[Oe];de&&de.filesProcessed++,t.logger.debug(`[COMPLETED] ${K} -> ${Oe}/${K}`),E&&E.update(I)}}}finally{E&&(E.update(S),E.stop(),t.logger.info())}a.logger.info(Ke.cyan("Copying asset files..."));let R=0;for(let[T,K]of v)if(fES(T))for(let G of u){let z=ut(c,me.of(G),me.of("fern")),W=ut(z,K),Oe=G4p.default.dirname(W);(0,P9a.existsSync)(Oe)||await(0,C8t.mkdir)(Oe,{recursive:!0}),await(0,C8t.copyFile)(T,W),R++,t.logger.debug(`[ASSET COPIED] ${K} -> ${G}/${K}`)}R>0&&a.logger.info(Ke.green(`\u2713 Copied ${R} asset files to translation directories`));for(let T of n){let K=s[T];if(!K)continue;h.filesProcessed+=K.filesProcessed,h.filesSkipped+=K.filesSkipped;let G=K.filesProcessed+K.filesSkipped;T===d?(a.logger.info(Ke.blue(`${T} (source) hash tracking summary: ${K.filesProcessed} processed, ${K.filesSkipped} skipped (${G} total)`)),a.logger.info(Ke.green(`\u2713 Successfully tracked ${T} source language hashes (no directory created)`))):(a.logger.info(Ke.blue(`${T} translation summary: ${K.filesProcessed} processed, ${K.filesSkipped} skipped (${G} total)`)),a.logger.info(Ke.green(`\u2713 Successfully created ${T} translation with content processing`)))}}catch(y){throw y instanceof Error&&y.message.includes("403")||a.logger.error(`Failed to create translations: ${y}`),y}let _=h.filesProcessed+h.filesSkipped;if(a.logger.info(Ke.cyan(`Overall summary: ${h.filesProcessed} files processed, ${h.filesSkipped} files skipped across ${n.length} languages (${_} total operations)`)),a.logger.info(Ke.green(`Translations created successfully in: ${c}`)),u.length>0){a.logger.info("You can now modify the content in each language directory:");for(let y of u)a.logger.info(Ke.blue(` - ${y}: ${ut(c,me.of(y))}`))}if(a.logger.info(`Source language (${d}) values are tracked as hashes in translations/hashes`),p&&u.length>0){a.logger.info("Language-specific docs configurations created with modified instance URLs:");for(let y of u)a.logger.info(` - ${y}/docs.yml: URLs modified to include ${y} prefix`)}})}var Sgc=OX5();function OX5(){return typeof window<"u"&&typeof window.document<"u"?{type:"browser",version:window.navigator.userAgent}:typeof globalThis<"u"&&globalThis?.navigator?.userAgent==="Cloudflare-Workers"?{type:"workerd"}:typeof EdgeRuntime=="string"?{type:"edge-runtime"}:typeof self=="object"&&typeof self?.importScripts=="function"&&(self.constructor?.name==="DedicatedWorkerGlobalScope"||self.constructor?.name==="ServiceWorkerGlobalScope"||self.constructor?.name==="SharedWorkerGlobalScope")?{type:"web-worker"}:typeof Deno<"u"&&typeof Deno.version<"u"&&typeof Deno.version.deno<"u"?{type:"deno",version:Deno.version.deno}:typeof Bun<"u"&&typeof Bun.version<"u"?{type:"bun",version:Bun.version}:typeof process<"u"&&"version"in process&&!!process.version&&"versions"in process&&!!process.versions?.node?{type:"node",version:process.versions.node,parsedVersion:Number(process.versions.node.split(".")[0])}:typeof navigator<"u"&&navigator?.product==="ReactNative"?{type:"react-native"}:{type:"unknown"}}IcH();var DcH="The Fern CLI requires Node 18+ or above.";async function IcH(){let e=process.argv.includes("--local"),t=new S_c(process.stdout,process.stderr,{isLocal:e}),r=async()=>{await t.exit()};if(Sgc.type==="node"&&Sgc.parsedVersion!=null&&Sgc.parsedVersion>=18){let{setGlobalDispatcher:i,Agent:n}=await Promise.resolve().then(()=>ce(f8p(),1));i(new n({connect:{timeout:2147483647},bodyTimeout:0,headersTimeout:2147483647}))}if(process.env.HTTP_PROXY!=null){let{setGlobalDispatcher:i,ProxyAgent:n}=await Promise.resolve().then(()=>ce(f8p(),1)),a=new n(process.env.HTTP_PROXY);i(a)}process.on("SIGINT",async()=>{t.suppressUpgradeMessage(),await r()});try{let i=process.env[Fxo];i!=null&&process.chdir(i);let n=await CcH(t);t.environment.packageVersion===n?await BcH(t):await Uxo({version:n,cliContext:t})}catch(i){await t.instrumentPostHogEvent({command:process.argv.join(" "),properties:{failed:!0,error:i}}),i?.message.includes("globalThis")?(t.logger.error(DcH),t.failWithoutThrowing()):i instanceof gS?t.failWithoutThrowing():i instanceof aWi?t.logger.error(`Failed. ${i.log}`):t.failWithoutThrowing("Failed.",i)}await r()}async function BcH(e){let t=Jia(process.argv);if(t[0]==="completion"){sNp(t).scriptName(e.environment.cliName).completion("completion","Generate shell completion script").parse();return}let r=sNp(t).scriptName(e.environment.cliName).version(!1).completion("completion","Generate shell completion script").fail((i,n,a)=>{n==null&&(a.showHelp(),e.logger.error(i))}).strict().exitProcess(!1).command("$0",!1,i=>i.option("version",{describe:"Print current version",alias:"v"}).version(!1),i=>{i.version!=null?e.logger.info(e.environment.packageVersion):(r.showHelp(),e.failAndThrow())}).option("log-level",{default:Kn.Info,choices:P3}).demandCommand().recommendCommands();RcH(r,e),zcH(r,e),TcH(r,e),NcH(r,e),FcH(r,e),QcH(r,e),UcH(r,e),WcH(r,e),LcH(r,e),VcH(r,e),GcH(r,e),xcH(r,e),HcH(r,e),XcH(r,e),ZcH(r,e),kcH(r,e),olH(r,e),ulH(r,e),tlH(r,e),rlH(r,e),alH(r,e),elH(r,e),JcH(r,e),YcH(r,e),KcH({cli:r,cliContext:e,onRun:()=>{e.suppressUpgradeMessage()}}),$cH(r,e),hlH(r,e),_lH(r,e),ylH(r,e),blH(r,e),vlH(r,e),gsS(r,e),OsS(r,e),glH(r,e),r.middleware(async i=>{e.setLogLevel(i["log-level"]),e.logFernVersionDebug()}),await r.parse()}async function CcH(e){if(process.env.FERN_NO_VERSION_REDIRECTION==="true")return e.environment.packageVersion;let t=await JM();if(t!=null){let r=await e.runTask(i=>aAe({directory:t,context:i}));return r.version==="*"?e.environment.packageVersion:r.version}return Kbn({cliEnvironment:e.environment})}async function qcH(e){let t=await JM();if(t!=null)return(await e.runTask(i=>aAe({directory:t,context:i}))).organization}function TcH(e,t){e.command("init","Initialize a Fern API",r=>r.option("api",{boolean:!0,description:"Initialize an api."}).option("docs",{boolean:!0,description:"Initialize a docs website."}).option("organization",{alias:"org",type:"string",description:"Organization name"}).option("openapi",{type:"string",description:"Filepath or url to an existing OpenAPI spec"}).option("mintlify",{type:"string",description:"Migrate docs from Mintlify provided a path to a mint.json file"}).option("readme",{type:"string",description:"Migrate docs from Readme provided a URL to a Readme generated docs site"}),async r=>{if(r.organization==null){let i=await qcH(t);i!=null?r.organization=i:r.organization=await t.getInput({message:"Please enter your organization"})}if(r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.");if(r.readme!=null&&r.mintlify!=null)return t.failWithoutThrowing("Cannot specify both --readme and --mintlify. Please choose one.");if(r.readme!=null)await t.runTask(async i=>{await jzp({readmeUrl:r.readme,organization:r.organization??"fern",taskContext:i,versionOfCli:await Kbn({cliEnvironment:t.environment})})});else if(r.docs!=null)await t.runTask(async i=>{await $Sp({organization:r.organization,versionOfCli:await Kbn({cliEnvironment:t.environment}),taskContext:i})});else if(r.mintlify!=null)await t.runTask(async i=>{await kSp({pathToMintJson:r.mintlify,organization:r.organization??"fern",taskContext:i,versionOfCli:await Kbn({cliEnvironment:t.environment})})});else{let i;if(r.openapi!=null){if(pmn(r.openapi)){let a=await juS({url:r.openapi,logger:t.logger});a.status==="failure"&&t.failAndThrow(a.errorMessage);let o=a.filePath;i=vr.of(o)}else i=vr.of(xo(AO(),r.openapi));await ii(i)||t.failAndThrow(`${i} does not exist`)}await t.runTask(async n=>{await GSp({organization:r.organization,versionOfCli:await Kbn({cliEnvironment:t.environment}),context:n,openApiPath:i})})}})}function RcH(e,t){e.command("diff","Diff two versions of an API",r=>r.option("from",{string:!0,demandOption:!0,description:"The previous version of the API"}).option("to",{string:!0,demandOption:!0,description:"The next version of the API"}).option("from-version",{string:!0,description:"The previous version of the API (e.g. 1.1.0)"}).option("from-generator-version",{string:!0,description:"The previous version of the generator (e.g. 1.1.0)"}).option("to-generator-version",{string:!0,description:"The next version of the generator (e.g. 1.1.0)"}).option("quiet",{boolean:!0,default:!1,alias:"q",description:"Whether to suppress output written to stderr"}).middleware(i=>{if(!hzc(i.fromGeneratorVersion,i.toGeneratorVersion))throw new Error("Both --from-generator-version and --to-generator-version must be provided together, or neither should be provided")}),async r=>{let i=dzc(r.fromVersion),n=pzc({from:r.fromGeneratorVersion,to:r.toGeneratorVersion}),a=await EsS({context:t,from:r.from,to:r.to,fromVersion:i,generatorVersions:n});if(i!=null){let{errors:c,...d}=a;t.logger.info(JSON.stringify(d))}!r.quiet&&a.errors.length>0&&t.stderr.info(a.errors.join(`
|
|
2648
2648
|
`));let o=a.bump==="major"?1:0;await t.exit({code:o})})}function zcH(e,t){e.command("sdk-diff <from-dir> <to-dir>",!1,r=>r.positional("from-dir",{type:"string",demandOption:!0,description:"Path to the directory containing the previous version of the SDK"}).positional("to-dir",{type:"string",demandOption:!0,description:"Path to the directory containing the next version of the SDK"}).option("json",{boolean:!0,default:!1,description:"Output result as JSON"}),async r=>{await t.instrumentPostHogEvent({command:"fern sdk-diff"});let i=await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),n=await kOS({context:t,project:i,fromDir:r.fromDir,toDir:r.toDir});r.json?t.logger.info(JSON.stringify(n,null,2)):(t.logger.info(`
|
|
2649
2649
|
`+n.message),t.logger.info(`
|
|
2650
|
-
Version Bump: ${n.version_bump}`))})}function NcH(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async i=>{await imS({orgId:r.organization??(await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:i})})})}function FcH(e,t){e.command("add <generator>",`Add a code generator to ${GM}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{await AsS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:r.generator,groupName:r.group,cliContext:t})})}function QcH(e,t){e.command(["generate"],"Generate all generators in the specified group",r=>r.option("api",{string:!0,description:"If multiple APIs, specify the name with --api <name>. Otherwise, just --api."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("group",{type:"string",description:"The group to generate"}).option("mode",{choices:Object.values(bOS),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally, using Docker"}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}).option("force",{boolean:!0,default:!1,description:"Ignore prompts to confirm generation, defaults to false"}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("disable-snippets",{boolean:!0,description:"Disable snippets in docs generation.",default:!1}).option("runner",{choices:["docker","podman"],description:"Choose the container runtime to use for local generation.",default:void 0}).option("lfs-override",{type:"string",hidden:!0,description:"Override output mode to local-file-system with the specified path"}).option("disable-dynamic-snippets",{boolean:!0,description:"Disable dynamic SDK snippets in docs generation",default:!1}).option("prompt",{boolean:!0,description:"Prompt for confirmation before generating (use --no-prompt to skip)",default:!0}).option("skip-upload",{boolean:!0,description:"Skip asset upload step and generate fake links for preview",default:!1}).option("fernignore",{type:"string",description:"Path to a custom .fernignore file to use instead of the one on the main branch (remote generation only)"}).option("dynamic-ir-only",{boolean:!0,description:"Only upload dynamic IR for specified version, skip SDK generation (remote generation only)",default:!1}).option("output",{type:"string",description:"Custom output directory (currently only supported with --preview for SDK generation)"}),async r=>r.api!=null&&r.docs!=null?t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one."):r.skipUpload&&!r.preview?t.failWithoutThrowing("The --skip-upload flag can only be used with --preview."):r.skipUpload&&r.docs==null?t.failWithoutThrowing("The --skip-upload flag can only be used with --docs."):r.fernignore!=null&&(r.local||r.runner!=null)?t.failWithoutThrowing("The --fernignore flag is not supported with local generation (--local or --runner). It can only be used with remote generation."):r["dynamic-ir-only"]&&(r.local||r.runner!=null)?t.failWithoutThrowing("The --dynamic-ir-only flag is not supported with local generation (--local or --runner). It can only be used with remote generation."):r["dynamic-ir-only"]&&r.version==null?t.failWithoutThrowing("The --dynamic-ir-only flag requires a version to be specified with --version."):r["dynamic-ir-only"]&&r.docs!=null?t.failWithoutThrowing("The --dynamic-ir-only flag can only be used for API generation, not docs generation."):r.output!=null&&!r.preview?t.failWithoutThrowing("The --output flag currently only works with --preview."):r.output!=null&&r.docs!=null?t.failWithoutThrowing("The --output flag is not supported for docs generation."):r.api!=null?await DLp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local||r.runner!=null,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,dynamicIrOnly:r["dynamic-ir-only"],outputDir:r.output}):r.docs!=null?(r.group!=null&&t.logger.warn("--group is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await gOS({project:await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview,brokenLinks:r.brokenLinks,strictBrokenLinks:r.strictBrokenLinks,disableTemplates:r.disableSnippets,noPrompt:!r.prompt,skipUpload:r.skipUpload})):await DLp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,dynamicIrOnly:r["dynamic-ir-only"],outputDir:r.output}))}function UcH(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Ki.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}).option("disable-examples",{boolean:!0,description:"Whether to disable automatic example generation in the IR",default:!1}),async r=>{await wOS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:xo(AO(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,readme:void 0,directFromOpenapi:r.fromOpenapi,disableExamples:r.disableExamples})})}function LcH(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(Ki.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await MOS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:xo(AO(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function VcH(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Ki.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("disable-examples",{boolean:!0,description:"Whether to suppress examples from being included in the IR"}),async r=>{await mOS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:xo(AO(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,disableDynamicExamples:r.disableExamples??!1})})}function WcH(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the FDR API definition for certain audiences"}).option("v2",{boolean:!0,description:"Use v2 format"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{r.v2?await ILp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:xo(AO(),r.pathToOutput),directFromOpenapi:!1,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):r.fromOpenapi?await ILp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:xo(AO(),r.pathToOutput),directFromOpenapi:!0,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):await POS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:xo(AO(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function xcH(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>tU(a));await JOS({project:i,cliContext:t,token:n,version:r.version})})}function HcH(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>tU(a));await YOS({project:i,cliContext:t,token:n})})}function GcH(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("local",{boolean:!0,description:"Run validation locally without sending data to Fern API.",default:!1}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{await rES({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,logWarnings:r.warnings,brokenLinks:r.brokenLinks,errorOnBrokenLinks:r.strictBrokenLinks,directFromOpenapi:r.fromOpenapi})})}function KcH({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades Fern CLI version in ${NC}`,i=>i.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}).option("to",{string:!0,hidden:!0}).option("from",{string:!0,description:"The version to migrate from. Use this to manually run migrations when upgrading from an older CLI version."}).option("from-git",{boolean:!0,hidden:!0}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to migration prompts."}),async i=>{await X0S({cliContext:t,includePreReleases:i.rc,targetVersion:i.to??i.version,fromVersion:i.from,fromGit:i["from-git"],yes:i.yes}),r()})}function $cH(e,t){e.command("downgrade <version>",`Downgrades Fern CLI version in ${NC}`,r=>r.positional("version",{type:"string",description:"The version to downgrade to",demandOption:!0}),async r=>{await UgS({cliContext:t,targetVersion:r.version})})}function JcH(e,t){e.command("api update",`Pulls the latest OpenAPI spec from the specified origin in ${GM} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{await t.instrumentPostHogEvent({command:"fern api update"}),await umS({cliContext:t,project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),indent:r.indent})})}function YcH(e,t){e.command("self-update [version]","Updates the globally installed Fern CLI to the latest version or the specified version",r=>r.positional("version",{type:"string",description:"The version to update to (e.g., 0.85.0, 10). Defaults to latest."}).option("dry-run",{type:"boolean",description:"Show what would be executed without actually running the update",default:!1}),async r=>{await t.instrumentPostHogEvent({command:"fern self-update"}),await tmS({cliContext:t,version:r.version,dryRun:r.dryRun})})}function XcH(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}),async r=>{await t.runTask(async i=>{await t.instrumentPostHogEvent({command:"fern login"}),await bka(i,{useDeviceCodeFlow:r.deviceCode})})})}function ZcH(e,t){e.command("logout","Log out of Fern",r=>r,async()=>{await t.runTask(async r=>{await t.instrumentPostHogEvent({command:"fern logout"}),await Txc(r)})})}function kcH(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern format"}),await JgS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function elH(e,t){e.command("test",!1,r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(Ki.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{await t.instrumentPostHogEvent({command:"fern test"}),await rmS({cliContext:t,project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function tlH(e,t){e.command("mock",!1,r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{await t.instrumentPostHogEvent({command:"fern mock"}),await xOS({cliContext:t,project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function rlH(e,t){e.command("overrides","Commands for managing OpenAPI overrides",r=>(ilH(r,t),nlH(r,t),r))}function ilH(e,t){e.command("compare <original> <modified>","Compare two OpenAPI specs and generate an overrides file from the differences.",r=>r.positional("original",{type:"string",description:"Path to the original OpenAPI spec",demandOption:!0}).positional("modified",{type:"string",description:"Path to the modified OpenAPI spec",demandOption:!0}).option("output",{type:"string",alias:"o",description:"Path to write the overrides file (defaults to <original>-overrides.yml)"}),async r=>{await t.instrumentPostHogEvent({command:"fern overrides compare"});let i=xo(AO(),r.original),n=xo(AO(),r.modified),a=r.output!=null?xo(AO(),r.output):void 0;await IOS({originalPath:vr.of(i),modifiedPath:vr.of(n),outputPath:a!=null?vr.of(a):void 0,cliContext:t})})}function nlH(e,t){e.command("write","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{await t.instrumentPostHogEvent({command:"fern overrides write"}),await CLp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function alH(e,t){e.command("write-overrides",!1,r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{t.logger.warn("The 'write-overrides' command is deprecated. Use 'fern overrides write' instead."),await t.instrumentPostHogEvent({command:"fern write-overrides"}),await CLp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function olH(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(Ki.GenerationLanguage),description:"Write the definition for a particular SDK language"}).option("preserve-schemas",{string:!0,description:"Preserve potentially unsafe schema Ids in the generated fern definition"}),async r=>{let i=r.preserveSchemas!=null;await t.instrumentPostHogEvent({command:"fern write-definition"}),await iES({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language,preserveSchemaIds:i}),cliContext:t,sdkLanguage:r.language,preserveSchemaIds:i})})}function ulH(e,t){e.command("docs","Commands for managing your docs",r=>(dlH(r,t),plH(r,t),clH(r,t),slH(r,t),r))}function slH(e,t){e.command("diff <preview-url> <files..>","Generate visual diffs between preview and production docs pages",r=>r.positional("preview-url",{type:"string",description:"The preview deployment URL (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}).positional("files",{type:"string",array:!0,description:"File paths to generate diffs for (e.g. fern/pages/intro.mdx)",demandOption:!0}).option("output",{type:"string",default:".fern/diff",description:"Output directory for diff images"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs diff"});let i=await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),n=await jgS({cliContext:t,project:i,previewUrl:r.previewUrl,files:r.files??[],outputDir:r.output});t.logger.info(JSON.stringify(n,null,2))})}function clH(e,t){e.command("preview","Commands for managing preview deployments",r=>(llH(r,t),flH(r,t),r))}function llH(e,t){e.command("list","List all preview deployments",r=>r.option("limit",{type:"number",description:"Maximum number of preview deployments to display"}).option("page",{type:"number",description:"Page number for pagination (starts at 1)"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview list"}),await EgS({cliContext:t,limit:r.limit,page:r.page})})}function flH(e,t){e.command("delete <url>","Delete a preview deployment",r=>r.positional("url",{type:"string",description:"The FQDN of the preview deployment to delete (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview delete"}),await wgS({cliContext:t,previewUrl:r.url})})}function dlH(e,t){e.command("dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}).option("broken-links",{boolean:!0,default:!1,description:"Check for broken links in your docs"}).option("beta",{boolean:!0,default:!1,description:"Run the app router development server"}).option("legacy",{boolean:!0,default:!1,description:"Run the legacy development server"}).option("backend-port",{number:!0,description:"Run the development backend server on the following port"}).option("force-download",{boolean:!0,default:!1,description:"Force re-download of the docs preview bundle by deleting the cached bundle"}),async r=>{r.beta&&t.logger.warn("--beta flag now accesses the same functionality as default and will be deprecated in a future release");let i;r.port!=null?i=r.port:i=await pGa({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]});let n;r.backendPort!=null?n=r.backendPort:n=await pGa({port:[3001,3002,3003,3004,3005,3006,3007,3008,3009,3010,3011]});let a=r.bundlePath;await wvS({loadProject:()=>Em(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:i,bundlePath:a,brokenLinks:r.brokenLinks,legacyPreview:r.legacy,backendPort:n,forceDownload:r.forceDownload})})}function plH(e,t){e.command("broken-links","Check for broken links in your docs",r=>r.option("strict",{boolean:!0,default:!1,description:"Fail with non-zero exit status"}),async r=>{let i=await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await Z0S({project:i,cliContext:t,errorOnBrokenLinks:r.strict})})}function hlH(e,t){e.command("jsonschema <path-to-output>","Generate JSON Schema for a specific type",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).positional("path-to-output",{type:"string",description:"Path to write JSON Schema",demandOption:!0}).option("type",{string:!0,demandOption:!0,description:"The type to generate JSON Schema for (e.g. 'MySchema' or 'mypackage.MySchema')"}),async r=>{await t.instrumentPostHogEvent({command:"fern jsonschema",properties:{output:r.output}}),await FOS({typeLocator:r.type,project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),jsonschemaFilepath:xo(AO(),r.pathToOutput),cliContext:t})})}function _lH(e,t){e.command("write-docs-definition <output-path>",!1,r=>r.positional("output-path",{type:"string",description:"Path to write the docs definition",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern write-docs-definition",properties:{outputPath:r.outputPath}}),await oES({project:await Em(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),outputPath:xo(AO(),r.outputPath),cliContext:t})})}function ylH(e,t){e.command("write-translation","Generate translation directories for each language defined in docs.yml",r=>r.option("stub",{alias:"s",type:"boolean",default:!1,description:"Return content as-is without calling the translation service"}),async r=>{await t.instrumentPostHogEvent({command:"fern write-translation"}),await wES({project:await Em(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,stub:r.stub})})}function blH(e,t){e.command("export <output-path>","Export your API to an OpenAPI spec",r=>r.positional("output-path",{type:"string",description:"Path to write the OpenAPI spec",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{await t.instrumentPostHogEvent({command:"fern export",properties:{outputPath:r.outputPath}}),await $gS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,outputPath:xo(AO(),r.outputPath),indent:r.indent})})}function vlH(e,t){e.command("beta",!1,r=>r.help(!1).version(!1).strict(!1).parserConfiguration({"unknown-options-as-args":!0}),async r=>{try{let i=r._.slice(1).map(String);await ISp(i)}catch(i){t.logger.error("CLI v2 failed:",String(i)),t.failWithoutThrowing()}})}function glH(e,t){e.command("protoc-gen-fern",!1,r=>{},async()=>{let r=Ezp,i=await OlH(process.stdin),n=I7a(Uxp,i),a=r.run(n);await mlH(process.stdout,tAc(pHo,a)),process.exit(0)})}function OlH(e){return new Promise((t,r)=>{let i=[];e.on("data",n=>i.push(n)),e.on("end",()=>{t(new Uint8Array(Buffer.concat(i)))}),e.on("error",n=>{r(n)})})}function mlH(e,t){return new Promise((r,i)=>{e.write(t,n=>{n?i(n):r()})})}
|
|
2650
|
+
Version Bump: ${n.version_bump}`))})}function NcH(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async i=>{await imS({orgId:r.organization??(await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:i})})})}function FcH(e,t){e.command("add <generator>",`Add a code generator to ${GM}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{await AsS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:r.generator,groupName:r.group,cliContext:t})})}function QcH(e,t){e.command(["generate"],"Generate all generators in the specified group",r=>r.option("api",{string:!0,description:"If multiple APIs, specify the name with --api <name>. Otherwise, just --api."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("group",{type:"string",description:"The group to generate"}).option("generator",{type:"string",description:"The name of a specific generator to run"}).option("mode",{choices:Object.values(bOS),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally, using Docker"}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}).option("force",{boolean:!0,default:!1,description:"Ignore prompts to confirm generation, defaults to false"}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("disable-snippets",{boolean:!0,description:"Disable snippets in docs generation.",default:!1}).option("runner",{choices:["docker","podman"],description:"Choose the container runtime to use for local generation.",default:void 0}).option("lfs-override",{type:"string",hidden:!0,description:"Override output mode to local-file-system with the specified path"}).option("disable-dynamic-snippets",{boolean:!0,description:"Disable dynamic SDK snippets in docs generation",default:!1}).option("prompt",{boolean:!0,description:"Prompt for confirmation before generating (use --no-prompt to skip)",default:!0}).option("skip-upload",{boolean:!0,description:"Skip asset upload step and generate fake links for preview",default:!1}).option("fernignore",{type:"string",description:"Path to a custom .fernignore file to use instead of the one on the main branch (remote generation only)"}).option("dynamic-ir-only",{boolean:!0,description:"Only upload dynamic IR for specified version, skip SDK generation (remote generation only)",default:!1}).option("output",{type:"string",description:"Custom output directory (currently only supported with --preview for SDK generation)"}),async r=>r.api!=null&&r.docs!=null?t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one."):r.skipUpload&&!r.preview?t.failWithoutThrowing("The --skip-upload flag can only be used with --preview."):r.skipUpload&&r.docs==null?t.failWithoutThrowing("The --skip-upload flag can only be used with --docs."):r.fernignore!=null&&(r.local||r.runner!=null)?t.failWithoutThrowing("The --fernignore flag is not supported with local generation (--local or --runner). It can only be used with remote generation."):r["dynamic-ir-only"]&&(r.local||r.runner!=null)?t.failWithoutThrowing("The --dynamic-ir-only flag is not supported with local generation (--local or --runner). It can only be used with remote generation."):r["dynamic-ir-only"]&&r.version==null?t.failWithoutThrowing("The --dynamic-ir-only flag requires a version to be specified with --version."):r["dynamic-ir-only"]&&r.docs!=null?t.failWithoutThrowing("The --dynamic-ir-only flag can only be used for API generation, not docs generation."):r.output!=null&&!r.preview?t.failWithoutThrowing("The --output flag currently only works with --preview."):r.output!=null&&r.docs!=null?t.failWithoutThrowing("The --output flag is not supported for docs generation."):r.api!=null?await DLp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,generatorName:r.generator,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local||r.runner!=null,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,dynamicIrOnly:r["dynamic-ir-only"],outputDir:r.output}):r.docs!=null?(r.group!=null&&t.logger.warn("--group is ignored when generating docs"),r.generator!=null&&t.logger.warn("--generator is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await gOS({project:await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview,brokenLinks:r.brokenLinks,strictBrokenLinks:r.strictBrokenLinks,disableTemplates:r.disableSnippets,noPrompt:!r.prompt,skipUpload:r.skipUpload})):await DLp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,generatorName:r.generator,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,fernignorePath:r.fernignore,dynamicIrOnly:r["dynamic-ir-only"],outputDir:r.output}))}function UcH(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Ki.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}).option("disable-examples",{boolean:!0,description:"Whether to disable automatic example generation in the IR",default:!1}),async r=>{await wOS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:xo(AO(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,readme:void 0,directFromOpenapi:r.fromOpenapi,disableExamples:r.disableExamples})})}function LcH(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(Ki.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await MOS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:xo(AO(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function VcH(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Ki.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("disable-examples",{boolean:!0,description:"Whether to suppress examples from being included in the IR"}),async r=>{await mOS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:xo(AO(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,disableDynamicExamples:r.disableExamples??!1})})}function WcH(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the FDR API definition for certain audiences"}).option("v2",{boolean:!0,description:"Use v2 format"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{r.v2?await ILp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:xo(AO(),r.pathToOutput),directFromOpenapi:!1,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):r.fromOpenapi?await ILp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:xo(AO(),r.pathToOutput),directFromOpenapi:!0,cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):await POS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:xo(AO(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function xcH(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>tU(a));await JOS({project:i,cliContext:t,token:n,version:r.version})})}function HcH(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>tU(a));await YOS({project:i,cliContext:t,token:n})})}function GcH(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("local",{boolean:!0,description:"Run validation locally without sending data to Fern API.",default:!1}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{await rES({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,logWarnings:r.warnings,brokenLinks:r.brokenLinks,errorOnBrokenLinks:r.strictBrokenLinks,directFromOpenapi:r.fromOpenapi})})}function KcH({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades Fern CLI version in ${NC}`,i=>i.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}).option("to",{string:!0,hidden:!0}).option("from",{string:!0,description:"The version to migrate from. Use this to manually run migrations when upgrading from an older CLI version."}).option("from-git",{boolean:!0,hidden:!0}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to migration prompts."}),async i=>{await X0S({cliContext:t,includePreReleases:i.rc,targetVersion:i.to??i.version,fromVersion:i.from,fromGit:i["from-git"],yes:i.yes}),r()})}function $cH(e,t){e.command("downgrade <version>",`Downgrades Fern CLI version in ${NC}`,r=>r.positional("version",{type:"string",description:"The version to downgrade to",demandOption:!0}),async r=>{await UgS({cliContext:t,targetVersion:r.version})})}function JcH(e,t){e.command("api update",`Pulls the latest OpenAPI spec from the specified origin in ${GM} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{await t.instrumentPostHogEvent({command:"fern api update"}),await umS({cliContext:t,project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),indent:r.indent})})}function YcH(e,t){e.command("self-update [version]","Updates the globally installed Fern CLI to the latest version or the specified version",r=>r.positional("version",{type:"string",description:"The version to update to (e.g., 0.85.0, 10). Defaults to latest."}).option("dry-run",{type:"boolean",description:"Show what would be executed without actually running the update",default:!1}),async r=>{await t.instrumentPostHogEvent({command:"fern self-update"}),await tmS({cliContext:t,version:r.version,dryRun:r.dryRun})})}function XcH(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}),async r=>{await t.runTask(async i=>{await t.instrumentPostHogEvent({command:"fern login"}),await bka(i,{useDeviceCodeFlow:r.deviceCode})})})}function ZcH(e,t){e.command("logout","Log out of Fern",r=>r,async()=>{await t.runTask(async r=>{await t.instrumentPostHogEvent({command:"fern logout"}),await Txc(r)})})}function kcH(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern format"}),await JgS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function elH(e,t){e.command("test",!1,r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(Ki.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{await t.instrumentPostHogEvent({command:"fern test"}),await rmS({cliContext:t,project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function tlH(e,t){e.command("mock",!1,r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{await t.instrumentPostHogEvent({command:"fern mock"}),await xOS({cliContext:t,project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function rlH(e,t){e.command("overrides","Commands for managing OpenAPI overrides",r=>(ilH(r,t),nlH(r,t),r))}function ilH(e,t){e.command("compare <original> <modified>","Compare two OpenAPI specs and generate an overrides file from the differences.",r=>r.positional("original",{type:"string",description:"Path to the original OpenAPI spec",demandOption:!0}).positional("modified",{type:"string",description:"Path to the modified OpenAPI spec",demandOption:!0}).option("output",{type:"string",alias:"o",description:"Path to write the overrides file (defaults to <original>-overrides.yml)"}),async r=>{await t.instrumentPostHogEvent({command:"fern overrides compare"});let i=xo(AO(),r.original),n=xo(AO(),r.modified),a=r.output!=null?xo(AO(),r.output):void 0;await IOS({originalPath:vr.of(i),modifiedPath:vr.of(n),outputPath:a!=null?vr.of(a):void 0,cliContext:t})})}function nlH(e,t){e.command("write","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{await t.instrumentPostHogEvent({command:"fern overrides write"}),await CLp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function alH(e,t){e.command("write-overrides",!1,r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{t.logger.warn("The 'write-overrides' command is deprecated. Use 'fern overrides write' instead."),await t.instrumentPostHogEvent({command:"fern write-overrides"}),await CLp({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function olH(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(Ki.GenerationLanguage),description:"Write the definition for a particular SDK language"}).option("preserve-schemas",{string:!0,description:"Preserve potentially unsafe schema Ids in the generated fern definition"}),async r=>{let i=r.preserveSchemas!=null;await t.instrumentPostHogEvent({command:"fern write-definition"}),await iES({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language,preserveSchemaIds:i}),cliContext:t,sdkLanguage:r.language,preserveSchemaIds:i})})}function ulH(e,t){e.command("docs","Commands for managing your docs",r=>(dlH(r,t),plH(r,t),clH(r,t),slH(r,t),r))}function slH(e,t){e.command("diff <preview-url> <files..>","Generate visual diffs between preview and production docs pages",r=>r.positional("preview-url",{type:"string",description:"The preview deployment URL (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}).positional("files",{type:"string",array:!0,description:"File paths to generate diffs for (e.g. fern/pages/intro.mdx)",demandOption:!0}).option("output",{type:"string",default:".fern/diff",description:"Output directory for diff images"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs diff"});let i=await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),n=await jgS({cliContext:t,project:i,previewUrl:r.previewUrl,files:r.files??[],outputDir:r.output});t.logger.info(JSON.stringify(n,null,2))})}function clH(e,t){e.command("preview","Commands for managing preview deployments",r=>(llH(r,t),flH(r,t),r))}function llH(e,t){e.command("list","List all preview deployments",r=>r.option("limit",{type:"number",description:"Maximum number of preview deployments to display"}).option("page",{type:"number",description:"Page number for pagination (starts at 1)"}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview list"}),await EgS({cliContext:t,limit:r.limit,page:r.page})})}function flH(e,t){e.command("delete <url>","Delete a preview deployment",r=>r.positional("url",{type:"string",description:"The FQDN of the preview deployment to delete (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern docs preview delete"}),await wgS({cliContext:t,previewUrl:r.url})})}function dlH(e,t){e.command("dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}).option("broken-links",{boolean:!0,default:!1,description:"Check for broken links in your docs"}).option("beta",{boolean:!0,default:!1,description:"Run the app router development server"}).option("legacy",{boolean:!0,default:!1,description:"Run the legacy development server"}).option("backend-port",{number:!0,description:"Run the development backend server on the following port"}).option("force-download",{boolean:!0,default:!1,description:"Force re-download of the docs preview bundle by deleting the cached bundle"}),async r=>{r.beta&&t.logger.warn("--beta flag now accesses the same functionality as default and will be deprecated in a future release");let i;r.port!=null?i=r.port:i=await pGa({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]});let n;r.backendPort!=null?n=r.backendPort:n=await pGa({port:[3001,3002,3003,3004,3005,3006,3007,3008,3009,3010,3011]});let a=r.bundlePath;await wvS({loadProject:()=>Em(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:i,bundlePath:a,brokenLinks:r.brokenLinks,legacyPreview:r.legacy,backendPort:n,forceDownload:r.forceDownload})})}function plH(e,t){e.command("broken-links","Check for broken links in your docs",r=>r.option("strict",{boolean:!0,default:!1,description:"Fail with non-zero exit status"}),async r=>{let i=await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await Z0S({project:i,cliContext:t,errorOnBrokenLinks:r.strict})})}function hlH(e,t){e.command("jsonschema <path-to-output>","Generate JSON Schema for a specific type",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).positional("path-to-output",{type:"string",description:"Path to write JSON Schema",demandOption:!0}).option("type",{string:!0,demandOption:!0,description:"The type to generate JSON Schema for (e.g. 'MySchema' or 'mypackage.MySchema')"}),async r=>{await t.instrumentPostHogEvent({command:"fern jsonschema",properties:{output:r.output}}),await FOS({typeLocator:r.type,project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),jsonschemaFilepath:xo(AO(),r.pathToOutput),cliContext:t})})}function _lH(e,t){e.command("write-docs-definition <output-path>",!1,r=>r.positional("output-path",{type:"string",description:"Path to write the docs definition",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern write-docs-definition",properties:{outputPath:r.outputPath}}),await oES({project:await Em(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),outputPath:xo(AO(),r.outputPath),cliContext:t})})}function ylH(e,t){e.command("write-translation","Generate translation directories for each language defined in docs.yml",r=>r.option("stub",{alias:"s",type:"boolean",default:!1,description:"Return content as-is without calling the translation service"}),async r=>{await t.instrumentPostHogEvent({command:"fern write-translation"}),await wES({project:await Em(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,stub:r.stub})})}function blH(e,t){e.command("export <output-path>","Export your API to an OpenAPI spec",r=>r.positional("output-path",{type:"string",description:"Path to write the OpenAPI spec",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{await t.instrumentPostHogEvent({command:"fern export",properties:{outputPath:r.outputPath}}),await $gS({project:await Em(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,outputPath:xo(AO(),r.outputPath),indent:r.indent})})}function vlH(e,t){e.command("beta",!1,r=>r.help(!1).version(!1).strict(!1).parserConfiguration({"unknown-options-as-args":!0}),async r=>{try{let i=r._.slice(1).map(String);await ISp(i)}catch(i){t.logger.error("CLI v2 failed:",String(i)),t.failWithoutThrowing()}})}function glH(e,t){e.command("protoc-gen-fern",!1,r=>{},async()=>{let r=Ezp,i=await OlH(process.stdin),n=I7a(Uxp,i),a=r.run(n);await mlH(process.stdout,tAc(pHo,a)),process.exit(0)})}function OlH(e){return new Promise((t,r)=>{let i=[];e.on("data",n=>i.push(n)),e.on("end",()=>{t(new Uint8Array(Buffer.concat(i)))}),e.on("error",n=>{r(n)})})}function mlH(e,t){return new Promise((r,i)=>{e.write(t,n=>{n?i(n):r()})})}
|
|
2651
2651
|
/*! Bundled license information:
|
|
2652
2652
|
|
|
2653
2653
|
yargs-parser/build/lib/string-utils.js:
|
package/package.json
CHANGED