fern-api 3.55.4 → 3.55.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +4 -4
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1395,7 +1395,7 @@ ${t}`)}return t}getContent(){let t=this.stringifyImports();return t.length>0?t+`
1395
1395
  `),n=i[0]+`
1396
1396
  `,a=i.slice(1).join(`
1397
1397
  `);t.write(n.replaceAll("`","\\`")),t.writeNoIndent(a.replaceAll("`","\\`")),t.write("`")}writeIterable({writer:t,iterable:r}){let i=HyB({values:r.values});if(i.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let n of i)n.write(t),t.writeLine(",");t.dedent(),t.write("]")}writeRecord({writer:t,record:r}){let i=GyB({entries:r.entries});if(i.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let n of i)n.key.write(t),t.write(": "),n.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}writeObject({writer:t,object:r}){let i=xyB({fields:r.fields});if(i.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let n of i)t.write(`${n.name}: `),n.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}static array({values:t}){return new this({type:"array",values:t})}static bigint(t){return new this({type:"bigint",value:t})}static blob(t){return new this({type:"blob",value:t})}static boolean(t){return new this({type:"boolean",value:t})}static datetime(t){return new this({type:"datetime",value:t})}static number(t){return new this({type:"number",value:t})}static object({fields:t}){return new this({type:"object",fields:t})}static record({entries:t}){return new this({type:"record",entries:t})}static reference(t){return new this({type:"reference",value:t})}static set({values:t}){return new this({type:"set",values:t})}static string(t){return new this({type:"string",value:t})}static tuple({values:t}){return new this({type:"tuple",values:t})}static unknown(t){return new this({type:"unknown",value:t})}static null(){return new this({type:"null"})}static nop(){return new this({type:"nop"})}static isNop(t){return t.internalType.type==="nop"}writeUnknown({writer:t,value:r}){switch(typeof r){case"boolean":t.write(r.toString());return;case"string":t.write(r.includes('"')?`\`${r}\``:`"${r}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("null");return}if(Array.isArray(r)){this.writeUnknownArray({writer:t,value:r});return}this.writeUnknownObject({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeUnknownArray({writer:t,value:r}){if(r.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let i of r)t.writeNode(e.unknown(i)),t.writeLine(",");t.dedent(),t.write("]")}writeUnknownObject({writer:t,value:r}){let i=Object.entries(r);if(i.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let[n,a]of i)t.write(`${n}: `),t.writeNode(e.unknown(a)),t.writeLine(",");t.dedent(),t.write("}")}};function xyB({fields:e}){return e.filter(t=>!L3i.isNop(t.value))}function GyB({entries:e}){return e.filter(t=>!L3i.isNop(t.key)&&!L3i.isNop(t.value))}function HyB({values:e}){return e.filter(t=>!L3i.isNop(t))}var o_a=class extends aE{args;constructor(t){super(),this.args=t}write(t){this.args.export&&t.write("export "),this.args.const?t.write("const "):t.write("let "),t.write(`${this.args.name} = `),t.writeNode(this.args.initializer)}};function $yB(e){return new t_a(e)}function JyB(e){return new r_a(e)}function YyB(e){return new e_a(e)}function XyB(e){return new i_a(e)}function ZyB(e){return new n_a(e)}function kyB(e){return new a_a(e)}function ebB(e){return new Mjn(e)}function tbB(e){return new o_a(e)}function fTh({generatorConfig:e,isPackagePrivate:t}){let r=e.output.mode;switch(r.type){case"downloadFiles":return;case"publish":return{packageName:r.registriesV2.npm.packageName,version:r.version,private:t,publishInfo:{registryUrl:r.registriesV2.npm.registryUrl,token:r.registriesV2.npm.token},license:void 0,repoUrl:void 0};case"github":if(r.publishInfo!=null&&r.publishInfo.type!=="npm")throw new Error(`Expected to receive npm publish info but received ${r.publishInfo.type} instead`);return{packageName:r.publishInfo!=null?r.publishInfo.packageName:"",version:r.version,private:t,publishInfo:void 0,repoUrl:rbB(r.repoUrl),license:e.license?._visit({basic:i=>i.id,custom:i=>`See ${i.filename}`,_other:()=>{}})};default:throw new Error(`Encountered unknown output mode: ${r}`)}}function rbB(e){if(e!=null)return e.startsWith("https://github.com/")?`git+${e}`:e.startsWith("ssh://github.com/")?`github:${ito(e).replace("ssh://github.com/","")}`:e.startsWith("https://bitbucket.org/")?`bitbucket:${ito(e).replace("https://bitbucket.org/","")}`:e.startsWith("ssh://bitbucket.org/")?`bitbucket:${ito(e).replace("ssh://bitbucket.org/","")}`:e.startsWith("https://gitlab.com/")?`gitlab:${ito(e).replace("https://gitlab.com/","")}`:e.startsWith("ssh://gitlab.com/")?`gitlab:${ito(e).replace("ssh://gitlab.com/","")}`:(e.startsWith("git+")||(e=`git+${e}`),e.endsWith(".git")||(e=`${e}.git`),e)}function ito(e){return e.endsWith(".git")?e.slice(0,-4):e}function uZc({organization:e,workspaceName:t,namespaceExport:r}){return r??`${Ff(bn(e))}${Ff(bn(t))}`}var OZc=ue(QFh(),1);var ZbB="value",oPu=class{context;constructor({context:t}){this.context=t}convert(t){let r=t.convertOpts;if(t.value===null)return this.context.isNullable(t.typeReference)?ea.TypeLiteral.null():(this.context.errors.add({severity:Ur.Critical,message:"Expected non-null value, but got null"}),ea.TypeLiteral.nop());if(t.value===void 0)return ea.TypeLiteral.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value,convertOpts:r});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value,convertOpts:r});case"map":return this.convertMap({map:t.typeReference,value:t.value,convertOpts:r});case"named":{let i=this.context.resolveNamedType({typeId:t.typeReference.value});return i==null?ea.TypeLiteral.nop():this.convertNamed({named:i,value:t.value,as:t.as,convertOpts:r})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"set":return this.convertSet({set:t.typeReference.value,value:t.value,convertOpts:r});case"unknown":return this.convertUnknown({value:t.value,convertOpts:r});default:le(t.typeReference)}}convertLiteral({literalType:t,value:r}){switch(t.type){case"boolean":{let i=this.context.getValueAsBoolean({value:r});return i==null?ea.TypeLiteral.nop():ea.TypeLiteral.boolean(i)}case"string":{let i=this.context.getValueAsString({value:r});return i==null?ea.TypeLiteral.nop():ea.TypeLiteral.string(i)}default:le(t)}}convertList({list:t,value:r,convertOpts:i}){return Array.isArray(r)?ea.TypeLiteral.array({values:r.map((n,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:n,convertOpts:i})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ur.Critical,message:`Expected array but got: ${typeof r}`}),ea.TypeLiteral.nop())}convertSet({set:t,value:r,convertOpts:i}){return Array.isArray(r)?ea.TypeLiteral.set({values:r.map((n,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:n,convertOpts:i})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ur.Critical,message:`Expected array but got: ${typeof r}`}),ea.TypeLiteral.nop())}convertMap({map:t,value:r,convertOpts:i}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ur.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),ea.TypeLiteral.nop()):ea.TypeLiteral.record({entries:Object.entries(r).map(([n,a])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key",convertOpts:i}),value:this.convert({typeReference:t.value,value:a,convertOpts:i})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:i,convertOpts:n}){switch(t.type){case"alias":return this.context.customConfig?.useBrandedStringAliases?ea.TypeLiteral.reference(ea.codeblock(a=>{a.writeNode(ea.reference({name:this.context.namespaceExport,importFrom:this.context.getModuleImport(),memberName:this.context.getFullyQualifiedReference({declaration:t.declaration})})),a.write("("),a.writeNode(this.convert({typeReference:t.typeReference,value:r,as:i,convertOpts:n})),a.write(")")})):this.convert({typeReference:t.typeReference,value:r,as:i,convertOpts:n});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r,convertOpts:n});case"enum":return this.convertEnum({enum_:t,value:r,convertOpts:n});case"object":return this.convertObject({object_:t,value:r,convertOpts:n});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,convertOpts:n});default:le(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r,convertOpts:i}){let n=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(n==null)return ea.TypeLiteral.nop();let a=n.singleDiscriminatedUnionType,o=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:n,unionVariant:a,convertOpts:i});if(o==null)return ea.TypeLiteral.nop();if(this.context.customConfig?.includeUtilsOnUnionMembers)return ea.TypeLiteral.reference(ea.codeblock(d=>{d.writeNode(ea.invokeMethod({on:ea.reference({name:this.context.namespaceExport,importFrom:this.context.getModuleImport(),memberName:this.context.getFullyQualifiedReference({declaration:t.declaration})}),method:this.context.getMethodName(a.discriminantValue.name),arguments_:this.convertDiscriminatedUnionUtilsArgs({discriminatedUnionTypeInstance:n,unionVariant:a,unionProperties:o,convertOpts:i})}))}));let c={name:this.context.getPropertyName(t.discriminant.name),value:ea.TypeLiteral.string(a.discriminantValue.wireValue)};return ea.TypeLiteral.object({fields:[c,...o]})}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:r,convertOpts:i}){let n=this.getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r});switch(r.type){case"samePropertiesAsObject":{let a=this.context.resolveNamedType({typeId:r.typeId});if(a==null)return;let o=this.convertNamed({named:a,value:t.value,convertOpts:i});if(!o.isObject()){this.context.errors.add({severity:Ur.Critical,message:"Internal error; expected union value to be an object"});return}let c=o.asObjectOrThrow();return[...n,...c.fields]}case"singleProperty":try{this.context.errors.scope(r.discriminantValue.wireValue);let a=this.context.getRecord(t.value);return a==null?[...n,{name:ZbB,value:this.convert({typeReference:r.typeReference,value:t.value,convertOpts:i})}]:[...n,{name:this.context.getPropertyName(r.discriminantValue.name),value:this.convert({typeReference:r.typeReference,value:a[r.discriminantValue.wireValue],convertOpts:i})}]}finally{this.context.errors.unscope()}case"noProperties":return n;default:le(r)}}convertDiscriminatedUnionUtilsArgs({discriminatedUnionTypeInstance:t,unionVariant:r,unionProperties:i,convertOpts:n}){return r.type==="singleProperty"&&this.context.getRecord(t.value)==null&&i.length===1?[this.convert({typeReference:r.typeReference,value:t.value,convertOpts:n})]:i.length>0?[ea.TypeLiteral.object({fields:i})]:[]}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r,convertOpts:i}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert({...a,convertOpts:i})}}finally{this.context.errors.unscope()}})}convertObject({object_:t,value:r,convertOpts:i}){let n=this.context.associateByWireValue({parameters:this.filterReadWriteProperties(t.properties,i),values:this.context.getRecord(r)??{}});return ea.TypeLiteral.object({fields:n.map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert({...a,convertOpts:i})}}finally{this.context.errors.unscope()}})})}filterReadWriteProperties(t,r){return this.context.customConfig?.experimentalGenerateReadWriteOnlyTypes!==!0||typeof r>"u"||(r.isForRequest&&(t=t.filter(i=>i.propertyAccess!==OZc.ObjectPropertyAccess.ReadOnly)),r.isForResponse&&(t=t.filter(i=>i.propertyAccess!==OZc.ObjectPropertyAccess.WriteOnly))),t}convertEnum({enum_:t,value:r}){let i=this.getEnumValue({enum_:t,value:r});return i==null?ea.TypeLiteral.nop():ea.TypeLiteral.string(i)}getEnumValue({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ur.Critical,message:`Expected enum value string, got: ${typeof r}`});return}if(t.values.find(n=>n.wireValue===r)==null){this.context.errors.add({severity:Ur.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return r}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,convertOpts:i}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,convertOpts:i});return n??ea.TypeLiteral.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,convertOpts:i}){for(let n of t.types)try{return this.convert({typeReference:n,value:r,convertOpts:i})}catch{continue}this.context.errors.add({severity:Ur.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertUnknown({value:t,convertOpts:r}){return ea.TypeLiteral.unknown(t)}convertPrimitive({primitive:t,value:r,as:i,convertOpts:n}){switch(t){case"INTEGER":case"UINT":{let a=this.getValueAsNumber({value:r,as:i});return a==null?ea.TypeLiteral.nop():ea.TypeLiteral.number(a)}case"LONG":case"UINT_64":{let a=this.getValueAsNumber({value:r,as:i});return a==null?ea.TypeLiteral.nop():this.context.customConfig?.useBigInt?ea.TypeLiteral.bigint(BigInt(a)):ea.TypeLiteral.number(a)}case"FLOAT":case"DOUBLE":{let a=this.getValueAsNumber({value:r});return a==null?ea.TypeLiteral.nop():ea.TypeLiteral.number(a)}case"BOOLEAN":{let a=this.getValueAsBoolean({value:r,as:i});return a==null?ea.TypeLiteral.nop():ea.TypeLiteral.boolean(a)}case"BASE_64":case"DATE":case"UUID":case"STRING":{let a=this.context.getValueAsString({value:r});return a==null?ea.TypeLiteral.nop():ea.TypeLiteral.string(a)}case"DATE_TIME":{let a=this.context.getValueAsString({value:r});return a==null?ea.TypeLiteral.nop():ea.TypeLiteral.datetime(a)}case"BIG_INTEGER":{let a=this.context.getValueAsString({value:r});return a==null?ea.TypeLiteral.nop():this.context.customConfig?.useBigInt?ea.TypeLiteral.bigint(BigInt(a)):ea.TypeLiteral.string(a)}default:le(t)}}getValueAsNumber({value:t,as:r}){let i=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:i})}getValueAsBoolean({value:t,as:r}){let i=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:i})}};var uPu=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let i={fileFields:[],bodyPropertyFields:[]},n=this.context.getRecord(r)??{};for(let a of t.properties)switch(a.type){case"file":i.fileFields.push({name:this.context.getPropertyName(a.name),value:this.getSingleFileProperty({property:a,record:n})});break;case"fileArray":i.fileFields.push({name:this.context.getPropertyName(a.name),value:this.getArrayFileProperty({property:a,record:n})});break;case"bodyProperty":i.bodyPropertyFields.push({name:this.context.getPropertyName(a.name.name),value:this.getBodyProperty({property:a,record:n})});break;default:le(a)}return i}getSingleFileProperty({property:t,record:r}){let i=this.context.getSingleFileValue({property:t,record:r});return i==null?ea.TypeLiteral.nop():ea.TypeLiteral.blob(i)}getArrayFileProperty({property:t,record:r}){let i=this.context.getFileArrayValues({property:t,record:r});return i==null?ea.TypeLiteral.nop():ea.TypeLiteral.array({values:i.map(n=>ea.TypeLiteral.blob(n))})}getBodyProperty({property:t,record:r}){let i=r[t.name.wireValue];return i==null?ea.TypeLiteral.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:i})}};var sPu=class e extends Oq{ir;customConfig;dynamicTypeLiteralMapper;filePropertyMapper;moduleName;namespaceExport;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeLiteralMapper=new oPu({context:this}),this.filePropertyMapper=new uPu({context:this}),this.moduleName=kbB({config:r,customConfig:this.customConfig}),this.namespaceExport=uZc({organization:r.organization,workspaceName:r.workspaceName,namespaceExport:this.customConfig?.namespaceExport})}clone(){return new e({ir:this.ir,config:this.config})}getModuleImport(){return{type:"named",moduleName:this.moduleName}}getRootClientName(){return`${this.namespaceExport}Client`}getPropertyName(t){return this.customConfig?.retainOriginalCasing||this.customConfig?.noSerdeLayer?this.formatOriginalPropertyName(t.originalName):t.camelCase.unsafeName}getMethodName(t){return t.camelCase.unsafeName}getTypeName(t){return t.pascalCase.unsafeName}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return this.getEnvironmentsTypeReference(r)}getFullyQualifiedReference({declaration:t}){return t.fernFilepath.allParts.length>0?`${t.fernFilepath.allParts.map(r=>r.camelCase.unsafeName).join(".")}.${this.getTypeName(t.name)}`:`${this.getTypeName(t.name)}`}getEnvironmentsTypeReference(t){return ea.reference({name:`${this.namespaceExport}Environment`,importFrom:this.getModuleImport(),memberName:this.getTypeName(t)})}formatOriginalPropertyName(t){return t.includes("-")?`"${t}"`:t}};function kbB({config:e,customConfig:t}){return fTh({generatorConfig:e,isPackagePrivate:t?.private??!1})?.packageName??e.organization}var UFh="client",LFh="main",evB={type:"primitive",value:"STRING"},cPu=class{context;constructor({context:t}){this.context=t}async generateSnippet({endpoint:t,request:r}){return await this.buildCodeBlock({endpoint:t,snippet:r}).toStringAsync({customConfig:this.context.customConfig})}generateSnippetSync({endpoint:t,request:r}){return this.buildCodeBlock({endpoint:t,snippet:r}).toString({customConfig:this.context.customConfig})}async generateSnippetAst({endpoint:t,request:r}){return this.buildCodeBlock({endpoint:t,snippet:r})}buildCodeBlock({endpoint:t,snippet:r}){return ea.codeblock(i=>{i.writeNode(ea.function_({name:LFh,async:!0,parameters:[],body:ea.codeblock(n=>{n.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),n.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))})})),i.writeNodeStatement(ea.invokeFunction({function_:ea.reference({name:LFh}),arguments_:[]}))})}constructClient({endpoint:t,snippet:r}){return ea.variable({name:UFh,const:!0,initializer:ea.instantiateClass({class_:ea.reference({name:this.context.getRootClientName(),importFrom:this.context.getModuleImport()}),arguments_:[this.getConstructorArgs({endpoint:t,snippet:r})]})})}getConstructorArgs({endpoint:t,snippet:r}){let i=[],n=this.getConstructorEnvironmentArgs({baseUrl:r.baseURL,environment:r.environment});return n.length>0&&i.push(...n),t.auth!=null&&(r.auth!=null?i.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ur.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`})),this.context.errors.scope(Po.PathParameters),this.context.ir.pathParameters!=null&&i.push(...this.getPathParameters({namedParameters:this.context.ir.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Po.Headers),this.context.ir.headers!=null&&r.headers!=null&&i.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),i.length===0?ea.TypeLiteral.nop():ea.TypeLiteral.object({fields:i})}getConstructorEnvironmentArgs({baseUrl:t,environment:r}){let i=this.getEnvironmentValue({baseUrl:t,environment:r});return i==null?[]:[{name:"environment",value:i}]}getEnvironmentValue({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ur.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return ea.TypeLiteral.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let i=this.context.getEnvironmentTypeReferenceFromID(r);if(i==null){this.context.errors.add({severity:Ur.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return ea.TypeLiteral.reference(i)}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?ea.TypeLiteral.object({fields:Object.entries(r).map(([i,n])=>({name:i,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:evB,value:n})}))}):void 0}}getConstructorAuthArgs({auth:t,values:r}){switch(t.type){case"basic":return r.type!=="basic"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBasicAuthArg({auth:t,values:r});case"bearer":return r.type!=="bearer"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBearerAuthArgs({auth:t,values:r});case"header":return r.type!=="header"?(this.addAuthMismatchError(t,r),[]):this.getConstructorHeaderAuthArgs({auth:t,values:r});case"oauth":return r.type!=="oauth"?(this.addAuthMismatchError(t,r),[]):this.getConstructorOAuthArgs({auth:t,values:r});case"inferred":return r.type!=="inferred"?(this.addAuthMismatchError(t,r),[]):(this.addWarning("The TypeScript SDK v2 Generator does not support Inferred auth scheme yet"),[]);default:le(t)}}addAuthMismatchError(t,r){this.context.errors.add({severity:Ur.Critical,message:this.context.newAuthMismatchError({auth:t,values:r}).message})}addWarning(t){this.context.errors.add({severity:Ur.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return[{name:this.context.getPropertyName(t.username),value:ea.TypeLiteral.string(r.username)},{name:this.context.getPropertyName(t.password),value:ea.TypeLiteral.string(r.password)}]}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.token),value:ea.TypeLiteral.string(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.clientId),value:ea.TypeLiteral.string(r.clientId)},{name:this.context.getPropertyName(t.clientSecret),value:ea.TypeLiteral.string(r.clientSecret)}]}getConstructorHeaderArgs({headers:t,values:r}){let i=[];for(let n of t){let a=this.getConstructorHeaderArg({header:n,value:r.value});a!=null&&i.push(a)}return i}getConstructorHeaderArg({header:t,value:r}){let i=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!ea.TypeLiteral.isNop(i))return{name:this.context.getPropertyName(t.name.name),value:i}}callMethod({endpoint:t,snippet:r}){return ea.invokeMethod({on:ea.reference({name:UFh}),method:this.getMethod({endpoint:t}),async:!0,arguments_:this.getMethodArgs({endpoint:t,snippet:r})})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:le(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let i=[];this.context.errors.scope(Po.PathParameters);let n=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return n.length>0&&i.push(...this.getPathParameters({namedParameters:n,snippet:r}).map(a=>a.value)),this.context.errors.unscope(),this.context.errors.scope(Po.RequestBody),t.body!=null&&i.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),i}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,convertOpts:{isForRequest:!0}});default:le(t)}}getBytesBodyRequestArg({value:t}){return typeof t!="string"?(this.context.errors.add({severity:Ur.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),ea.TypeLiteral.nop()):ea.TypeLiteral.blob(t)}getMethodArgsForInlinedRequest({request:t,snippet:r}){let i=[],{inlinePathParameters:n,inlineFileProperties:a}={inlinePathParameters:this.context.customConfig?.inlinePathParameters??!1,inlineFileProperties:this.context.customConfig?.inlineFileProperties??!1};this.context.errors.scope(Po.PathParameters);let o=[];t.pathParameters!=null&&o.push(...this.getPathParameters({namedParameters:t.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Po.RequestBody);let c=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:n})||i.push(...o.map(d=>d.value)),a||i.push(...c.fileFields.map(d=>d.value)),this.context.needsRequestParameter({request:t,inlinePathParameters:n,inlineFileProperties:a})&&i.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:n})?o:[],filePropertyInfo:c})),i}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:i,filePropertyInfo:n}){this.context.errors.scope(Po.QueryParameters);let o=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(u=>({name:this.context.getPropertyName(u.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...u,convertOpts:{isForRequest:!0}})}));this.context.errors.unscope(),this.context.errors.scope(Po.Headers);let d=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(u=>({name:this.context.getPropertyName(u.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...u,convertOpts:{isForRequest:!0}})}));this.context.errors.unscope(),this.context.errors.scope(Po.RequestBody);let s=t.body!=null?this.getInlinedRequestBodyObjectFields({body:t.body,value:r.requestBody,filePropertyInfo:n}):[];return this.context.errors.unscope(),ea.TypeLiteral.object({fields:[...i,...o,...d,...s]})}getInlinedRequestBodyObjectFields({body:t,value:r,filePropertyInfo:i}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyObjectFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyObjectField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyObjectFields({filePropertyInfo:i});default:le(t)}}getFileUploadRequestBodyObjectFields({filePropertyInfo:t}){return this.context.customConfig?.inlineFileProperties?[...t.fileFields,...t.bodyPropertyFields]:t.bodyPropertyFields}getReferencedRequestBodyPropertyObjectField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,convertOpts:{isForRequest:!0}});default:le(t)}}getInlinedRequestBodyPropertyObjectFields({parameters:t,value:r}){let i=[],n=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let a of n)i.push({name:this.context.getPropertyName(a.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...a,convertOpts:{isForRequest:!0}})});return i}getPathParameters({namedParameters:t,snippet:r}){let i=[],n=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{},ignoreMissingParameters:!0});for(let a of n)i.push({name:this.context.getPropertyName(a.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...a,convertOpts:{isForRequest:!0}})});return i}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getMethodName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}};var ato=class extends gq{constructor({ir:t,config:r}){super(new sPu({ir:t,config:r}))}async generate(t){return super.generate(t)}generateSync(t){return super.generateSync(t)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new cPu({context:t})}};var fPu=require("fs/promises"),VFh=ue(require("path"),1);var lPu=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,i){this.context=t,this.ir=r,this.generatorConfig=i,this.dynamicSnippetsGenerator=new ato({ir:LQ(this.ir),config:this.buildGeneratorConfig(this.generatorConfig)})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[i,n]of r.entries())try{let a=UQ(n);if(a==null)continue;let o=await this.dynamicSnippetsGenerator.generate(a),c=this.getTestFilePath({outputDir:t,idx:i});await(0,fPu.mkdir)(VFh.default.dirname(c),{recursive:!0}),await(0,fPu.writeFile)(c,o.snippet)}catch(a){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(n.endpoint)}: ${a}`)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return at(t,Oe.of(`src/dynamic-snippets/example${r}/snippet.ts`))}buildGeneratorConfig(t){let r=t.output.mode;if(r.type!=="github")throw new Error("GitHub output mode is required for TypeScript dynamic snippet tests");let i=r.publishInfo;if(!i||i.type!=="npm")throw new Error("NPM publish info is required for TypeScript dynamic snippet tests");return{...t,output:{...t.output,mode:{...r,publishInfo:{...i,packageName:"../.."}}}}}};var dPu=class e{context;testSuite;static GENERATORS={csharp:{generator:Rmu},go:{generator:Wmu},java:{generator:kmu},php:{generator:oAu},typescript:{generator:lPu,unstable:!0},python:{generator:_Au,unstable:!0},ruby:{generator:jAu},rust:{generator:RAu},swift:{generator:kAu}};constructor(t,r){this.context=t,this.testSuite=r}async generateTests({outputDir:t,language:r,skipUnstable:i}){let n=e.GENERATORS[r];if(n==null||n.unstable&&i){this.context.logger.debug(`Skipping dynamic snippets test generation for language "${r}"`);return}return new n.generator(this.context,this.testSuite.ir,this.testSuite.config).generateTests({outputDir:t,requests:this.testSuite.requests})}};async function WFh({ir:e,config:t}){if(e.dynamic==null)throw new Error("Internal error; dynamic IR is not available");return{ir:e.dynamic,config:t,requests:Object.values(e.dynamic.endpoints).flatMap(r=>(r.examples??[]).map(i=>({...i,baseUrl:"https://api.fern.com"})))}}async function xFh({context:e,ir:t,config:r,language:i,outputDir:n,skipUnstable:a}){let o=await WFh({ir:t,config:r});return new dPu(e,o).generateTests({language:i,outputDir:n,skipUnstable:a})}var OdE=ue(rn(),1),uZn=require("fs/promises"),M4a=ue(require("path"),1),S4a=require("path"),mdE=ue(oQ(),1);var GFh=ue(require("path"),1);async function pPu({schema:e,value:t,context:r,filepathBeingParsed:i}){let n=await e.safeParseAsync(t);if(n.success)return n.data;let a=n.error.errors.map(c=>{let d=c.path.length>0?`${c.message} at "${tvB(c.path)}"`:c.message;return qWt({content:d,prefix:" - "})}),o=[`Failed to parse file: ${GFh.default.relative(process.cwd(),i)}`,...a].join(`
1398
- `);return r.failAndThrow(o)}function tvB(e){return e.reduce((t,r)=>typeof r=="number"?t+"["+r+"]":t+(t===""?"":".")+r,"")}var HFh=ue(require("path"),1),rvB={dependencies:{}};async function KFh({absolutePathToWorkspace:e,rawDependenciesConfiguration:t,context:r}){if(t==null)return rvB;let i={};for(let[n,a]of Object.entries(t.dependencies))if(nvB(a)){let o=vr.of(HFh.default.join(e,a));await ei(o)?i[n]={type:"local",absoluteFilepath:o,path:a}:r.failWithoutThrowing(`Path to ${n} dependency does not exist: ${o}`)}else{let c=n.substring(1).split("/"),d=c[0],s=c[1];d!=null&&s!=null?i[n]={type:"version",organization:d,apiName:s,version:a}:r.failWithoutThrowing(`Failed to parse dependency: ${n}`)}return r.getResult()===OA.Failure&&r.failAndThrow(),{dependencies:i}}var ivB=/^\.\.\/.*$/;function nvB(e){return ivB.test(e)}var JFh=require("fs/promises");var $Fh=Dt.object({dependencies:Dt.record(Dt.string(),Dt.string())});async function YFh({absolutePathToWorkspace:e,context:t}){let r=at(e,Oe.of(r6_));if(!await ei(r))return;let i=await(0,JFh.readFile)(r),n=Ii.load(i.toString());return await pPu({schema:$Fh,value:n,context:t,filepathBeingParsed:r})}async function mZc({absolutePathToWorkspace:e,context:t}){let r=await YFh({absolutePathToWorkspace:e,context:t});return KFh({absolutePathToWorkspace:e,rawDependenciesConfiguration:r,context:t})}function XFh(e={accentPrimary:void 0,background:void 0},t){e.accentPrimary=e.accentPrimary??e.accentPrimaryDeprecated;let r=hPu(e);switch(r){case"dark":return{type:"dark",..._Pu(e,t,"dark")};case"light":return{type:"light",..._Pu(e,t,"light")};case"darkAndLight":return{type:"darkAndLight",dark:_Pu(e,t,"dark"),light:_Pu(e,t,"light")};default:le(r)}}function hPu({background:e,accentPrimary:t,accentPrimaryDeprecated:r}){if(t=t??r,typeof e=="string"&&typeof t=="string")return su(e).isDark()?"dark":"light";if(e!=null){if(typeof e=="string")return su(e).isDark()?"dark":"light";if(e.dark!=null&&e.light!=null)return"darkAndLight"}if(t!=null){if(typeof t=="string")return su(t).isLight()?"dark":"light";if(t.dark!=null&&t.light!=null)return"darkAndLight"}if(t!=null&&e!=null){if(e.dark!=null&&t.dark!=null)return"dark";if(e.light!=null&&t.light!=null)return"light"}return"darkAndLight"}function _Pu(e,t,r){let i=s_a(e.accentPrimary??e.accentPrimaryDeprecated,t,"accent-primary",r)??su.random(),n=s_a(e.background,t,"background",r);return{accentPrimary:i.toRgb(),background:n?.toRgb(),border:s_a(e.border,t,"border",r)?.toRgb(),sidebarBackground:s_a(e.sidebarBackground,t,"sidebar-background",r)?.toRgb(),headerBackground:s_a(e.headerBackground,t,"header-background",r)?.toRgb(),cardBackground:s_a(e.cardBackground,t,"card-background",r)?.toRgb(),logo:void 0,backgroundImage:void 0}}function oto(e,t,r){if(e==null)return;let i=typeof e=="string"?e:e[r];if(i==null&&t==="accent-primary"&&typeof e!="string"&&(i=e[r==="dark"?"light":"dark"]),i!=null)return i}function s_a(e,t,r,i){let n=oto(e,r,i);if(n==null)return;let a=su(n);return a.isValid()||t.failAndThrow(`'${typeof e=="string"?r:`colors.${r}.${i}`}' should be a hex color of the format #FFFFFF`),a}var TPu=require("fs/promises");var ALh=ue(require("path"),1);var kFh=require("fs/promises");var ZFh=100;async function avB({files:e,absolutePathToFernFolder:t}){let r=await Promise.all(e.map(async i=>{let n=await(0,kFh.readFile)(i,"utf-8");return[aQ(t,i),n]}));return Object.fromEntries(r)}async function eQh({files:e,absolutePathToFernFolder:t}){let r={};for(let i=0;i<e.length;i+=ZFh){let n=e.slice(i,i+ZFh),a=await avB({files:n,absolutePathToFernFolder:t});Object.assign(r,a)}return r}function bPu({landingPage:e,navigation:t}){return OEe([e?.absolutePath,...ovB(t)])}function ovB(e){switch(e.type){case"tabbed":return e.items.flatMap(t=>t.child.type==="layout"?t.child.layout.flatMap(r=>yPu({item:r})):t.child.type==="variants"?t.child.variants.flatMap(r=>r.layout.flatMap(i=>yPu({item:i}))):t.child.type==="changelog"?t.child.changelog:[]);case"untabbed":return e.items.flatMap(t=>yPu({item:t}));case"versioned":return e.versions.flatMap(t=>bPu({landingPage:t.landingPage,navigation:t.navigation}));case"productgroup":return e.products.flatMap(t=>t.type==="external"?[]:bPu({landingPage:t.landingPage,navigation:t.navigation}));default:le(e)}}function yPu({item:e}){switch(e.type){case"apiSection":return OEe([e.overviewAbsolutePath,...e.navigation.flatMap(t=>tQh({item:t}))]);case"link":return[];case"page":return[e.absolutePath];case"section":return OEe([e.overviewAbsolutePath,...e.contents.flatMap(t=>yPu({item:t}))]);case"changelog":return e.changelog;case"pythonDocsSection":return[];default:le(e)}}function tQh({item:e}){return e.type==="page"?[e.absolutePath]:e.type==="package"||e.type==="section"?OEe([e.overviewAbsolutePath,...e.contents.flatMap(t=>tQh({item:t}))]):[]}var FZc=require("fs/promises"),OLh=ue(hme(),1);function DPu({name:e}){return e.replace(/\.(md|mdx)$/i,"").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}function BPu({name:e}){return e.replace(/\.(md|mdx)$/i,"").replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase())}async function vmB({absolutePath:e,readFileFn:t=(r,i)=>(0,FZc.readFile)(r,i)}){try{let r=await t(e,"utf-8"),{data:i}=(0,OLh.default)(r);if(i.position==null)return;let n=typeof i.position=="string"?parseFloat(i.position):i.position;return typeof n=="number"&&Number.isFinite(n)?n:void 0}catch{return}}async function QZc({directoryPath:e,getDir:t=kI,readFileFn:r=(i,n)=>(0,FZc.readFile)(i,n)}){let i=await t(e),n=i.filter(u=>u.type==="file"&&(u.name.endsWith(".md")||u.name.endsWith(".mdx"))),a=i.filter(u=>u.type==="directory"),o=await Promise.all(n.map(u=>vmB({absolutePath:u.absolutePath,readFileFn:r}))),c=n.map(u=>({type:"page",title:BPu({name:u.name}),absolutePath:u.absolutePath,slug:DPu({name:u.name}),icon:void 0,hidden:void 0,noindex:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0})),d=await Promise.all(a.map(async u=>{let f=await QZc({directoryPath:u.absolutePath,getDir:t,readFileFn:r});return{type:"section",title:BPu({name:u.name}),slug:DPu({name:u.name}),icon:void 0,contents:f,collapsed:void 0,hidden:void 0,skipUrlSlug:!1,overviewAbsolutePath:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0}})),s=[...c.map((u,f)=>({item:u,title:u.type==="page"?u.title:"",position:o[f]})),...d.map(u=>({item:u,title:u.type==="section"?u.title:"",position:void 0}))];return s.sort((u,f)=>{let p=typeof u.position=="number",_=typeof f.position=="number";if(p&&!_)return-1;if(!p&&_)return 1;if(typeof u.position=="number"&&typeof f.position=="number"){let h=u.position-f.position;return h!==0?h:u.title.localeCompare(f.title,void 0,{sensitivity:"base"})}return u.title.localeCompare(f.title,void 0,{sensitivity:"base"})}),s.map(u=>u.item)}function gmB(e){return!e||e.startsWith("<")?!1:e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function ED(e,t){if(e)return gmB(e)?Aq(e,t):e}async function xZc({rawDocsConfiguration:e,absolutePathToFernFolder:t,absoluteFilepathToDocsConfig:r,context:i}){let{instances:n,title:a,tabs:o,products:c,versions:d,navigation:s,navbarLinks:u,footerLinks:f,defaultLanguage:p,metadata:_,redirects:h,logo:y,favicon:b,backgroundImage:v,colors:O,typography:m,layout:g,integrations:A,css:j,js:S,aiChat:w,aiSearch:D,pageActions:B,experimental:R}=e,T=hto(e.landingPage,r),q=CmB({tabs:o,products:c,versions:d,navigation:s,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}),z=q.then(He=>eQh({files:bPu({navigation:He,landingPage:T}),absolutePathToFernFolder:t})),N=OmB(y,r),H=Aq(b,r),J=mmB(v,r),be=m!=null?qmB({rawTypography:m,absoluteFilepathToDocsConfig:r}):void 0,ge=AmB(j,r),G=wmB(S,r),V=kmB(_,r),[Se,se,Ae,Ue,ae,re]=await Promise.all([q,z,be,ge,G,V]);return{title:a,instances:n,roles:e.roles,pages:se,landingPage:T,navigation:Se,navbarLinks:XmB(u,r),footerLinks:ZmB(f),defaultLanguage:p,languages:e.languages,announcement:e.announcement,metadata:re,redirects:h?.map(He=>({...He,permanent:He?.permanent})),logo:N,favicon:H,backgroundImage:J,colors:XFh(O,i),typography:Ae,layout:ImB(g),settings:BmB(e.settings),theme:DmB(e.theme),analyticsConfig:{...e.analytics,intercom:e.analytics?.intercom?{...e.analytics.intercom,appId:e.analytics.intercom.appId,apiBase:e.analytics.intercom.apiBase}:void 0,fullstory:e.analytics?.fullstory,posthog:e.analytics?.posthog?{...e.analytics.posthog,apiKey:e.analytics.posthog.apiKey,endpoint:e.analytics.posthog.endpoint}:void 0,segment:e.analytics?.segment,gtm:e.analytics?.gtm,ga4:e.analytics?.ga4,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},integrations:{...A,intercom:A?.intercom?A.intercom:void 0},css:Ue,js:ae,aiChatConfig:D??w,pageActions:EmB(B,r),header:void 0,footer:void 0,experimental:R}}function OmB(e,t){return e!=null?{dark:Aq(e.dark,t),light:Aq(e.light,t),height:e.height,href:e.href!=null?li.Url(e.href):void 0,rightText:e.rightText}:void 0}function mmB(e,t){if(e!=null)if(typeof e=="string"){let r=Aq(e,t);return{dark:r,light:r}}else{let r=Aq(e.dark,t),i=Aq(e.light,t);return{dark:r,light:i}}}async function AmB(e,t){if(e==null)return;let r=typeof e=="string"?[e]:e;return{inline:await Promise.all(r.map(async i=>(await(0,TPu.readFile)(Aq(i,t))).toString()))}}function PmB(e){return Object.hasOwn(e,"url")}function jmB(e){return Object.hasOwn(e,"path")}async function wmB(e,t){let r=[],i=[];if(e==null)return{files:[]};let n=Array.isArray(e)?e:[e];for(let a of n)typeof a=="string"?i.push({absolutePath:Aq(a,t)}):PmB(a)?r.push({strategy:a.strategy,url:li.Url(a.url)}):jmB(a)&&i.push({absolutePath:Aq(a.path,t),strategy:a.strategy});return{remote:r,files:i}}function EmB(e,t){return e==null?void 0:{default:e.default!=null?SmB(e.default):void 0,options:{askAi:e.options?.askAi??!0,copyPage:e.options?.copyPage??!0,viewAsMarkdown:e.options?.viewAsMarkdown??!0,openAi:e.options?.chatgpt??!0,claude:e.options?.claude??!0,cursor:e.options?.cursor??!0,vscode:e.options?.vscode??!1,custom:(e.options?.custom??[]).map(i=>MmB(i,t))}}}function SmB(e){switch(e){case"copy-page":return li.docs.v1.commons.PageActionOption.CopyPage;case"view-as-markdown":return li.docs.v1.commons.PageActionOption.ViewAsMarkdown;case"ask-ai":return li.docs.v1.commons.PageActionOption.AskAi;case"chatgpt":return li.docs.v1.commons.PageActionOption.OpenAi;case"claude":return li.docs.v1.commons.PageActionOption.Claude;case"cursor":return li.docs.v1.commons.PageActionOption.Cursor;case"vscode":return li.docs.v1.commons.PageActionOption.Vscode;default:le(e)}}function MmB(e,t){return{title:e.title,subtitle:e.subtitle,url:e.url,icon:ED(e.icon,t),default:e.default}}function DmB(e){if(e!=null)return{sidebar:e.sidebar??"default",tabs:e.tabs??"default",body:e.body??"default",pageActions:e.pageActions??"default",footerNav:e.footerNav??"default",languageSwitcher:e.languageSwitcher??"default",productSwitcher:e.productSwitcher??"default"}}function BmB(e){if(e!=null)return{darkModeCode:e.darkModeCode??!1,defaultSearchFilters:e.defaultSearchFilters??!1,language:e.language??"en",disableSearch:e.disableSearch??!1,hide404Page:e.hide404Page??!1,httpSnippets:e.httpSnippets??!0,searchText:e.searchText??void 0,useJavascriptAsTypescript:e.useJavascriptAsTypescript??!1,disableExplorerProxy:e.disableExplorerProxy??!1,disableAnalytics:e.disableAnalytics??!1}}function ImB(e){if(e!=null)return{pageWidth:e.pageWidth?.trim().toLowerCase()==="full"?{type:"full"}:IPu(e.pageWidth),contentWidth:IPu(e.contentWidth),sidebarWidth:IPu(e.sidebarWidth),headerHeight:IPu(e.headerHeight),searchbarPlacement:e.searchbarPlacement==="header"?li.docs.v1.commons.SearchbarPlacement.Header:e.searchbarPlacement==="header-tabs"?li.docs.v1.commons.SearchbarPlacement.HeaderTabs:li.docs.v1.commons.SearchbarPlacement.Sidebar,switcherPlacement:e.switcherPlacement==="header"?li.docs.v1.commons.SwitcherPlacement.Header:li.docs.v1.commons.SwitcherPlacement.Sidebar,tabsPlacement:e.tabsPlacement==="header"?li.docs.v1.commons.TabsPlacement.Header:li.docs.v1.commons.TabsPlacement.Sidebar,contentAlignment:e.contentAlignment==="left"?li.docs.v1.commons.ContentAlignment.Left:li.docs.v1.commons.ContentAlignment.Center,headerPosition:e.headerPosition==="static"?li.docs.v1.commons.HeaderPosition.Absolute:li.docs.v1.commons.HeaderPosition.Fixed,disableHeader:e.disableHeader??!1,hideNavLinks:e.hideNavLinks??!1,hideFeedback:e.hideFeedback??!1}}function IPu(e){if(e==null)return;let t=e.trim().toLowerCase(),r=t.match(/^(\d+)px$/);if(r!=null&&r[1]!=null)return{type:"px",value:parseFloat(r[1])};let i=t.match(/^(\d+)rem$/);if(i!=null&&i[1]!=null)return{type:"rem",value:parseFloat(i[1])}}async function mLh({versions:e,absolutePathToFernFolder:t,context:r}){let i=[];for(let n of e){let a=Uo(t,n.path),o=Ii.load((await(0,TPu.readFile)(a)).toString()),c=[],d=AEe(o,[],c);c.length>0&&r.logger.warn(`Version file ${n.path} contained null/undefined sections that were ignored: ${c.map(f=>f.join(".")).join(", ")}`);let s=BX.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(d),u=await WZc({tabs:s.tabs,rawNavigationConfig:s.navigation,absolutePathToFernFolder:t,absolutePathToConfig:a,context:r});i.push({landingPage:hto(s.landingPage,a),version:n.displayName,navigation:u,availability:n.availability,slug:n.slug,hidden:n.hidden,viewers:ux(n.viewers),orphaned:n.orphaned,featureFlags:ox(n.featureFlag),announcement:n.announcement})}return{type:"versioned",versions:i}}async function CmB({tabs:e,products:t,versions:r,navigation:i,absolutePathToFernFolder:n,absolutePathToConfig:a,context:o}){if(i!=null)return await WZc({tabs:e,rawNavigationConfig:i,absolutePathToFernFolder:n,absolutePathToConfig:a,context:o});if(t!=null){let c=[];for(let d of t){let s=d.image!=null?Uo(n,d.image):void 0;if("path"in d){let u,f=Uo(n,d.path),p=Ii.load((await(0,TPu.readFile)(f)).toString()),_=[],h=AEe(p,[],_);_.length>0&&o.logger.warn(`Product file ${d.path} contained null/undefined sections that were ignored: ${_.map(b=>b.join(".")).join(", ")}`);let y=BX.RawSchemas.Serializer.ProductFileConfig.parseOrThrow(h);d.versions!=null&&d.versions.length>0?u=await mLh({versions:d.versions,absolutePathToFernFolder:n,context:o}):u=await WZc({tabs:y.tabs,rawNavigationConfig:y.navigation,absolutePathToFernFolder:n,absolutePathToConfig:f,context:o}),c.push({type:"internal",landingPage:hto(y.landingPage,f),product:d.displayName,navigation:u,slug:d.slug,subtitle:d.subtitle,icon:ED(d.icon,a)||"fa-solid fa-code",image:s,viewers:ux(d.viewers),orphaned:d.orphaned,featureFlags:ox(d.featureFlag),announcement:d.announcement})}else if("href"in d&&d.href!=null)c.push({type:"external",product:d.displayName,href:d.href,target:d.target,subtitle:d.subtitle,icon:ED(d.icon,a)||"fa-solid fa-code",image:s,viewers:ux(d.viewers),orphaned:d.orphaned,featureFlags:ox(d.featureFlag)});else throw new Error("Invalid product configuration: product must have either 'path' or valid 'href' property")}return{type:"productgroup",products:c}}else if(r!=null)return await mLh({versions:r,absolutePathToFernFolder:n,context:o});throw new Error("Unexpected. Docs have neither navigation or versions defined.")}function ox(e){if(e!=null)return typeof e=="string"?[{flag:e,match:!0,fallbackValue:void 0}]:Array.isArray(e)?e.map(t=>({flag:t.flag,match:t.match,fallbackValue:t.fallbackValue})):[{flag:e.flag,match:e.match??!0,fallbackValue:e.fallbackValue}]}async function qmB({rawTypography:e,absoluteFilepathToDocsConfig:t}){return{headingsFont:e.headingsFont!=null?await UZc({rawFontConfig:e.headingsFont,absoluteFilepathToDocsConfig:t}):void 0,bodyFont:e.bodyFont!=null?await UZc({rawFontConfig:e.bodyFont,absoluteFilepathToDocsConfig:t}):void 0,codeFont:e.codeFont!=null?await UZc({rawFontConfig:e.codeFont,absoluteFilepathToDocsConfig:t}):void 0}}async function UZc({rawFontConfig:e,absoluteFilepathToDocsConfig:t}){return{name:e.name,variants:await TmB(e,t),display:e.display,fallback:e.fallback,fontVariationSettings:e.fontVariationSettings}}function TmB(e,t){let r=[];return e.path!=null&&r.push({path:e.path,weight:e.weight,style:e.style}),e.paths?.forEach(i=>{typeof i=="string"?r.push({path:i,weight:e.weight,style:e.style}):r.push({path:i.path,weight:i.weight??e.weight,style:i.style??e.style})}),Promise.all(r.map(async i=>({absolutePath:Aq(i.path,t),weight:RmB(i.weight),style:i.style})))}function RmB(e){return e==null?void 0:typeof e=="number"?[e.toString()]:e.split(/\D+/).filter(r=>r!==""&&["100","200","300","400","500","600","700","800","900"].includes(r))}async function zmB({tabs:e,item:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){let a=e[t.tab];if(a==null)throw new Error(`Tab ${t.tab} is not defined in the tabs config.`);if(YmB(t)){let o=await Promise.all(t.variants.map(async c=>{let d=await Promise.all(c.layout.map(s=>qPu({rawConfig:s,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})));return{title:c.title,subtitle:c.subtitle,icon:ED(c.icon,i),layout:d,slug:c.slug,skipUrlSlug:c.skipSlug,hidden:c.hidden,default:c.default,viewers:ux(c.viewers),orphaned:c.orphaned,featureFlags:ox(c.featureFlag)}}));return{title:a.displayName,icon:ED(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"variants",variants:o},viewers:ux(a.viewers),orphaned:a.orphaned,featureFlags:ox(a.featureFlag)}}if(JmB(t)){let o=await Promise.all(t.layout.map(c=>qPu({rawConfig:c,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})));return{title:a.displayName,icon:ED(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"layout",layout:o},viewers:ux(a.viewers),orphaned:a.orphaned,featureFlags:ox(a.featureFlag)}}if(a.href!=null)return{title:a.displayName,icon:ED(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"link",href:a.href,target:a.target},viewers:ux(a.viewers),orphaned:a.orphaned,featureFlags:ox(a.featureFlag)};if(a.changelog!=null)return{title:a.displayName,icon:ED(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"changelog",changelog:await wV(Aq(a.changelog,i),"{md,mdx}")},viewers:ux(a.viewers),orphaned:a.orphaned,featureFlags:ox(a.featureFlag)};le(a)}async function WZc({tabs:e={},rawNavigationConfig:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){return $mB(t)?{type:"tabbed",items:await Promise.all(t.map(o=>zmB({tabs:e,item:o,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}:{type:"untabbed",items:await Promise.all(t.map(a=>qPu({rawConfig:a,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}}var NmB="Changelog";async function FmB({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}){let n=Aq(e.folder,r);await ei(n)||i.failAndThrow(`Folder not found: ${e.folder}`);let a=await QZc({directoryPath:n}),o=ALh.default.basename(n),c=e.title??BPu({name:o}),d=e.slug??DPu({name:o});return{type:"section",title:c,icon:ED(e.icon,r),contents:a,slug:d,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:void 0,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag),availability:e.availability}}async function qPu({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}){if(PLh(e))return hto(e,r);if(UmB(e))return{type:"section",title:e.section,icon:ED(e.icon,r),contents:await Promise.all(e.contents.map(n=>qPu({rawConfig:n,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}))),slug:e.slug??void 0,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:Aq(e.path,r),viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag),availability:e.availability};if(LmB(e))return{type:"apiSection",openrpc:e.openrpc,title:e.api,icon:ED(e.icon,r),apiName:e.apiName??void 0,audiences:e.audiences!=null?{type:"select",audiences:yto(e.audiences)??[]}:{type:"all"},availability:e.availability,showErrors:e.displayErrors??!0,tagDescriptionPages:e.tagDescriptionPages??!1,snippetsConfiguration:e.snippets!=null?QmB({rawConfig:e.snippets}):void 0,postman:e.postman,navigation:e.layout?.flatMap(n=>CPu(n,r))??[],overviewAbsolutePath:Aq(e.summary,r),collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,slug:e.slug,skipUrlSlug:e.skipSlug??!1,flattened:e.flattened??!1,alphabetized:e.alphabetized??!1,paginated:e.paginated??!1,playground:e.playground,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag)};if(jLh(e))return{type:"link",text:e.link,url:e.href,icon:ED(e.icon,r),target:e.target};if(VmB(e))return{type:"changelog",changelog:await wV(Aq(e.changelog,r),"{md,mdx}"),hidden:e.hidden??!1,icon:ED(e.icon,r),title:e.title??NmB,slug:e.slug,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag)};if(WmB(e))return await FmB({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i});if(xmB(e))return{type:"pythonDocsSection",githubUrl:e.pythonDocs,title:e.title??void 0,slug:e.slug??void 0};le(e)}function hto(e,t){if(e!=null)return{type:"page",title:e.page,absolutePath:Aq(e.path,t),slug:e.slug,icon:ED(e.icon,t),hidden:e.hidden,noindex:e.noindex,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag),availability:e.availability}}function CPu(e,t){return typeof e=="string"?[{type:"item",value:e}]:PLh(e)?[hto(e,t)]:jLh(e)?[{type:"link",text:e.link,url:e.href,icon:ED(e.icon,t),target:e.target}]:GmB(e)?[{type:"section",title:e.section,referencedSubpackages:e.referencedPackages??[],overviewAbsolutePath:Aq(e.summary,t),contents:e.contents?.flatMap(r=>CPu(r,t))??[],slug:e.slug,hidden:e.hidden,skipUrlSlug:e.skipSlug,availability:e.availability,icon:ED(e.icon,t),playground:e.playground,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag)}]:HmB(e)?[{type:"endpoint",endpoint:e.endpoint,title:e.title,icon:ED(e.icon,t),slug:e.slug,hidden:e.hidden,availability:e.availability,playground:e.playground,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag)}]:Object.entries(e).map(([r,i])=>KmB(i)?{type:"package",title:i.title,package:r,overviewAbsolutePath:Aq(i.summary,t),contents:i.contents?.flatMap(n=>CPu(n,t))??[],slug:i.slug,hidden:i.hidden,skipUrlSlug:i.skipSlug,icon:ED(i.icon,t),playground:i.playground,availability:i.availability,viewers:ux(i.viewers),orphaned:i.orphaned,featureFlags:ox(i.featureFlag)}:{type:"package",title:void 0,package:r,overviewAbsolutePath:void 0,contents:i.flatMap(n=>CPu(n,t)),hidden:!1,slug:void 0,skipUrlSlug:!1,icon:void 0,playground:void 0,availability:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}function QmB({rawConfig:e}){return{python:e.python,typescript:e.typescript,go:e.go,java:e.java,ruby:e.ruby,csharp:e.csharp,php:e.php,swift:e.swift}}function PLh(e){return Nl(e)&&typeof e.page=="string"&&typeof e.path=="string"}function UmB(e){return e.section!=null}function LmB(e){return e.api!=null}function jLh(e){return BX.RawSchemas,Nl(e)&&typeof e.link=="string"&&typeof e.href=="string"}function VmB(e){return Nl(e)&&typeof e.changelog=="string"}function WmB(e){return Nl(e)&&typeof e.folder=="string"}function xmB(e){return Nl(e)&&typeof e.pythonDocs=="string"}function GmB(e){return Nl(e)&&typeof e.section=="string"&&Array.isArray(e.contents)}function HmB(e){return Nl(e)&&typeof e.endpoint=="string"}function KmB(e){return!Array.isArray(e)}function Aq(e,t){if(e!=null)return Uo(an(t),e)}function $mB(e){return Array.isArray(e)&&e.length>0&&e[0].tab!=null}function JmB(e){return"layout"in e&&Array.isArray(e.layout)}function YmB(e){return"variants"in e&&Array.isArray(e.variants)}function XmB(e,t){return e?.map(r=>{if(r.type==="github"){let n=r.value;return typeof n=="string"?{type:"github",url:li.Url(n),viewers:void 0,target:void 0}:{type:"github",url:li.Url(n.url),viewers:LZc(n.viewers),target:n.target}}let i=LZc(r.viewers);return r.type==="dropdown"?{type:"dropdown",text:r.text,icon:ED(r.icon,t),rightIcon:ED(r.rightIcon,t),rounded:r.rounded,viewers:i,links:r.links?.map(n=>({href:n.href,target:n.target,url:li.Url(n.url??n.href??"/"),text:n.text,icon:ED(n.icon,t),rightIcon:ED(n.rightIcon,t),rounded:n.rounded,viewers:LZc(n.viewers)}))??[]}:{type:r.type,text:r.text,url:li.Url(r.href??r.url??"/"),target:r.target,icon:ED(r.icon,t),rightIcon:ED(r.rightIcon,t),rounded:r.rounded,viewers:i}})}function LZc(e){if(e!=null)return Array.isArray(e)?e.map(t=>li.RoleId(t)):[li.RoleId(e)]}function ZmB(e){if(e==null)return;let t=[];if(Object.keys(e).forEach(r=>{let i=e[r];i!=null&&t.push({type:r,value:li.Url(i)})}),t.length!==0)return t}async function kmB(e,t){if(e!=null)return{"og:site_name":e.ogSiteName,"og:title":e.ogTitle,"og:description":e.ogDescription,"og:url":e.ogUrl,"og:image":await VZc(e.ogImage,t),"og:image:width":e.ogImageWidth,"og:image:height":e.ogImageHeight,"og:locale":e.ogLocale,"og:logo":await VZc(e.ogLogo,t),"twitter:title":e.twitterTitle,"twitter:description":e.twitterDescription,"twitter:image":await VZc(e.twitterImage,t),"twitter:handle":e.twitterHandle,"twitter:site":e.twitterSite,"twitter:url":e.twitterUrl,"twitter:card":e.twitterCard,nofollow:void 0,noindex:void 0,canonicalHost:e.canonicalHost}}async function VZc(e,t){if(e==null)return;if(e.startsWith("http"))return{type:"url",value:e};let r=Aq(e,t);return await ei(r)?{type:"filepath",value:r}:{type:"url",value:e}}function ux(e){if(e!=null){if(typeof e=="string")return[li.RoleId(e)];if(e.length!==0)return e.map(li.RoleId)}}function yto(e){if(e!=null){if(typeof e=="string")return[e];if(e.length!==0)return e}}var ELh=require("fs/promises");var wLh=Dt.strictObject({organization:Dt.string(),version:Dt.string()});async function yme({directory:e,context:t}){let r=at(e,Oe.of(aC)),i=await(0,ELh.readFile)(r),n=JSON.parse(i.toString()),a=await pPu({schema:wLh,value:n,context:t,filepathBeingParsed:r});return{_absolutePath:r,rawConfig:a,organization:a.organization,version:a.version}}var P={TYPESCRIPT:"fernapi/fern-typescript",TYPESCRIPT_SDK:"fernapi/fern-typescript-sdk",TYPESCRIPT_NODE_SDK:"fernapi/fern-typescript-node-sdk",TYPESCRIPT_BROWSER_SDK:"fernapi/fern-typescript-browser-sdk",TYPESCRIPT_EXPRESS:"fernapi/fern-typescript-express",JAVA:"fernapi/fern-java",JAVA_MODEL:"fernapi/fern-java-model",JAVA_SDK:"fernapi/fern-java-sdk",JAVA_SPRING:"fernapi/fern-java-spring",PYTHON_FASTAPI:"fernapi/fern-fastapi-server",PYTHON_PYDANTIC:"fernapi/fern-pydantic-model",PYTHON_SDK:"fernapi/fern-python-sdk",GO_MODEL:"fernapi/fern-go-model",GO_SDK:"fernapi/fern-go-sdk",GO_FIBER:"fernapi/fern-go-fiber",RUBY_MODEL:"fernapi/fern-ruby-model",RUBY_SDK:"fernapi/fern-ruby-sdk",CSHARP_MODEL:"fernapi/fern-csharp-model",CSHARP_SDK:"fernapi/fern-csharp-sdk",SWIFT_MODEL:"fernapi/fern-swift-model",SWIFT_SDK:"fernapi/fern-swift-sdk",PHP_MODEL:"fernapi/fern-php-model",PHP_SDK:"fernapi/fern-php-sdk",RUST_MODEL:"fernapi/fern-rust-model",RUST_SDK:"fernapi/fern-rust-sdk",OPENAPI:"fernapi/fern-openapi",STOPLIGHT:"fernapi/fern-stoplight",POSTMAN:"fernapi/fern-postman",OPENAPI_PYTHON_CLIENT:"fernapi/openapi-python-client"};var bto={[P.JAVA]:{version:"2.38.1"},[P.TYPESCRIPT_EXPRESS]:{version:"0.18.4",output:{location:"local-file-system",path:"../src/fern"}},[P.JAVA_MODEL]:{version:"1.0.0"},[P.JAVA_SDK]:{version:"2.38.1",output:{location:"local-file-system",path:"../sdks/java/src/main/java/"}},[P.JAVA_SPRING]:{version:"0.9.2",output:{location:"local-file-system",path:"../src/main/java/com/fern"}},[P.TYPESCRIPT]:{version:"0.0.247"},[P.TYPESCRIPT_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.TYPESCRIPT_NODE_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.TYPESCRIPT_BROWSER_SDK]:{version:"1.0.0",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.PYTHON_PYDANTIC]:{version:"1.4.7"},[P.PYTHON_FASTAPI]:{version:"1.7.0",output:{location:"local-file-system",path:"../src/fern"}},[P.PYTHON_SDK]:{version:"4.23.2",output:{location:"local-file-system",path:"../sdks/python"}},[P.GO_FIBER]:{version:"0.23.5"},[P.GO_MODEL]:{version:"0.23.5"},[P.GO_SDK]:{version:"1.4.0",output:{location:"local-file-system",path:"../sdks/go"},config:{module:{path:"sdk"}}},[P.RUBY_MODEL]:{version:"0.0.8"},[P.RUBY_SDK]:{version:"0.8.2",output:{location:"local-file-system",path:"../sdks/ruby"}},[P.OPENAPI]:{version:"0.1.7",config:{format:"yaml"},output:{location:"local-file-system",path:"../openapi"}},[P.STOPLIGHT]:{version:"0.0.28",config:{format:"yaml"}},[P.POSTMAN]:{version:"0.4.0",output:{location:"local-file-system",path:"../postman"}},[P.OPENAPI_PYTHON_CLIENT]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/python"},config:{format:"yaml"}},[P.CSHARP_MODEL]:{version:"0.0.1"},[P.CSHARP_SDK]:{version:"2.0.2",output:{location:"local-file-system",path:"../sdks/csharp"}},[P.SWIFT_MODEL]:{version:"0.0.0"},[P.SWIFT_SDK]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/swift/sdk"}},[P.PHP_MODEL]:{version:"0.0.0"},[P.PHP_SDK]:{version:"1.16.3",output:{location:"local-file-system",path:"../sdks/php/sdk"}},[P.RUST_MODEL]:{version:"0.0.1",output:{location:"local-file-system",path:"../models/rust"}},[P.RUST_SDK]:{version:"0.0.1",output:{location:"local-file-system",path:"../sdks/rust"}}};var SLh="fernapi";function xQ(e){return e.includes("/")?e:`${SLh}/${e}`}function GZc(e){let t=`${SLh}/`;return e.startsWith(t)?e.slice(t.length):e}function R2i(e,t){let r=eAB(e);return r??t.failAndThrow("Unrecognized generator: "+e)}function eAB(e){if(e=xQ(e),tAB(e))return e}function tAB(e){return Object.values(P).includes(e)}var RPu=ue(u$a(),1),MLh=ue(EY(),1);async function rxt({generatorName:e,cliVersion:t,channel:r,currentGeneratorVersion:i,includeMajor:n,context:a}){let o=MLh.default.parse(i),c=new RPu.FernRegistryClient({environment:"https://registry.buildwithfern.com"});a?.logger.debug(`Getting latest version for ${e} with CLI version ${t}, includeMajor: ${n}, prior version: ${o}`);let d={generator:rAB(e,a),releaseTypes:[r??RPu.FernRegistry.generators.ReleaseType.Ga],cliVersion:t==="0.0.0"?void 0:t};!n&&o!=null&&(d.generatorMajorVersion=o.major);let s=await c.generators.versions.getLatestGeneratorRelease(d);if(s.ok)return s.body.version}function rAB(e,t){switch(e.startsWith("fernapi/")&&(e=e.replace("fernapi/","")),e){case"fern-python-sdk":return"python-sdk";case"fern-pydantic-model":return"pydantic";case"fern-fastapi-server":return"fastapi";case"fern-typescript-browser-sdk":case"fern-typescript-node-sdk":case"fern-typescript-sdk":return"ts-sdk";case"fern-typescript-express":return"ts-express";case"fern-java-sdk":return"java-sdk";case"fern-java-model":return"java-model";case"fern-java-spring":return"java-spring";case"fern-go-sdk":return"go-sdk";case"fern-go-model":return"go-model";case"fern-go-fiber":return"go-fiber";case"fern-csharp-sdk":return"csharp-sdk";case"fern-csharp-model":return"csharp-model";case"fern-ruby-sdk":return"ruby-sdk";case"fern-ruby-model":return"ruby-model";case"fern-postman":return"postman";case"fern-openapi":return"openapi";case"fern-php-sdk":return"php-sdk";case"fern-php-model":return"php-model";case"fern-rust-sdk":return"rust-sdk";case"fern-rust-model":return"rust-model";case"fern-swift-sdk":return"swift-sdk";case"fern-swift-model":return"swift-model";default:return t?.logger.warn(`Unrecognized generator name found, attempting to parse manually: ${e}`),e.startsWith("fern-")?e.replace("fern-",""):e}}async function DLh({generatorsConfiguration:e,groupName:t=e[Ki.DEFAULT_GROUP_GENERATORS_CONFIG_KEY],context:r,update:i}){if(t==null)return r.failAndThrow("No group specified.");let n=e.groups??={},a=n[t];if(a==null){let o=n[t]??={generators:[]};await i(o,t)}else await i(a,t);return e}async function HZc({generatorName:e,generatorsConfiguration:t,groupName:r=t[jua],context:i,cliVersion:n}){let a=R2i(e,i),o=GZc(a),c=bto[a];return await DLh({generatorsConfiguration:t,groupName:r,context:i,update:async d=>{d.generators.some(s=>xQ(s.name)===a)&&i.failAndThrow(`${e} is already installed in group ${r}.`),d.generators.push({name:o,...c,version:await rxt({cliVersion:n,generatorName:a,context:i,channel:void 0})??c.version})}})}var ixt=require("fs/promises"),own=ue(require("path"),1);var f4h=require("buffer"),$Pu=ue(ILh(),1),GPu=ue(mB(),1),tVh=require("child_process"),FVh=ue($Zc(),1),JVh=require("path"),g_a=ue($Zc(),1),d3h=require("events"),h2c=Object.defineProperty,cAB=Object.getOwnPropertyDescriptor,y2c=Object.getOwnPropertyNames,lAB=Object.prototype.hasOwnProperty,za=(e,t)=>function(){return e&&(t=(0,e[y2c(e)[0]])(e=0)),t},fAB=(e,t)=>function(){return t||(0,e[y2c(e)[0]])((t={exports:{}}).exports,t),t.exports},jq=(e,t)=>{for(var r in t)h2c(e,r,{get:t[r],enumerable:!0})},dAB=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of y2c(t))!lAB.call(e,n)&&n!==r&&h2c(e,n,{get:()=>t[n],enumerable:!(i=cAB(t,n))||i.enumerable});return e},pC=e=>dAB(h2c({},"__esModule",{value:!0}),e);function pAB(...e){let t=new String(e);return KPu.set(t,e),t}function VPu(e){return e instanceof String&&KPu.has(e)}function CLh(e){return KPu.get(e)||[]}var KPu,mto=za({"src/lib/args/pathspec.ts"(){"use strict";KPu=new WeakMap}}),G3i,N2i=za({"src/lib/errors/git-error.ts"(){"use strict";G3i=class extends Error{constructor(e,t){super(t),this.task=e,Object.setPrototypeOf(this,new.target.prototype)}}}}),Ato,m_a=za({"src/lib/errors/git-response-error.ts"(){"use strict";N2i(),Ato=class extends G3i{constructor(e,t){super(void 0,t||String(e)),this.git=e}}}}),c4h,l4h=za({"src/lib/errors/task-configuration-error.ts"(){"use strict";N2i(),c4h=class extends G3i{constructor(e){super(void 0,e)}}}});function d4h(e){return typeof e!="function"?awn:e}function p4h(e){return typeof e=="function"&&e!==awn}function _4h(e,t){let r=e.indexOf(t);return r<=0?[e,""]:[e.substr(0,r),e.substr(r+1)]}function h4h(e,t=0){return y4h(e)&&e.length>t?e[t]:void 0}function nwn(e,t=0){if(y4h(e)&&e.length>t)return e[e.length-1-t]}function y4h(e){return ZPu(e)}function Pto(e="",t=!0,r=`
1398
+ `);return r.failAndThrow(o)}function tvB(e){return e.reduce((t,r)=>typeof r=="number"?t+"["+r+"]":t+(t===""?"":".")+r,"")}var HFh=ue(require("path"),1),rvB={dependencies:{}};async function KFh({absolutePathToWorkspace:e,rawDependenciesConfiguration:t,context:r}){if(t==null)return rvB;let i={};for(let[n,a]of Object.entries(t.dependencies))if(nvB(a)){let o=vr.of(HFh.default.join(e,a));await ei(o)?i[n]={type:"local",absoluteFilepath:o,path:a}:r.failWithoutThrowing(`Path to ${n} dependency does not exist: ${o}`)}else{let c=n.substring(1).split("/"),d=c[0],s=c[1];d!=null&&s!=null?i[n]={type:"version",organization:d,apiName:s,version:a}:r.failWithoutThrowing(`Failed to parse dependency: ${n}`)}return r.getResult()===OA.Failure&&r.failAndThrow(),{dependencies:i}}var ivB=/^\.\.\/.*$/;function nvB(e){return ivB.test(e)}var JFh=require("fs/promises");var $Fh=Dt.object({dependencies:Dt.record(Dt.string(),Dt.string())});async function YFh({absolutePathToWorkspace:e,context:t}){let r=at(e,Oe.of(r6_));if(!await ei(r))return;let i=await(0,JFh.readFile)(r),n=Ii.load(i.toString());return await pPu({schema:$Fh,value:n,context:t,filepathBeingParsed:r})}async function mZc({absolutePathToWorkspace:e,context:t}){let r=await YFh({absolutePathToWorkspace:e,context:t});return KFh({absolutePathToWorkspace:e,rawDependenciesConfiguration:r,context:t})}function XFh(e={accentPrimary:void 0,background:void 0},t){e.accentPrimary=e.accentPrimary??e.accentPrimaryDeprecated;let r=hPu(e);switch(r){case"dark":return{type:"dark",..._Pu(e,t,"dark")};case"light":return{type:"light",..._Pu(e,t,"light")};case"darkAndLight":return{type:"darkAndLight",dark:_Pu(e,t,"dark"),light:_Pu(e,t,"light")};default:le(r)}}function hPu({background:e,accentPrimary:t,accentPrimaryDeprecated:r}){if(t=t??r,typeof e=="string"&&typeof t=="string")return su(e).isDark()?"dark":"light";if(e!=null){if(typeof e=="string")return su(e).isDark()?"dark":"light";if(e.dark!=null&&e.light!=null)return"darkAndLight"}if(t!=null){if(typeof t=="string")return su(t).isLight()?"dark":"light";if(t.dark!=null&&t.light!=null)return"darkAndLight"}if(t!=null&&e!=null){if(e.dark!=null&&t.dark!=null)return"dark";if(e.light!=null&&t.light!=null)return"light"}return"darkAndLight"}function _Pu(e,t,r){let i=s_a(e.accentPrimary??e.accentPrimaryDeprecated,t,"accent-primary",r)??su.random(),n=s_a(e.background,t,"background",r);return{accentPrimary:i.toRgb(),background:n?.toRgb(),border:s_a(e.border,t,"border",r)?.toRgb(),sidebarBackground:s_a(e.sidebarBackground,t,"sidebar-background",r)?.toRgb(),headerBackground:s_a(e.headerBackground,t,"header-background",r)?.toRgb(),cardBackground:s_a(e.cardBackground,t,"card-background",r)?.toRgb(),logo:void 0,backgroundImage:void 0}}function oto(e,t,r){if(e==null)return;let i=typeof e=="string"?e:e[r];if(i==null&&t==="accent-primary"&&typeof e!="string"&&(i=e[r==="dark"?"light":"dark"]),i!=null)return i}function s_a(e,t,r,i){let n=oto(e,r,i);if(n==null)return;let a=su(n);return a.isValid()||t.failAndThrow(`'${typeof e=="string"?r:`colors.${r}.${i}`}' should be a hex color of the format #FFFFFF`),a}var TPu=require("fs/promises");var ALh=ue(require("path"),1);var kFh=require("fs/promises");var ZFh=100;async function avB({files:e,absolutePathToFernFolder:t}){let r=await Promise.all(e.map(async i=>{let n=await(0,kFh.readFile)(i,"utf-8");return[aQ(t,i),n]}));return Object.fromEntries(r)}async function eQh({files:e,absolutePathToFernFolder:t}){let r={};for(let i=0;i<e.length;i+=ZFh){let n=e.slice(i,i+ZFh),a=await avB({files:n,absolutePathToFernFolder:t});Object.assign(r,a)}return r}function bPu({landingPage:e,navigation:t}){return OEe([e?.absolutePath,...ovB(t)])}function ovB(e){switch(e.type){case"tabbed":return e.items.flatMap(t=>t.child.type==="layout"?t.child.layout.flatMap(r=>yPu({item:r})):t.child.type==="variants"?t.child.variants.flatMap(r=>r.layout.flatMap(i=>yPu({item:i}))):t.child.type==="changelog"?t.child.changelog:[]);case"untabbed":return e.items.flatMap(t=>yPu({item:t}));case"versioned":return e.versions.flatMap(t=>bPu({landingPage:t.landingPage,navigation:t.navigation}));case"productgroup":return e.products.flatMap(t=>t.type==="external"?[]:bPu({landingPage:t.landingPage,navigation:t.navigation}));default:le(e)}}function yPu({item:e}){switch(e.type){case"apiSection":return OEe([e.overviewAbsolutePath,...e.navigation.flatMap(t=>tQh({item:t}))]);case"link":return[];case"page":return[e.absolutePath];case"section":return OEe([e.overviewAbsolutePath,...e.contents.flatMap(t=>yPu({item:t}))]);case"changelog":return e.changelog;case"pythonDocsSection":return[];default:le(e)}}function tQh({item:e}){return e.type==="page"?[e.absolutePath]:e.type==="package"||e.type==="section"?OEe([e.overviewAbsolutePath,...e.contents.flatMap(t=>tQh({item:t}))]):[]}var FZc=require("fs/promises"),OLh=ue(hme(),1);function DPu({name:e}){return e.replace(/\.(md|mdx)$/i,"").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}function BPu({name:e}){return e.replace(/\.(md|mdx)$/i,"").replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase())}async function vmB({absolutePath:e,readFileFn:t=(r,i)=>(0,FZc.readFile)(r,i)}){try{let r=await t(e,"utf-8"),{data:i}=(0,OLh.default)(r);if(i.position==null)return;let n=typeof i.position=="string"?parseFloat(i.position):i.position;return typeof n=="number"&&Number.isFinite(n)?n:void 0}catch{return}}async function QZc({directoryPath:e,getDir:t=kI,readFileFn:r=(i,n)=>(0,FZc.readFile)(i,n)}){let i=await t(e),n=i.filter(u=>u.type==="file"&&(u.name.endsWith(".md")||u.name.endsWith(".mdx"))),a=i.filter(u=>u.type==="directory"),o=await Promise.all(n.map(u=>vmB({absolutePath:u.absolutePath,readFileFn:r}))),c=n.map(u=>({type:"page",title:BPu({name:u.name}),absolutePath:u.absolutePath,slug:DPu({name:u.name}),icon:void 0,hidden:void 0,noindex:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0})),d=await Promise.all(a.map(async u=>{let f=await QZc({directoryPath:u.absolutePath,getDir:t,readFileFn:r});return{type:"section",title:BPu({name:u.name}),slug:DPu({name:u.name}),icon:void 0,contents:f,collapsed:void 0,hidden:void 0,skipUrlSlug:!1,overviewAbsolutePath:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0,availability:void 0}})),s=[...c.map((u,f)=>({item:u,title:u.type==="page"?u.title:"",position:o[f]})),...d.map(u=>({item:u,title:u.type==="section"?u.title:"",position:void 0}))];return s.sort((u,f)=>{let p=typeof u.position=="number",_=typeof f.position=="number";if(p&&!_)return-1;if(!p&&_)return 1;if(typeof u.position=="number"&&typeof f.position=="number"){let h=u.position-f.position;return h!==0?h:u.title.localeCompare(f.title,void 0,{sensitivity:"base"})}return u.title.localeCompare(f.title,void 0,{sensitivity:"base"})}),s.map(u=>u.item)}function gmB(e){return!e||e.startsWith("<")?!1:e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function ED(e,t){if(e)return gmB(e)?Aq(e,t):e}async function xZc({rawDocsConfiguration:e,absolutePathToFernFolder:t,absoluteFilepathToDocsConfig:r,context:i}){let{instances:n,title:a,tabs:o,products:c,versions:d,navigation:s,navbarLinks:u,footerLinks:f,defaultLanguage:p,metadata:_,redirects:h,logo:y,favicon:b,backgroundImage:v,colors:O,typography:m,layout:g,integrations:A,css:j,js:S,aiChat:w,aiSearch:D,pageActions:B,experimental:R}=e,T=hto(e.landingPage,r),q=CmB({tabs:o,products:c,versions:d,navigation:s,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}),z=q.then(He=>eQh({files:bPu({navigation:He,landingPage:T}),absolutePathToFernFolder:t})),N=OmB(y,r),H=Aq(b,r),J=mmB(v,r),be=m!=null?qmB({rawTypography:m,absoluteFilepathToDocsConfig:r}):void 0,ge=AmB(j,r),G=wmB(S,r),V=kmB(_,r),[Se,se,Ae,Ue,ae,re]=await Promise.all([q,z,be,ge,G,V]);return{title:a,instances:n,roles:e.roles,pages:se,landingPage:T,navigation:Se,navbarLinks:XmB(u,r),footerLinks:ZmB(f),defaultLanguage:p,languages:e.languages,announcement:e.announcement,metadata:re,redirects:h?.map(He=>({...He,permanent:He?.permanent})),logo:N,favicon:H,backgroundImage:J,colors:XFh(O,i),typography:Ae,layout:ImB(g),settings:BmB(e.settings),theme:DmB(e.theme),analyticsConfig:{...e.analytics,intercom:e.analytics?.intercom?{...e.analytics.intercom,appId:e.analytics.intercom.appId,apiBase:e.analytics.intercom.apiBase}:void 0,fullstory:e.analytics?.fullstory,posthog:e.analytics?.posthog?{...e.analytics.posthog,apiKey:e.analytics.posthog.apiKey,endpoint:e.analytics.posthog.endpoint}:void 0,segment:e.analytics?.segment,gtm:e.analytics?.gtm,ga4:e.analytics?.ga4,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},integrations:{...A,intercom:A?.intercom?A.intercom:void 0},css:Ue,js:ae,aiChatConfig:D??w,pageActions:EmB(B,r),header:void 0,footer:void 0,experimental:R}}function OmB(e,t){return e!=null?{dark:Aq(e.dark,t),light:Aq(e.light,t),height:e.height,href:e.href!=null?li.Url(e.href):void 0,rightText:e.rightText}:void 0}function mmB(e,t){if(e!=null)if(typeof e=="string"){let r=Aq(e,t);return{dark:r,light:r}}else{let r=Aq(e.dark,t),i=Aq(e.light,t);return{dark:r,light:i}}}async function AmB(e,t){if(e==null)return;let r=typeof e=="string"?[e]:e;return{inline:await Promise.all(r.map(async i=>(await(0,TPu.readFile)(Aq(i,t))).toString()))}}function PmB(e){return Object.hasOwn(e,"url")}function jmB(e){return Object.hasOwn(e,"path")}async function wmB(e,t){let r=[],i=[];if(e==null)return{files:[]};let n=Array.isArray(e)?e:[e];for(let a of n)typeof a=="string"?i.push({absolutePath:Aq(a,t)}):PmB(a)?r.push({strategy:a.strategy,url:li.Url(a.url)}):jmB(a)&&i.push({absolutePath:Aq(a.path,t),strategy:a.strategy});return{remote:r,files:i}}function EmB(e,t){return e==null?void 0:{default:e.default!=null?SmB(e.default):void 0,options:{askAi:e.options?.askAi??!0,copyPage:e.options?.copyPage??!0,viewAsMarkdown:e.options?.viewAsMarkdown??!0,openAi:e.options?.chatgpt??!0,claude:e.options?.claude??!0,cursor:e.options?.cursor??!0,vscode:e.options?.vscode??!1,custom:(e.options?.custom??[]).map(i=>MmB(i,t))}}}function SmB(e){switch(e){case"copy-page":return li.docs.v1.commons.PageActionOption.CopyPage;case"view-as-markdown":return li.docs.v1.commons.PageActionOption.ViewAsMarkdown;case"ask-ai":return li.docs.v1.commons.PageActionOption.AskAi;case"chatgpt":return li.docs.v1.commons.PageActionOption.OpenAi;case"claude":return li.docs.v1.commons.PageActionOption.Claude;case"cursor":return li.docs.v1.commons.PageActionOption.Cursor;case"vscode":return li.docs.v1.commons.PageActionOption.Vscode;default:le(e)}}function MmB(e,t){return{title:e.title,subtitle:e.subtitle,url:e.url,icon:ED(e.icon,t),default:e.default}}function DmB(e){if(e!=null)return{sidebar:e.sidebar??"default",tabs:e.tabs??"default",body:e.body??"default",pageActions:e.pageActions??"default",footerNav:e.footerNav??"default",languageSwitcher:e.languageSwitcher??"default",productSwitcher:e.productSwitcher??"default"}}function BmB(e){if(e!=null)return{darkModeCode:e.darkModeCode??!1,defaultSearchFilters:e.defaultSearchFilters??!1,language:e.language??"en",disableSearch:e.disableSearch??!1,hide404Page:e.hide404Page??!1,httpSnippets:e.httpSnippets??!0,searchText:e.searchText??void 0,useJavascriptAsTypescript:e.useJavascriptAsTypescript??!1,disableExplorerProxy:e.disableExplorerProxy??!1,disableAnalytics:e.disableAnalytics??!1}}function ImB(e){if(e!=null)return{pageWidth:e.pageWidth?.trim().toLowerCase()==="full"?{type:"full"}:IPu(e.pageWidth),contentWidth:IPu(e.contentWidth),sidebarWidth:IPu(e.sidebarWidth),headerHeight:IPu(e.headerHeight),searchbarPlacement:e.searchbarPlacement==="header"?li.docs.v1.commons.SearchbarPlacement.Header:e.searchbarPlacement==="header-tabs"?li.docs.v1.commons.SearchbarPlacement.HeaderTabs:li.docs.v1.commons.SearchbarPlacement.Sidebar,switcherPlacement:!e.switcherPlacement||e.switcherPlacement==="header"?li.docs.v1.commons.SwitcherPlacement.Header:li.docs.v1.commons.SwitcherPlacement.Sidebar,tabsPlacement:e.tabsPlacement==="header"?li.docs.v1.commons.TabsPlacement.Header:li.docs.v1.commons.TabsPlacement.Sidebar,contentAlignment:e.contentAlignment==="left"?li.docs.v1.commons.ContentAlignment.Left:li.docs.v1.commons.ContentAlignment.Center,headerPosition:e.headerPosition==="static"?li.docs.v1.commons.HeaderPosition.Absolute:li.docs.v1.commons.HeaderPosition.Fixed,disableHeader:e.disableHeader??!1,hideNavLinks:e.hideNavLinks??!1,hideFeedback:e.hideFeedback??!1}}function IPu(e){if(e==null)return;let t=e.trim().toLowerCase(),r=t.match(/^(\d+)px$/);if(r!=null&&r[1]!=null)return{type:"px",value:parseFloat(r[1])};let i=t.match(/^(\d+)rem$/);if(i!=null&&i[1]!=null)return{type:"rem",value:parseFloat(i[1])}}async function mLh({versions:e,absolutePathToFernFolder:t,context:r}){let i=[];for(let n of e){let a=Uo(t,n.path),o=Ii.load((await(0,TPu.readFile)(a)).toString()),c=[],d=AEe(o,[],c);c.length>0&&r.logger.warn(`Version file ${n.path} contained null/undefined sections that were ignored: ${c.map(f=>f.join(".")).join(", ")}`);let s=BX.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(d),u=await WZc({tabs:s.tabs,rawNavigationConfig:s.navigation,absolutePathToFernFolder:t,absolutePathToConfig:a,context:r});i.push({landingPage:hto(s.landingPage,a),version:n.displayName,navigation:u,availability:n.availability,slug:n.slug,hidden:n.hidden,viewers:ux(n.viewers),orphaned:n.orphaned,featureFlags:ox(n.featureFlag),announcement:n.announcement})}return{type:"versioned",versions:i}}async function CmB({tabs:e,products:t,versions:r,navigation:i,absolutePathToFernFolder:n,absolutePathToConfig:a,context:o}){if(i!=null)return await WZc({tabs:e,rawNavigationConfig:i,absolutePathToFernFolder:n,absolutePathToConfig:a,context:o});if(t!=null){let c=[];for(let d of t){let s=d.image!=null?Uo(n,d.image):void 0;if("path"in d){let u,f=Uo(n,d.path),p=Ii.load((await(0,TPu.readFile)(f)).toString()),_=[],h=AEe(p,[],_);_.length>0&&o.logger.warn(`Product file ${d.path} contained null/undefined sections that were ignored: ${_.map(b=>b.join(".")).join(", ")}`);let y=BX.RawSchemas.Serializer.ProductFileConfig.parseOrThrow(h);d.versions!=null&&d.versions.length>0?u=await mLh({versions:d.versions,absolutePathToFernFolder:n,context:o}):u=await WZc({tabs:y.tabs,rawNavigationConfig:y.navigation,absolutePathToFernFolder:n,absolutePathToConfig:f,context:o}),c.push({type:"internal",landingPage:hto(y.landingPage,f),product:d.displayName,navigation:u,slug:d.slug,subtitle:d.subtitle,icon:ED(d.icon,a)||"fa-solid fa-code",image:s,viewers:ux(d.viewers),orphaned:d.orphaned,featureFlags:ox(d.featureFlag),announcement:d.announcement})}else if("href"in d&&d.href!=null)c.push({type:"external",product:d.displayName,href:d.href,target:d.target,subtitle:d.subtitle,icon:ED(d.icon,a)||"fa-solid fa-code",image:s,viewers:ux(d.viewers),orphaned:d.orphaned,featureFlags:ox(d.featureFlag)});else throw new Error("Invalid product configuration: product must have either 'path' or valid 'href' property")}return{type:"productgroup",products:c}}else if(r!=null)return await mLh({versions:r,absolutePathToFernFolder:n,context:o});throw new Error("Unexpected. Docs have neither navigation or versions defined.")}function ox(e){if(e!=null)return typeof e=="string"?[{flag:e,match:!0,fallbackValue:void 0}]:Array.isArray(e)?e.map(t=>({flag:t.flag,match:t.match,fallbackValue:t.fallbackValue})):[{flag:e.flag,match:e.match??!0,fallbackValue:e.fallbackValue}]}async function qmB({rawTypography:e,absoluteFilepathToDocsConfig:t}){return{headingsFont:e.headingsFont!=null?await UZc({rawFontConfig:e.headingsFont,absoluteFilepathToDocsConfig:t}):void 0,bodyFont:e.bodyFont!=null?await UZc({rawFontConfig:e.bodyFont,absoluteFilepathToDocsConfig:t}):void 0,codeFont:e.codeFont!=null?await UZc({rawFontConfig:e.codeFont,absoluteFilepathToDocsConfig:t}):void 0}}async function UZc({rawFontConfig:e,absoluteFilepathToDocsConfig:t}){return{name:e.name,variants:await TmB(e,t),display:e.display,fallback:e.fallback,fontVariationSettings:e.fontVariationSettings}}function TmB(e,t){let r=[];return e.path!=null&&r.push({path:e.path,weight:e.weight,style:e.style}),e.paths?.forEach(i=>{typeof i=="string"?r.push({path:i,weight:e.weight,style:e.style}):r.push({path:i.path,weight:i.weight??e.weight,style:i.style??e.style})}),Promise.all(r.map(async i=>({absolutePath:Aq(i.path,t),weight:RmB(i.weight),style:i.style})))}function RmB(e){return e==null?void 0:typeof e=="number"?[e.toString()]:e.split(/\D+/).filter(r=>r!==""&&["100","200","300","400","500","600","700","800","900"].includes(r))}async function zmB({tabs:e,item:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){let a=e[t.tab];if(a==null)throw new Error(`Tab ${t.tab} is not defined in the tabs config.`);if(YmB(t)){let o=await Promise.all(t.variants.map(async c=>{let d=await Promise.all(c.layout.map(s=>qPu({rawConfig:s,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})));return{title:c.title,subtitle:c.subtitle,icon:ED(c.icon,i),layout:d,slug:c.slug,skipUrlSlug:c.skipSlug,hidden:c.hidden,default:c.default,viewers:ux(c.viewers),orphaned:c.orphaned,featureFlags:ox(c.featureFlag)}}));return{title:a.displayName,icon:ED(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"variants",variants:o},viewers:ux(a.viewers),orphaned:a.orphaned,featureFlags:ox(a.featureFlag)}}if(JmB(t)){let o=await Promise.all(t.layout.map(c=>qPu({rawConfig:c,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})));return{title:a.displayName,icon:ED(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"layout",layout:o},viewers:ux(a.viewers),orphaned:a.orphaned,featureFlags:ox(a.featureFlag)}}if(a.href!=null)return{title:a.displayName,icon:ED(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"link",href:a.href,target:a.target},viewers:ux(a.viewers),orphaned:a.orphaned,featureFlags:ox(a.featureFlag)};if(a.changelog!=null)return{title:a.displayName,icon:ED(a.icon,i),slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"changelog",changelog:await wV(Aq(a.changelog,i),"{md,mdx}")},viewers:ux(a.viewers),orphaned:a.orphaned,featureFlags:ox(a.featureFlag)};le(a)}async function WZc({tabs:e={},rawNavigationConfig:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){return $mB(t)?{type:"tabbed",items:await Promise.all(t.map(o=>zmB({tabs:e,item:o,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}:{type:"untabbed",items:await Promise.all(t.map(a=>qPu({rawConfig:a,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}}var NmB="Changelog";async function FmB({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}){let n=Aq(e.folder,r);await ei(n)||i.failAndThrow(`Folder not found: ${e.folder}`);let a=await QZc({directoryPath:n}),o=ALh.default.basename(n),c=e.title??BPu({name:o}),d=e.slug??DPu({name:o});return{type:"section",title:c,icon:ED(e.icon,r),contents:a,slug:d,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:void 0,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag),availability:e.availability}}async function qPu({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}){if(PLh(e))return hto(e,r);if(UmB(e))return{type:"section",title:e.section,icon:ED(e.icon,r),contents:await Promise.all(e.contents.map(n=>qPu({rawConfig:n,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}))),slug:e.slug??void 0,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:Aq(e.path,r),viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag),availability:e.availability};if(LmB(e))return{type:"apiSection",openrpc:e.openrpc,title:e.api,icon:ED(e.icon,r),apiName:e.apiName??void 0,audiences:e.audiences!=null?{type:"select",audiences:yto(e.audiences)??[]}:{type:"all"},availability:e.availability,showErrors:e.displayErrors??!0,tagDescriptionPages:e.tagDescriptionPages??!1,snippetsConfiguration:e.snippets!=null?QmB({rawConfig:e.snippets}):void 0,postman:e.postman,navigation:e.layout?.flatMap(n=>CPu(n,r))??[],overviewAbsolutePath:Aq(e.summary,r),collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,slug:e.slug,skipUrlSlug:e.skipSlug??!1,flattened:e.flattened??!1,alphabetized:e.alphabetized??!1,paginated:e.paginated??!1,playground:e.playground,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag)};if(jLh(e))return{type:"link",text:e.link,url:e.href,icon:ED(e.icon,r),target:e.target};if(VmB(e))return{type:"changelog",changelog:await wV(Aq(e.changelog,r),"{md,mdx}"),hidden:e.hidden??!1,icon:ED(e.icon,r),title:e.title??NmB,slug:e.slug,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag)};if(WmB(e))return await FmB({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i});if(xmB(e))return{type:"pythonDocsSection",githubUrl:e.pythonDocs,title:e.title??void 0,slug:e.slug??void 0};le(e)}function hto(e,t){if(e!=null)return{type:"page",title:e.page,absolutePath:Aq(e.path,t),slug:e.slug,icon:ED(e.icon,t),hidden:e.hidden,noindex:e.noindex,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag),availability:e.availability}}function CPu(e,t){return typeof e=="string"?[{type:"item",value:e}]:PLh(e)?[hto(e,t)]:jLh(e)?[{type:"link",text:e.link,url:e.href,icon:ED(e.icon,t),target:e.target}]:GmB(e)?[{type:"section",title:e.section,referencedSubpackages:e.referencedPackages??[],overviewAbsolutePath:Aq(e.summary,t),contents:e.contents?.flatMap(r=>CPu(r,t))??[],slug:e.slug,hidden:e.hidden,skipUrlSlug:e.skipSlug,availability:e.availability,icon:ED(e.icon,t),playground:e.playground,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag)}]:HmB(e)?[{type:"endpoint",endpoint:e.endpoint,title:e.title,icon:ED(e.icon,t),slug:e.slug,hidden:e.hidden,availability:e.availability,playground:e.playground,viewers:ux(e.viewers),orphaned:e.orphaned,featureFlags:ox(e.featureFlag)}]:Object.entries(e).map(([r,i])=>KmB(i)?{type:"package",title:i.title,package:r,overviewAbsolutePath:Aq(i.summary,t),contents:i.contents?.flatMap(n=>CPu(n,t))??[],slug:i.slug,hidden:i.hidden,skipUrlSlug:i.skipSlug,icon:ED(i.icon,t),playground:i.playground,availability:i.availability,viewers:ux(i.viewers),orphaned:i.orphaned,featureFlags:ox(i.featureFlag)}:{type:"package",title:void 0,package:r,overviewAbsolutePath:void 0,contents:i.flatMap(n=>CPu(n,t)),hidden:!1,slug:void 0,skipUrlSlug:!1,icon:void 0,playground:void 0,availability:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}function QmB({rawConfig:e}){return{python:e.python,typescript:e.typescript,go:e.go,java:e.java,ruby:e.ruby,csharp:e.csharp,php:e.php,swift:e.swift}}function PLh(e){return Nl(e)&&typeof e.page=="string"&&typeof e.path=="string"}function UmB(e){return e.section!=null}function LmB(e){return e.api!=null}function jLh(e){return BX.RawSchemas,Nl(e)&&typeof e.link=="string"&&typeof e.href=="string"}function VmB(e){return Nl(e)&&typeof e.changelog=="string"}function WmB(e){return Nl(e)&&typeof e.folder=="string"}function xmB(e){return Nl(e)&&typeof e.pythonDocs=="string"}function GmB(e){return Nl(e)&&typeof e.section=="string"&&Array.isArray(e.contents)}function HmB(e){return Nl(e)&&typeof e.endpoint=="string"}function KmB(e){return!Array.isArray(e)}function Aq(e,t){if(e!=null)return Uo(an(t),e)}function $mB(e){return Array.isArray(e)&&e.length>0&&e[0].tab!=null}function JmB(e){return"layout"in e&&Array.isArray(e.layout)}function YmB(e){return"variants"in e&&Array.isArray(e.variants)}function XmB(e,t){return e?.map(r=>{if(r.type==="github"){let n=r.value;return typeof n=="string"?{type:"github",url:li.Url(n),viewers:void 0,target:void 0}:{type:"github",url:li.Url(n.url),viewers:LZc(n.viewers),target:n.target}}let i=LZc(r.viewers);return r.type==="dropdown"?{type:"dropdown",text:r.text,icon:ED(r.icon,t),rightIcon:ED(r.rightIcon,t),rounded:r.rounded,viewers:i,links:r.links?.map(n=>({href:n.href,target:n.target,url:li.Url(n.url??n.href??"/"),text:n.text,icon:ED(n.icon,t),rightIcon:ED(n.rightIcon,t),rounded:n.rounded,viewers:LZc(n.viewers)}))??[]}:{type:r.type,text:r.text,url:li.Url(r.href??r.url??"/"),target:r.target,icon:ED(r.icon,t),rightIcon:ED(r.rightIcon,t),rounded:r.rounded,viewers:i}})}function LZc(e){if(e!=null)return Array.isArray(e)?e.map(t=>li.RoleId(t)):[li.RoleId(e)]}function ZmB(e){if(e==null)return;let t=[];if(Object.keys(e).forEach(r=>{let i=e[r];i!=null&&t.push({type:r,value:li.Url(i)})}),t.length!==0)return t}async function kmB(e,t){if(e!=null)return{"og:site_name":e.ogSiteName,"og:title":e.ogTitle,"og:description":e.ogDescription,"og:url":e.ogUrl,"og:image":await VZc(e.ogImage,t),"og:image:width":e.ogImageWidth,"og:image:height":e.ogImageHeight,"og:locale":e.ogLocale,"og:logo":await VZc(e.ogLogo,t),"twitter:title":e.twitterTitle,"twitter:description":e.twitterDescription,"twitter:image":await VZc(e.twitterImage,t),"twitter:handle":e.twitterHandle,"twitter:site":e.twitterSite,"twitter:url":e.twitterUrl,"twitter:card":e.twitterCard,nofollow:void 0,noindex:void 0,canonicalHost:e.canonicalHost}}async function VZc(e,t){if(e==null)return;if(e.startsWith("http"))return{type:"url",value:e};let r=Aq(e,t);return await ei(r)?{type:"filepath",value:r}:{type:"url",value:e}}function ux(e){if(e!=null){if(typeof e=="string")return[li.RoleId(e)];if(e.length!==0)return e.map(li.RoleId)}}function yto(e){if(e!=null){if(typeof e=="string")return[e];if(e.length!==0)return e}}var ELh=require("fs/promises");var wLh=Dt.strictObject({organization:Dt.string(),version:Dt.string()});async function yme({directory:e,context:t}){let r=at(e,Oe.of(aC)),i=await(0,ELh.readFile)(r),n=JSON.parse(i.toString()),a=await pPu({schema:wLh,value:n,context:t,filepathBeingParsed:r});return{_absolutePath:r,rawConfig:a,organization:a.organization,version:a.version}}var P={TYPESCRIPT:"fernapi/fern-typescript",TYPESCRIPT_SDK:"fernapi/fern-typescript-sdk",TYPESCRIPT_NODE_SDK:"fernapi/fern-typescript-node-sdk",TYPESCRIPT_BROWSER_SDK:"fernapi/fern-typescript-browser-sdk",TYPESCRIPT_EXPRESS:"fernapi/fern-typescript-express",JAVA:"fernapi/fern-java",JAVA_MODEL:"fernapi/fern-java-model",JAVA_SDK:"fernapi/fern-java-sdk",JAVA_SPRING:"fernapi/fern-java-spring",PYTHON_FASTAPI:"fernapi/fern-fastapi-server",PYTHON_PYDANTIC:"fernapi/fern-pydantic-model",PYTHON_SDK:"fernapi/fern-python-sdk",GO_MODEL:"fernapi/fern-go-model",GO_SDK:"fernapi/fern-go-sdk",GO_FIBER:"fernapi/fern-go-fiber",RUBY_MODEL:"fernapi/fern-ruby-model",RUBY_SDK:"fernapi/fern-ruby-sdk",CSHARP_MODEL:"fernapi/fern-csharp-model",CSHARP_SDK:"fernapi/fern-csharp-sdk",SWIFT_MODEL:"fernapi/fern-swift-model",SWIFT_SDK:"fernapi/fern-swift-sdk",PHP_MODEL:"fernapi/fern-php-model",PHP_SDK:"fernapi/fern-php-sdk",RUST_MODEL:"fernapi/fern-rust-model",RUST_SDK:"fernapi/fern-rust-sdk",OPENAPI:"fernapi/fern-openapi",STOPLIGHT:"fernapi/fern-stoplight",POSTMAN:"fernapi/fern-postman",OPENAPI_PYTHON_CLIENT:"fernapi/openapi-python-client"};var bto={[P.JAVA]:{version:"2.38.1"},[P.TYPESCRIPT_EXPRESS]:{version:"0.18.4",output:{location:"local-file-system",path:"../src/fern"}},[P.JAVA_MODEL]:{version:"1.0.0"},[P.JAVA_SDK]:{version:"2.38.1",output:{location:"local-file-system",path:"../sdks/java/src/main/java/"}},[P.JAVA_SPRING]:{version:"0.9.2",output:{location:"local-file-system",path:"../src/main/java/com/fern"}},[P.TYPESCRIPT]:{version:"0.0.247"},[P.TYPESCRIPT_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.TYPESCRIPT_NODE_SDK]:{version:"2.3.2",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.TYPESCRIPT_BROWSER_SDK]:{version:"1.0.0",output:{location:"local-file-system",path:"../sdks/typescript"}},[P.PYTHON_PYDANTIC]:{version:"1.4.7"},[P.PYTHON_FASTAPI]:{version:"1.7.0",output:{location:"local-file-system",path:"../src/fern"}},[P.PYTHON_SDK]:{version:"4.23.2",output:{location:"local-file-system",path:"../sdks/python"}},[P.GO_FIBER]:{version:"0.23.5"},[P.GO_MODEL]:{version:"0.23.5"},[P.GO_SDK]:{version:"1.4.0",output:{location:"local-file-system",path:"../sdks/go"},config:{module:{path:"sdk"}}},[P.RUBY_MODEL]:{version:"0.0.8"},[P.RUBY_SDK]:{version:"0.8.2",output:{location:"local-file-system",path:"../sdks/ruby"}},[P.OPENAPI]:{version:"0.1.7",config:{format:"yaml"},output:{location:"local-file-system",path:"../openapi"}},[P.STOPLIGHT]:{version:"0.0.28",config:{format:"yaml"}},[P.POSTMAN]:{version:"0.4.0",output:{location:"local-file-system",path:"../postman"}},[P.OPENAPI_PYTHON_CLIENT]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/python"},config:{format:"yaml"}},[P.CSHARP_MODEL]:{version:"0.0.1"},[P.CSHARP_SDK]:{version:"2.0.2",output:{location:"local-file-system",path:"../sdks/csharp"}},[P.SWIFT_MODEL]:{version:"0.0.0"},[P.SWIFT_SDK]:{version:"0.0.0",output:{location:"local-file-system",path:"../sdks/swift/sdk"}},[P.PHP_MODEL]:{version:"0.0.0"},[P.PHP_SDK]:{version:"1.16.3",output:{location:"local-file-system",path:"../sdks/php/sdk"}},[P.RUST_MODEL]:{version:"0.0.1",output:{location:"local-file-system",path:"../models/rust"}},[P.RUST_SDK]:{version:"0.0.1",output:{location:"local-file-system",path:"../sdks/rust"}}};var SLh="fernapi";function xQ(e){return e.includes("/")?e:`${SLh}/${e}`}function GZc(e){let t=`${SLh}/`;return e.startsWith(t)?e.slice(t.length):e}function R2i(e,t){let r=eAB(e);return r??t.failAndThrow("Unrecognized generator: "+e)}function eAB(e){if(e=xQ(e),tAB(e))return e}function tAB(e){return Object.values(P).includes(e)}var RPu=ue(u$a(),1),MLh=ue(EY(),1);async function rxt({generatorName:e,cliVersion:t,channel:r,currentGeneratorVersion:i,includeMajor:n,context:a}){let o=MLh.default.parse(i),c=new RPu.FernRegistryClient({environment:"https://registry.buildwithfern.com"});a?.logger.debug(`Getting latest version for ${e} with CLI version ${t}, includeMajor: ${n}, prior version: ${o}`);let d={generator:rAB(e,a),releaseTypes:[r??RPu.FernRegistry.generators.ReleaseType.Ga],cliVersion:t==="0.0.0"?void 0:t};!n&&o!=null&&(d.generatorMajorVersion=o.major);let s=await c.generators.versions.getLatestGeneratorRelease(d);if(s.ok)return s.body.version}function rAB(e,t){switch(e.startsWith("fernapi/")&&(e=e.replace("fernapi/","")),e){case"fern-python-sdk":return"python-sdk";case"fern-pydantic-model":return"pydantic";case"fern-fastapi-server":return"fastapi";case"fern-typescript-browser-sdk":case"fern-typescript-node-sdk":case"fern-typescript-sdk":return"ts-sdk";case"fern-typescript-express":return"ts-express";case"fern-java-sdk":return"java-sdk";case"fern-java-model":return"java-model";case"fern-java-spring":return"java-spring";case"fern-go-sdk":return"go-sdk";case"fern-go-model":return"go-model";case"fern-go-fiber":return"go-fiber";case"fern-csharp-sdk":return"csharp-sdk";case"fern-csharp-model":return"csharp-model";case"fern-ruby-sdk":return"ruby-sdk";case"fern-ruby-model":return"ruby-model";case"fern-postman":return"postman";case"fern-openapi":return"openapi";case"fern-php-sdk":return"php-sdk";case"fern-php-model":return"php-model";case"fern-rust-sdk":return"rust-sdk";case"fern-rust-model":return"rust-model";case"fern-swift-sdk":return"swift-sdk";case"fern-swift-model":return"swift-model";default:return t?.logger.warn(`Unrecognized generator name found, attempting to parse manually: ${e}`),e.startsWith("fern-")?e.replace("fern-",""):e}}async function DLh({generatorsConfiguration:e,groupName:t=e[Ki.DEFAULT_GROUP_GENERATORS_CONFIG_KEY],context:r,update:i}){if(t==null)return r.failAndThrow("No group specified.");let n=e.groups??={},a=n[t];if(a==null){let o=n[t]??={generators:[]};await i(o,t)}else await i(a,t);return e}async function HZc({generatorName:e,generatorsConfiguration:t,groupName:r=t[jua],context:i,cliVersion:n}){let a=R2i(e,i),o=GZc(a),c=bto[a];return await DLh({generatorsConfiguration:t,groupName:r,context:i,update:async d=>{d.generators.some(s=>xQ(s.name)===a)&&i.failAndThrow(`${e} is already installed in group ${r}.`),d.generators.push({name:o,...c,version:await rxt({cliVersion:n,generatorName:a,context:i,channel:void 0})??c.version})}})}var ixt=require("fs/promises"),own=ue(require("path"),1);var f4h=require("buffer"),$Pu=ue(ILh(),1),GPu=ue(mB(),1),tVh=require("child_process"),FVh=ue($Zc(),1),JVh=require("path"),g_a=ue($Zc(),1),d3h=require("events"),h2c=Object.defineProperty,cAB=Object.getOwnPropertyDescriptor,y2c=Object.getOwnPropertyNames,lAB=Object.prototype.hasOwnProperty,za=(e,t)=>function(){return e&&(t=(0,e[y2c(e)[0]])(e=0)),t},fAB=(e,t)=>function(){return t||(0,e[y2c(e)[0]])((t={exports:{}}).exports,t),t.exports},jq=(e,t)=>{for(var r in t)h2c(e,r,{get:t[r],enumerable:!0})},dAB=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of y2c(t))!lAB.call(e,n)&&n!==r&&h2c(e,n,{get:()=>t[n],enumerable:!(i=cAB(t,n))||i.enumerable});return e},pC=e=>dAB(h2c({},"__esModule",{value:!0}),e);function pAB(...e){let t=new String(e);return KPu.set(t,e),t}function VPu(e){return e instanceof String&&KPu.has(e)}function CLh(e){return KPu.get(e)||[]}var KPu,mto=za({"src/lib/args/pathspec.ts"(){"use strict";KPu=new WeakMap}}),G3i,N2i=za({"src/lib/errors/git-error.ts"(){"use strict";G3i=class extends Error{constructor(e,t){super(t),this.task=e,Object.setPrototypeOf(this,new.target.prototype)}}}}),Ato,m_a=za({"src/lib/errors/git-response-error.ts"(){"use strict";N2i(),Ato=class extends G3i{constructor(e,t){super(void 0,t||String(e)),this.git=e}}}}),c4h,l4h=za({"src/lib/errors/task-configuration-error.ts"(){"use strict";N2i(),c4h=class extends G3i{constructor(e){super(void 0,e)}}}});function d4h(e){return typeof e!="function"?awn:e}function p4h(e){return typeof e=="function"&&e!==awn}function _4h(e,t){let r=e.indexOf(t);return r<=0?[e,""]:[e.substr(0,r),e.substr(r+1)]}function h4h(e,t=0){return y4h(e)&&e.length>t?e[t]:void 0}function nwn(e,t=0){if(y4h(e)&&e.length>t)return e[e.length-1-t]}function y4h(e){return ZPu(e)}function Pto(e="",t=!0,r=`
1399
1399
  `){return e.split(r).reduce((i,n)=>{let a=t?n.trim():n;return a&&i.push(a),i},[])}function b2c(e,t){return Pto(e,!0).map(r=>t(r))}function v2c(e){return(0,$Pu.exists)(e,$Pu.FOLDER)}function uP(e,t){return Array.isArray(e)?e.includes(t)||e.push(t):e.add(t),t}function b4h(e,t){return Array.isArray(e)&&!e.includes(t)&&e.push(t),e}function JPu(e,t){if(Array.isArray(e)){let r=e.indexOf(t);r>=0&&e.splice(r,1)}else e.delete(t);return t}function Ter(e){return Array.isArray(e)?e:[e]}function v4h(e){return e.replace(/[\s-]+(.)/g,(t,r)=>r.toUpperCase())}function A_a(e){return Ter(e).map(t=>t instanceof String?t:String(t))}function kE(e,t=0){if(e==null)return t;let r=parseInt(e,10);return Number.isNaN(r)?t:r}function gto(e,t){let r=[];for(let i=0,n=e.length;i<n;i++)r.push(t,e[i]);return r}function Oto(e){return(Array.isArray(e)?f4h.Buffer.concat(e):e).toString("utf-8")}function g4h(e,t){let r={};return t.forEach(i=>{e[i]!==void 0&&(r[i]=e[i])}),r}function t2c(e=0){return new Promise(t=>setTimeout(t,e))}function r2c(e){if(e!==!1)return e}var O_a,awn,jto,YPu=za({"src/lib/utils/util.ts"(){"use strict";g2c(),O_a="\0",awn=()=>{},jto=Object.prototype.toString.call.bind(Object.prototype.toString)}});function gme(e,t,r){return t(e)?e:arguments.length>2?r:void 0}function i2c(e,t){let r=VPu(e)?"string":typeof e;return/number|string|boolean/.test(r)&&(!t||!t.includes(r))}function XPu(e){return!!e&&jto(e)==="[object Object]"}function O4h(e){return typeof e=="function"}var wto,m4h,GQ,WPu,ZPu,g2c=za({"src/lib/utils/argument-filters.ts"(){"use strict";mto(),YPu(),wto=e=>Array.isArray(e),m4h=e=>typeof e=="number",GQ=e=>typeof e=="string",WPu=e=>GQ(e)||Array.isArray(e)&&e.every(GQ),ZPu=e=>e==null||"number|boolean|function".includes(typeof e)?!1:typeof e.length=="number"}}),n2c,_AB=za({"src/lib/utils/exit-codes.ts"(){"use strict";n2c=(e=>(e[e.SUCCESS=0]="SUCCESS",e[e.ERROR=1]="ERROR",e[e.NOT_FOUND=-2]="NOT_FOUND",e[e.UNCLEAN=128]="UNCLEAN",e))(n2c||{})}}),xPu,hAB=za({"src/lib/utils/git-output-streams.ts"(){"use strict";xPu=class A4h{constructor(t,r){this.stdOut=t,this.stdErr=r}asStrings(){return new A4h(this.stdOut.toString("utf8"),this.stdErr.toString("utf8"))}}}});function yAB(){throw new Error("LineParser:useMatches not implemented")}var Xp,z2i,bAB=za({"src/lib/utils/line-parser.ts"(){"use strict";Xp=class{constructor(e,t){this.matches=[],this.useMatches=yAB,this.parse=(r,i)=>(this.resetMatches(),this._regExp.every((n,a)=>this.addMatch(n,a,r(a)))?this.useMatches(i,this.prepareMatches())!==!1:!1),this._regExp=Array.isArray(e)?e:[e],t&&(this.useMatches=t)}resetMatches(){this.matches.length=0}prepareMatches(){return this.matches}addMatch(e,t,r){let i=r&&e.exec(r);return i&&this.pushMatch(t,i),!!i}pushMatch(e,t){this.matches.push(...t.slice(1))}},z2i=class extends Xp{addMatch(e,t,r){return/^remote:\s/.test(String(r))&&super.addMatch(e,t,r)}pushMatch(e,t){(e>0||t.length>1)&&super.pushMatch(e,t)}}}});function P4h(...e){let t=process.cwd(),r=Object.assign({baseDir:t,...j4h},...e.filter(i=>typeof i=="object"&&i));return r.baseDir=r.baseDir||t,r.trimmed=r.trimmed===!0,r}var j4h,vAB=za({"src/lib/utils/simple-git-options.ts"(){"use strict";j4h={binary:"git",maxConcurrentProcesses:5,config:[],trimmed:!1}}});function O2c(e,t=[]){return XPu(e)?Object.keys(e).reduce((r,i)=>{let n=e[i];if(VPu(n))r.push(n);else if(i2c(n,["boolean"]))r.push(i+"="+n);else if(Array.isArray(n))for(let a of n)i2c(a,["string","number"])||r.push(i+"="+a);else r.push(i);return r},t):t}function PZ(e,t=0,r=!1){let i=[];for(let n=0,a=t<0?e.length:t;n<a;n++)"string|number".includes(typeof e[n])&&i.push(String(e[n]));return O2c(m2c(e),i),r||i.push(...gAB(e)),i}function gAB(e){let t=typeof nwn(e)=="function";return A_a(gme(nwn(e,t?1:0),wto,[]))}function m2c(e){let t=O4h(nwn(e));return gme(nwn(e,t?1:0),XPu)}function _C(e,t=!0){let r=d4h(nwn(e));return t||p4h(r)?r:void 0}var OAB=za({"src/lib/utils/task-options.ts"(){"use strict";g2c(),YPu(),mto()}});function a2c(e,t){return e(t.stdOut,t.stdErr)}function wZ(e,t,r,i=!0){return Ter(r).forEach(n=>{for(let a=Pto(n,i),o=0,c=a.length;o<c;o++){let d=(s=0)=>{if(!(o+s>=c))return a[o+s]};t.some(({parse:s})=>s(d,e))}}),e}var mAB=za({"src/lib/utils/task-parser.ts"(){"use strict";YPu()}}),w4h={};jq(w4h,{ExitCodes:()=>n2c,GitOutputStreams:()=>xPu,LineParser:()=>Xp,NOOP:()=>awn,NULL:()=>O_a,RemoteLineParser:()=>z2i,append:()=>uP,appendTaskOptions:()=>O2c,asArray:()=>Ter,asCamelCase:()=>v4h,asFunction:()=>d4h,asNumber:()=>kE,asStringArray:()=>A_a,bufferToString:()=>Oto,callTaskParser:()=>a2c,createInstanceConfig:()=>P4h,delay:()=>t2c,filterArray:()=>wto,filterFunction:()=>O4h,filterHasLength:()=>ZPu,filterNumber:()=>m4h,filterPlainObject:()=>XPu,filterPrimitives:()=>i2c,filterString:()=>GQ,filterStringOrStringArray:()=>WPu,filterType:()=>gme,first:()=>h4h,folderExists:()=>v2c,forEachLineWithContent:()=>b2c,getTrailingOptions:()=>PZ,including:()=>b4h,isUserFunction:()=>p4h,last:()=>nwn,objectToString:()=>jto,orVoid:()=>r2c,parseStringResponse:()=>wZ,pick:()=>g4h,prefixedArray:()=>gto,remove:()=>JPu,splitOn:()=>_4h,toLinesWithContent:()=>Pto,trailingFunctionArgument:()=>_C,trailingOptionsArgument:()=>m2c});var wd=za({"src/lib/utils/index.ts"(){"use strict";g2c(),_AB(),hAB(),bAB(),vAB(),OAB(),mAB(),YPu()}}),E4h={};jq(E4h,{CheckRepoActions:()=>o2c,checkIsBareRepoTask:()=>M4h,checkIsRepoRootTask:()=>S4h,checkIsRepoTask:()=>AAB});function AAB(e){switch(e){case"bare":return M4h();case"root":return S4h()}return{commands:["rev-parse","--is-inside-work-tree"],format:"utf-8",onError:kPu,parser:A2c}}function S4h(){return{commands:["rev-parse","--git-dir"],format:"utf-8",onError:kPu,parser(t){return/^\.(git)?$/.test(t.trim())}}}function M4h(){return{commands:["rev-parse","--is-bare-repository"],format:"utf-8",onError:kPu,parser:A2c}}function PAB(e){return/(Not a git repository|Kein Git-Repository)/i.test(String(e))}var o2c,kPu,A2c,D4h=za({"src/lib/tasks/check-is-repo.ts"(){"use strict";wd(),o2c=(e=>(e.BARE="bare",e.IN_TREE="tree",e.IS_REPO_ROOT="root",e))(o2c||{}),kPu=({exitCode:e},t,r,i)=>{if(e===128&&PAB(t))return r(Buffer.from("false"));i(t)},A2c=e=>e.trim()==="true"}});function jAB(e,t){let r=new B4h(e),i=e?C4h:I4h;return Pto(t).forEach(n=>{let a=n.replace(i,"");r.paths.push(a),(q4h.test(a)?r.folders:r.files).push(a)}),r}var B4h,I4h,C4h,q4h,wAB=za({"src/lib/responses/CleanSummary.ts"(){"use strict";wd(),B4h=class{constructor(e){this.dryRun=e,this.paths=[],this.files=[],this.folders=[]}},I4h=/^[a-z]+\s*/i,C4h=/^[a-z]+\s+[a-z]+\s*/i,q4h=/\/$/}}),u2c={};jq(u2c,{EMPTY_COMMANDS:()=>eju,adhocExecTask:()=>T4h,configurationErrorTask:()=>jZ,isBufferTask:()=>z4h,isEmptyTask:()=>N4h,straightThroughBufferTask:()=>R4h,straightThroughStringTask:()=>r7});function T4h(e){return{commands:eju,format:"empty",parser:e}}function jZ(e){return{commands:eju,format:"empty",parser(){throw typeof e=="string"?new c4h(e):e}}}function r7(e,t=!1){return{commands:e,format:"utf-8",parser(r){return t?String(r).trim():r}}}function R4h(e){return{commands:e,format:"buffer",parser(t){return t}}}function z4h(e){return e.format==="buffer"}function N4h(e){return e.format==="empty"||!e.commands.length}var eju,Pq=za({"src/lib/tasks/task.ts"(){"use strict";l4h(),eju=[]}}),F4h={};jq(F4h,{CONFIG_ERROR_INTERACTIVE_MODE:()=>P2c,CONFIG_ERROR_MODE_REQUIRED:()=>j2c,CONFIG_ERROR_UNKNOWN_OPTION:()=>w2c,CleanOptions:()=>FPu,cleanTask:()=>Q4h,cleanWithOptionsTask:()=>EAB,isCleanOptionsArray:()=>SAB});function EAB(e,t){let{cleanMode:r,options:i,valid:n}=MAB(e);return r?n.options?(i.push(...t),i.some(IAB)?jZ(P2c):Q4h(r,i)):jZ(w2c+JSON.stringify(e)):jZ(j2c)}function Q4h(e,t){return{commands:["clean",`-${e}`,...t],format:"utf-8",parser(i){return jAB(e==="n",i)}}}function SAB(e){return Array.isArray(e)&&e.every(t=>E2c.has(t))}function MAB(e){let t,r=[],i={cleanMode:!1,options:!0};return e.replace(/[^a-z]i/g,"").split("").forEach(n=>{DAB(n)?(t=n,i.cleanMode=!0):i.options=i.options&&BAB(r[r.length]=`-${n}`)}),{cleanMode:t,options:r,valid:i}}function DAB(e){return e==="f"||e==="n"}function BAB(e){return/^-[a-z]$/i.test(e)&&E2c.has(e.charAt(1))}function IAB(e){return/^-[^\-]/.test(e)?e.indexOf("i")>0:e==="--interactive"}var P2c,j2c,w2c,FPu,E2c,U4h=za({"src/lib/tasks/clean.ts"(){"use strict";wAB(),wd(),Pq(),P2c="Git clean interactive mode is not supported",j2c='Git clean mode parameter ("n" or "f") is required',w2c="Git clean unknown option found in: ",FPu=(e=>(e.DRY_RUN="n",e.FORCE="f",e.IGNORED_INCLUDED="x",e.IGNORED_ONLY="X",e.EXCLUDING="e",e.QUIET="q",e.RECURSIVE="d",e))(FPu||{}),E2c=new Set(["i",...A_a(Object.values(FPu))])}});function CAB(e){let t=new V4h;for(let r of L4h(e))t.addValue(r.file,String(r.key),r.value);return t}function qAB(e,t){let r=null,i=[],n=new Map;for(let a of L4h(e,t))a.key===t&&(i.push(r=a.value),n.has(a.file)||n.set(a.file,[]),n.get(a.file).push(r));return{key:t,paths:Array.from(n.keys()),scopes:n,value:r,values:i}}function TAB(e){return e.replace(/^(file):/,"")}function*L4h(e,t=null){let r=e.split("\0");for(let i=0,n=r.length-1;i<n;){let a=TAB(r[i++]),o=r[i++],c=t;if(o.includes(`
1400
1400
  `)){let d=_4h(o,`
1401
1401
  `);c=d[0],o=d[1]}yield{file:a,key:c,value:o}}}var V4h,RAB=za({"src/lib/responses/ConfigList.ts"(){"use strict";wd(),V4h=class{constructor(){this.files=[],this.values=Object.create(null)}get all(){return this._all||(this._all=this.files.reduce((e,t)=>Object.assign(e,this.values[t]),{})),this._all}addFile(e){if(!(e in this.values)){let t=nwn(this.files);this.values[e]=t?Object.create(this.values[t]):{},this.files.push(e)}return this.values[e]}addValue(e,t,r){let i=this.addFile(e);Object.hasOwn(i,t)?Array.isArray(i[t])?i[t].push(r):i[t]=[i[t],r]:i[t]=r,this._all=void 0}}}});function JZc(e,t){return typeof e=="string"&&Object.hasOwn(s2c,e)?e:t}function zAB(e,t,r,i){let n=["config",`--${i}`];return r&&n.push("--add"),n.push(e,t),{commands:n,format:"utf-8",parser(a){return a}}}function NAB(e,t){let r=["config","--null","--show-origin","--get-all",e];return t&&r.splice(1,0,`--${t}`),{commands:r,format:"utf-8",parser(i){return qAB(i,e)}}}function FAB(e){let t=["config","--list","--show-origin","--null"];return e&&t.push(`--${e}`),{commands:t,format:"utf-8",parser(r){return CAB(r)}}}function QAB(){return{addConfig(e,t,...r){return this._runTask(zAB(e,t,r[0]===!0,JZc(r[1],"local")),_C(arguments))},getConfig(e,t){return this._runTask(NAB(e,JZc(t,void 0)),_C(arguments))},listConfig(...e){return this._runTask(FAB(JZc(e[0],void 0)),_C(arguments))}}}var s2c,W4h=za({"src/lib/tasks/config.ts"(){"use strict";RAB(),wd(),s2c=(e=>(e.system="system",e.global="global",e.local="local",e.worktree="worktree",e))(s2c||{})}});function UAB(e){return x4h.has(e)}var YZc,x4h,G4h=za({"src/lib/tasks/diff-name-status.ts"(){"use strict";YZc=(e=>(e.ADDED="A",e.COPIED="C",e.DELETED="D",e.MODIFIED="M",e.RENAMED="R",e.CHANGED="T",e.UNMERGED="U",e.UNKNOWN="X",e.BROKEN="B",e))(YZc||{}),x4h=new Set(Object.values(YZc))}});function LAB(...e){return new K4h().param(...e)}function VAB(e){let t=new Set,r={};return b2c(e,i=>{let[n,a,o]=i.split(O_a);t.add(n),(r[n]=r[n]||[]).push({line:kE(a),path:n,preview:o})}),{paths:t,results:r}}function WAB(){return{grep(e){let t=_C(arguments),r=PZ(arguments);for(let n of H4h)if(r.includes(n))return this._runTask(jZ(`git.grep: use of "${n}" is not supported.`),t);typeof e=="string"&&(e=LAB().param(e));let i=["grep","--null","-n","--full-name",...r,...e];return this._runTask({commands:i,format:"utf-8",parser(n){return VAB(n)}},t)}}}var H4h,vto,qLh,K4h,$4h=za({"src/lib/tasks/grep.ts"(){"use strict";wd(),Pq(),H4h=["-h"],vto=Symbol("grepQuery"),K4h=class{constructor(){this[qLh]=[]}*[(qLh=vto,Symbol.iterator)](){for(let e of this[vto])yield e}and(...e){return e.length&&this[vto].push("--and","(",...gto(e,"-e"),")"),this}param(...e){return this[vto].push(...gto(e,"-e")),this}}}}),J4h={};jq(J4h,{ResetMode:()=>QPu,getResetMode:()=>GAB,resetTask:()=>xAB});function xAB(e,t){let r=["reset"];return Y4h(e)&&r.push(`--${e}`),r.push(...t),r7(r)}function GAB(e){if(Y4h(e))return e;switch(typeof e){case"string":case"undefined":return"soft"}}function Y4h(e){return typeof e=="string"&&X4h.includes(e)}var QPu,X4h,Z4h=za({"src/lib/tasks/reset.ts"(){"use strict";wd(),Pq(),QPu=(e=>(e.MIXED="mixed",e.SOFT="soft",e.HARD="hard",e.MERGE="merge",e.KEEP="keep",e))(QPu||{}),X4h=A_a(Object.values(QPu))}});function HAB(){return(0,GPu.default)("simple-git")}function TLh(e,t,r){return!t||!String(t).replace(/\s*/,"")?r?(i,...n)=>{e(i,...n),r(i,...n)}:e:(i,...n)=>{e(`%s ${i}`,t,...n),r&&r(i,...n)}}function KAB(e,t,{namespace:r}){if(typeof e=="string")return e;let i=t&&t.namespace||"";return i.startsWith(r)?i.substr(r.length+1):i||r}function S2c(e,t,r,i=HAB()){let n=e&&`[${e}]`||"",a=[],o=typeof t=="string"?i.extend(t):t,c=KAB(gme(t,GQ),o,i);return s(r);function d(u,f){return uP(a,S2c(e,c.replace(/^[^:]+/,u),f,i))}function s(u){let f=u&&`[${u}]`||"",p=o&&TLh(o,f)||awn,_=TLh(i,`${n} ${f}`,p);return Object.assign(o?p:_,{label:e,sibling:d,info:_,step:s})}}var k4h=za({"src/lib/git-logger.ts"(){"use strict";wd(),GPu.default.formatters.L=e=>String(ZPu(e)?e.length:"-"),GPu.default.formatters.B=e=>Buffer.isBuffer(e)?e.toString("utf8"):jto(e)}}),eVh,$AB=za({"src/lib/runners/tasks-pending-queue.ts"(){"use strict";N2i(),k4h(),eVh=class c2c{constructor(t="GitExecutor"){this.logLabel=t,this._queue=new Map}withProgress(t){return this._queue.get(t)}createProgress(t){let r=c2c.getName(t.commands[0]),i=S2c(this.logLabel,r);return{task:t,logger:i,name:r}}push(t){let r=this.createProgress(t);return r.logger("Adding task to the queue, commands = %o",t.commands),this._queue.set(t,r),r}fatal(t){for(let[r,{logger:i}]of Array.from(this._queue.entries()))r===t.task?(i.info("Failed %o",t),i("Fatal exception, any as-yet un-started tasks run through this executor will not be attempted")):i.info("A fatal exception occurred in a previous task, the queue has been purged: %o",t.message),this.complete(r);if(this._queue.size!==0)throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(t){this.withProgress(t)&&this._queue.delete(t)}attempt(t){let r=this.withProgress(t);if(!r)throw new G3i(void 0,"TasksPendingQueue: attempt called for an unknown task");return r.logger("Starting task"),r}static getName(t="empty"){return`task:${t}:${++c2c.counter}`}static{this.counter=0}}}});function iwn(e,t){return{method:h4h(e.commands)||"",commands:t}}function JAB(e,t){return r=>{t("[ERROR] child process exception %o",r),e.push(Buffer.from(String(r.stack),"ascii"))}}function RLh(e,t,r,i){return n=>{r("%s received %L bytes",t,n),i("%B",n),e.push(n)}}var l2c,YAB=za({"src/lib/runners/git-executor-chain.ts"(){"use strict";N2i(),Pq(),wd(),$AB(),l2c=class{constructor(e,t,r){this._executor=e,this._scheduler=t,this._plugins=r,this._chain=Promise.resolve(),this._queue=new eVh}get cwd(){return this._cwd||this._executor.cwd}set cwd(e){this._cwd=e}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(e){return this._queue.push(e),this._chain=this._chain.then(()=>this.attemptTask(e))}async attemptTask(e){let t=await this._scheduler.next(),r=()=>this._queue.complete(e);try{let{logger:i}=this._queue.attempt(e);return await(N4h(e)?this.attemptEmptyTask(e,i):this.attemptRemoteTask(e,i))}catch(i){throw this.onFatalException(e,i)}finally{r(),t()}}onFatalException(e,t){let r=t instanceof G3i?Object.assign(t,{task:e}):new G3i(e,t&&String(t));return this._chain=Promise.resolve(),this._queue.fatal(r),r}async attemptRemoteTask(e,t){let r=this._plugins.exec("spawn.binary","",iwn(e,e.commands)),i=this._plugins.exec("spawn.args",[...e.commands],iwn(e,e.commands)),n=await this.gitResponse(e,r,i,this.outputHandler,t.step("SPAWN")),a=await this.handleTaskData(e,i,n,t.step("HANDLE"));return t("passing response to task's parser as a %s",e.format),z4h(e)?a2c(e.parser,a):a2c(e.parser,a.asStrings())}async attemptEmptyTask(e,t){return t("empty task bypassing child process to call to task's parser"),e.parser(this)}handleTaskData(e,t,r,i){let{exitCode:n,rejection:a,stdOut:o,stdErr:c}=r;return new Promise((d,s)=>{i("Preparing to handle process response exitCode=%d stdOut=",n);let{error:u}=this._plugins.exec("task.error",{error:a},{...iwn(e,t),...r});if(u&&e.onError)return i.info("exitCode=%s handling with custom error handler"),e.onError(r,u,f=>{i.info("custom error handler treated as success"),i("custom error returned a %s",jto(f)),d(new xPu(Array.isArray(f)?Buffer.concat(f):f,Buffer.concat(c)))},s);if(u)return i.info("handling as error: exitCode=%s stdErr=%s rejection=%o",n,c.length,a),s(u);i.info("retrieving task output complete"),d(new xPu(Buffer.concat(o),Buffer.concat(c)))})}async gitResponse(e,t,r,i,n){let a=n.sibling("output"),o=this._plugins.exec("spawn.options",{cwd:this.cwd,env:this.env,windowsHide:!0},iwn(e,e.commands));return new Promise(c=>{let d=[],s=[];n.info("%s %o",t,r),n("%O",o);let u=this._beforeSpawn(e,r);if(u)return c({stdOut:d,stdErr:s,exitCode:9901,rejection:u});this._plugins.exec("spawn.before",void 0,{...iwn(e,r),kill(p){u=p||u}});let f=(0,tVh.spawn)(t,r,o);f.stdout.on("data",RLh(d,"stdOut",n,a.step("stdOut"))),f.stderr.on("data",RLh(s,"stdErr",n,a.step("stdErr"))),f.on("error",JAB(s,n)),i&&(n("Passing child process stdOut/stdErr to custom outputHandler"),i(t,f.stdout,f.stderr,[...r])),this._plugins.exec("spawn.after",void 0,{...iwn(e,r),spawned:f,close(p,_){c({stdOut:d,stdErr:s,exitCode:p,rejection:u||_})},kill(p){f.killed||(u=p,f.kill("SIGINT"))}})})}_beforeSpawn(e,t){let r;return this._plugins.exec("spawn.before",void 0,{...iwn(e,t),kill(i){r=i||r}}),r}}}}),rVh={};jq(rVh,{GitExecutor:()=>iVh});var iVh,XAB=za({"src/lib/runners/git-executor.ts"(){"use strict";YAB(),iVh=class{constructor(e,t,r){this.cwd=e,this._scheduler=t,this._plugins=r,this._chain=new l2c(this,this._scheduler,this._plugins)}chain(){return new l2c(this,this._scheduler,this._plugins)}push(e){return this._chain.push(e)}}}});function ZAB(e,t,r=awn){let i=a=>{r(null,a)},n=a=>{a?.task===e&&r(a instanceof Ato?kAB(a):a,void 0)};t.then(i,n)}function kAB(e){let t=i=>{console.warn(`simple-git deprecation notice: accessing GitResponseError.${i} should be GitResponseError.git.${i}, this will no longer be available in version 3`),t=awn};return Object.create(e,Object.getOwnPropertyNames(e.git).reduce(r,{}));function r(i,n){return n in e||(i[n]={enumerable:!1,configurable:!1,get(){return t(n),e.git[n]}}),i}}var ePB=za({"src/lib/task-callback.ts"(){"use strict";m_a(),wd()}});function zLh(e,t){return T4h(r=>{if(!v2c(e))throw new Error(`Git.cwd: cannot change to non-directory "${e}"`);return(t||r).cwd=e})}var tPB=za({"src/lib/tasks/change-working-directory.ts"(){"use strict";wd(),Pq()}});function XZc(e){let t=["checkout",...e];return t[1]==="-b"&&t.includes("-B")&&(t[1]=JPu(t,"-B")),r7(t)}function rPB(){return{checkout(){return this._runTask(XZc(PZ(arguments,1)),_C(arguments))},checkoutBranch(e,t){return this._runTask(XZc(["-b",e,t,...PZ(arguments)]),_C(arguments))},checkoutLocalBranch(e){return this._runTask(XZc(["-b",e,...PZ(arguments)]),_C(arguments))}}}var iPB=za({"src/lib/tasks/checkout.ts"(){"use strict";wd(),Pq()}});function nPB(){return{count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}function aPB(){return{countObjects(){return this._runTask({commands:["count-objects","--verbose"],format:"utf-8",parser(e){return wZ(nPB(),[nVh],e)}})}}}var nVh,oPB=za({"src/lib/tasks/count-objects.ts"(){"use strict";wd(),nVh=new Xp(/([a-z-]+): (\d+)$/,(e,[t,r])=>{let i=v4h(t);Object.hasOwn(e,i)&&(e[i]=kE(r))})}});function uPB(e){return wZ({author:null,branch:"",commit:"",root:!1,summary:{changes:0,insertions:0,deletions:0}},aVh,e)}var aVh,sPB=za({"src/lib/parsers/parse-commit.ts"(){"use strict";wd(),aVh=[new Xp(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(e,[t,r,i])=>{e.branch=t,e.commit=i,e.root=!!r}),new Xp(/\s*Author:\s(.+)/i,(e,[t])=>{let r=t.split("<"),i=r.pop();!i||!i.includes("@")||(e.author={email:i.substr(0,i.length-1),name:r.join("<").trim()})}),new Xp(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(e,[t,r,i])=>{e.summary.changes=parseInt(t,10)||0,e.summary.insertions=parseInt(r,10)||0,e.summary.deletions=parseInt(i,10)||0}),new Xp(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(e,[t,r,i])=>{e.summary.changes=parseInt(t,10)||0;let n=parseInt(r,10)||0;i==="-"?e.summary.deletions=n:i==="+"&&(e.summary.insertions=n)})]}});function cPB(e,t,r){return{commands:["-c","core.abbrev=40","commit",...gto(e,"-m"),...t,...r],format:"utf-8",parser:uPB}}function lPB(){return{commit(t,...r){let i=_C(arguments),n=e(t)||cPB(Ter(t),Ter(gme(r[0],WPu,[])),[...A_a(gme(r[1],wto,[])),...PZ(arguments,0,!0)]);return this._runTask(n,i)}};function e(t){return!WPu(t)&&jZ("git.commit: requires the commit message to be supplied as a string/string[]")}}var fPB=za({"src/lib/tasks/commit.ts"(){"use strict";sPB(),wd(),Pq()}});function dPB(){return{firstCommit(){return this._runTask(r7(["rev-list","--max-parents=0","HEAD"],!0),_C(arguments))}}}var pPB=za({"src/lib/tasks/first-commit.ts"(){"use strict";wd(),Pq()}});function _PB(e,t){let r=["hash-object",e];return t&&r.push("-w"),r7(r,!0)}var hPB=za({"src/lib/tasks/hash-object.ts"(){"use strict";Pq()}});function yPB(e,t,r){let i=String(r).trim(),n;if(n=oVh.exec(i))return new UPu(e,t,!1,n[1]);if(n=uVh.exec(i))return new UPu(e,t,!0,n[1]);let a="",o=i.split(" ");for(;o.length;)if(o.shift()==="in"){a=o.join(" ");break}return new UPu(e,t,/^re/i.test(i),a)}var UPu,oVh,uVh,bPB=za({"src/lib/responses/InitSummary.ts"(){"use strict";UPu=class{constructor(e,t,r,i){this.bare=e,this.path=t,this.existing=r,this.gitDir=i}},oVh=/^Init.+ repository in (.+)$/,uVh=/^Rein.+ in (.+)$/}});function vPB(e){return e.includes(M2c)}function gPB(e=!1,t,r){let i=["init",...r];return e&&!vPB(i)&&i.splice(1,0,M2c),{commands:i,format:"utf-8",parser(n){return yPB(i.includes("--bare"),t,n)}}}var M2c,OPB=za({"src/lib/tasks/init.ts"(){"use strict";bPB(),M2c="--bare"}});function D2c(e){for(let t=0;t<e.length;t++){let r=B2c.exec(e[t]);if(r)return`--${r[1]}`}return""}function mPB(e){return B2c.test(e)}var B2c,Eto=za({"src/lib/args/log-format.ts"(){"use strict";B2c=/^--(stat|numstat|name-only|name-status)(=|$)/}}),sVh,APB=za({"src/lib/responses/DiffSummary.ts"(){"use strict";sVh=class{constructor(){this.changed=0,this.deletions=0,this.insertions=0,this.files=[]}}}});function cVh(e=""){let t=lVh[e];return r=>wZ(new sVh,t,r,!1)}var ZZc,NLh,FLh,QLh,lVh,fVh=za({"src/lib/parsers/parse-diff-summary.ts"(){"use strict";Eto(),APB(),G4h(),wd(),ZZc=[new Xp(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(e,[t,r,i=""])=>{e.files.push({file:t.trim(),changes:kE(r),insertions:i.replace(/[^+]/g,"").length,deletions:i.replace(/[^-]/g,"").length,binary:!1})}),new Xp(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(e,[t,r,i])=>{e.files.push({file:t.trim(),before:kE(r),after:kE(i),binary:!0})}),new Xp(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(e,[t,r])=>{let i=/(\d+) i/.exec(r),n=/(\d+) d/.exec(r);e.changed=kE(t),e.insertions=kE(i?.[1]),e.deletions=kE(n?.[1])})],NLh=[new Xp(/(\d+)\t(\d+)\t(.+)$/,(e,[t,r,i])=>{let n=kE(t),a=kE(r);e.changed++,e.insertions+=n,e.deletions+=a,e.files.push({file:i,changes:n+a,insertions:n,deletions:a,binary:!1})}),new Xp(/-\t-\t(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,after:0,before:0,binary:!0})})],FLh=[new Xp(/(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,changes:0,insertions:0,deletions:0,binary:!1})})],QLh=[new Xp(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(e,[t,r,i,n,a])=>{e.changed++,e.files.push({file:a??i,changes:0,insertions:0,deletions:0,binary:!1,status:r2c(UAB(t)&&t),from:r2c(!!a&&i!==a&&i),similarity:kE(r)})})],lVh={"":ZZc,"--stat":ZZc,"--numstat":NLh,"--name-status":QLh,"--name-only":FLh}}});function PPB(e,t){return t.reduce((r,i,n)=>(r[i]=e[n]||"",r),Object.create({diff:null}))}function dVh(e=q2c,t=pVh,r=""){let i=cVh(r);return function(n){let a=Pto(n.trim(),!1,I2c).map(function(o){let c=o.split(C2c),d=PPB(c[0].split(e),t);return c.length>1&&c[1].trim()&&(d.diff=i(c[1])),d});return{all:a,latest:a.length&&a[0]||null,total:a.length}}}var I2c,C2c,q2c,pVh,_Vh=za({"src/lib/parsers/parse-list-log-summary.ts"(){"use strict";wd(),fVh(),Eto(),I2c="\xF2\xF2\xF2\xF2\xF2\xF2 ",C2c=" \xF2\xF2",q2c=" \xF2 ",pVh=["hash","date","message","refs","author_name","author_email"]}}),hVh={};jq(hVh,{diffSummaryTask:()=>jPB,validateLogFormatConfig:()=>tju});function jPB(e){let t=D2c(e),r=["diff"];return t===""&&(t="--stat",r.push("--stat=4096")),r.push(...e),tju(r)||{commands:r,format:"utf-8",parser:cVh(t)}}function tju(e){let t=e.filter(mPB);if(t.length>1)return jZ(`Summary flags are mutually exclusive - pick one of ${t.join(",")}`);if(t.length&&e.includes("-z"))return jZ(`Summary flag ${t} parsing is not compatible with null termination option '-z'`)}var T2c=za({"src/lib/tasks/diff.ts"(){"use strict";Eto(),fVh(),Pq()}});function wPB(e,t){let r=[],i=[];return Object.keys(e).forEach(n=>{r.push(n),i.push(String(e[n]))}),[r,i.join(t)]}function EPB(e){return Object.keys(e).reduce((t,r)=>(r in f2c||(t[r]=e[r]),t),{})}function yVh(e={},t=[]){let r=gme(e.splitter,GQ,q2c),i=XPu(e.format)?e.format:{hash:"%H",date:e.strictDate===!1?"%ai":"%aI",message:"%s",refs:"%D",body:e.multiLine?"%B":"%b",author_name:e.mailMap!==!1?"%aN":"%an",author_email:e.mailMap!==!1?"%aE":"%ae"},[n,a]=wPB(i,r),o=[],c=[`--pretty=format:${I2c}${a}${C2c}`,...t],d=e.n||e["max-count"]||e.maxCount;if(d&&c.push(`--max-count=${d}`),e.from||e.to){let s=e.symmetric!==!1?"...":"..";o.push(`${e.from||""}${s}${e.to||""}`)}return GQ(e.file)&&c.push("--follow",pAB(e.file)),O2c(EPB(e),c),{fields:n,splitter:r,commands:[...c,...o]}}function SPB(e,t,r){let i=dVh(e,t,D2c(r));return{commands:["log",...r],format:"utf-8",parser:i}}function MPB(){return{log(...r){let i=_C(arguments),n=yVh(m2c(arguments),A_a(gme(arguments[0],wto,[]))),a=t(...r)||tju(n.commands)||e(n);return this._runTask(a,i)}};function e(r){return SPB(r.splitter,r.fields,r.commands)}function t(r,i){return GQ(r)&&GQ(i)&&jZ("git.log(string, string) should be replaced with git.log({ from: string, to: string })")}}var f2c,bVh=za({"src/lib/tasks/log.ts"(){"use strict";Eto(),mto(),_Vh(),wd(),Pq(),T2c(),f2c=(e=>(e[e["--pretty"]=0]="--pretty",e[e["max-count"]=1]="max-count",e[e.maxCount=2]="maxCount",e[e.n=3]="n",e[e.file=4]="file",e[e.format=5]="format",e[e.from=6]="from",e[e.to=7]="to",e[e.splitter=8]="splitter",e[e.symmetric=9]="symmetric",e[e.mailMap=10]="mailMap",e[e.multiLine=11]="multiLine",e[e.strictDate=12]="strictDate",e))(f2c||{})}}),LPu,vVh,DPB=za({"src/lib/responses/MergeSummary.ts"(){"use strict";LPu=class{constructor(e,t=null,r){this.reason=e,this.file=t,this.meta=r}toString(){return`${this.file}:${this.reason}`}},vVh=class{constructor(){this.conflicts=[],this.merges=[],this.result="success"}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){return this.conflicts.length?`CONFLICTS: ${this.conflicts.join(", ")}`:"OK"}}}}),d2c,gVh,BPB=za({"src/lib/responses/PullSummary.ts"(){"use strict";d2c=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0}}},gVh=class{constructor(){this.remote="",this.hash={local:"",remote:""},this.branch={local:"",remote:""},this.message=""}toString(){return this.message}}}});function kZc(e){return e.objects=e.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function ULh(e){let t=/^\s*(\d+)/.exec(e),r=/delta (\d+)/i.exec(e);return{count:kE(t&&t[1]||"0"),delta:kE(r&&r[1]||"0")}}var OVh,IPB=za({"src/lib/parsers/parse-remote-objects.ts"(){"use strict";wd(),OVh=[new z2i(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(e,[t,r])=>{let i=t.toLowerCase(),n=kZc(e.remoteMessages);Object.assign(n,{[i]:kE(r)})}),new z2i(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(e,[t,r])=>{let i=t.toLowerCase(),n=kZc(e.remoteMessages);Object.assign(n,{[i]:kE(r)})}),new z2i(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(e,[t,r,i])=>{let n=kZc(e.remoteMessages);n.total=ULh(t),n.reused=ULh(r),n.packReused=kE(i)})]}});function mVh(e,t){return wZ({remoteMessages:new PVh},AVh,t)}var AVh,PVh,jVh=za({"src/lib/parsers/parse-remote-messages.ts"(){"use strict";wd(),IPB(),AVh=[new z2i(/^remote:\s*(.+)$/,(e,[t])=>(e.remoteMessages.all.push(t.trim()),!1)),...OVh,new z2i([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(e,[t])=>{e.remoteMessages.pullRequestUrl=t}),new z2i([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(e,[t,r,i])=>{e.remoteMessages.vulnerabilities={count:kE(t),summary:r,url:i}})],PVh=class{constructor(){this.all=[]}}}});function CPB(e,t){let r=wZ(new gVh,wVh,[e,t]);return r.message&&r}var LLh,VLh,WLh,xLh,wVh,GLh,R2c,EVh=za({"src/lib/parsers/parse-pull.ts"(){"use strict";BPB(),wd(),jVh(),LLh=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,VLh=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,WLh=/^(create|delete) mode \d+ (.+)/,xLh=[new Xp(LLh,(e,[t,r,i])=>{e.files.push(t),r&&(e.insertions[t]=r.length),i&&(e.deletions[t]=i.length)}),new Xp(VLh,(e,[t,,r,,i])=>r!==void 0||i!==void 0?(e.summary.changes=+t||0,e.summary.insertions=+r||0,e.summary.deletions=+i||0,!0):!1),new Xp(WLh,(e,[t,r])=>{uP(e.files,r),uP(t==="create"?e.created:e.deleted,r)})],wVh=[new Xp(/^from\s(.+)$/i,(e,[t])=>void(e.remote=t)),new Xp(/^fatal:\s(.+)$/,(e,[t])=>void(e.message=t)),new Xp(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(e,[t,r,i,n])=>{e.branch.local=i,e.hash.local=t,e.branch.remote=n,e.hash.remote=r})],GLh=(e,t)=>wZ(new d2c,xLh,[e,t]),R2c=(e,t)=>Object.assign(new d2c,GLh(e,t),mVh(e,t))}}),HLh,SVh,KLh,qPB=za({"src/lib/parsers/parse-merge.ts"(){"use strict";DPB(),wd(),EVh(),HLh=[new Xp(/^Auto-merging\s+(.+)$/,(e,[t])=>{e.merges.push(t)}),new Xp(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(e,[t,r])=>{e.conflicts.push(new LPu(t,r))}),new Xp(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(e,[t,r,i])=>{e.conflicts.push(new LPu(t,r,{deleteRef:i}))}),new Xp(/^CONFLICT\s+\((.+)\):/,(e,[t])=>{e.conflicts.push(new LPu(t,null))}),new Xp(/^Automatic merge failed;\s+(.+)$/,(e,[t])=>{e.result=t})],SVh=(e,t)=>Object.assign(KLh(e,t),R2c(e,t)),KLh=e=>wZ(new vVh,HLh,e)}});function $Lh(e){return e.length?{commands:["merge",...e],format:"utf-8",parser(t,r){let i=SVh(t,r);if(i.failed)throw new Ato(i);return i}}:jZ("Git.merge requires at least one option")}var TPB=za({"src/lib/tasks/merge.ts"(){"use strict";m_a(),qPB(),Pq()}});function RPB(e,t,r){let i=r.includes("deleted"),n=r.includes("tag")||/^refs\/tags/.test(e),a=!r.includes("new");return{deleted:i,tag:n,branch:!n,new:!a,alreadyUpdated:a,local:e,remote:t}}var JLh,MVh,YLh,zPB=za({"src/lib/parsers/parse-push.ts"(){"use strict";wd(),jVh(),JLh=[new Xp(/^Pushing to (.+)$/,(e,[t])=>{e.repo=t}),new Xp(/^updating local tracking ref '(.+)'/,(e,[t])=>{e.ref={...e.ref||{},local:t}}),new Xp(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(e,[t,r,i])=>{e.pushed.push(RPB(t,r,i))}),new Xp(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(e,[t,r,i])=>{e.branch={...e.branch||{},local:t,remote:r,remoteName:i}}),new Xp(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(e,[t,r,i,n])=>{e.update={head:{local:t,remote:r},hash:{from:i,to:n}}})],MVh=(e,t)=>{let r=YLh(e,t),i=mVh(e,t);return{...r,...i}},YLh=(e,t)=>wZ({pushed:[]},JLh,[e,t])}}),DVh={};jq(DVh,{pushTagsTask:()=>NPB,pushTask:()=>z2c});function NPB(e={},t){return uP(t,"--tags"),z2c(e,t)}function z2c(e={},t){let r=["push",...t];return e.branch&&r.splice(1,0,e.branch),e.remote&&r.splice(1,0,e.remote),JPu(r,"-v"),uP(r,"--verbose"),uP(r,"--porcelain"),{commands:r,format:"utf-8",parser:MVh}}var BVh=za({"src/lib/tasks/push.ts"(){"use strict";zPB(),wd()}});function FPB(){return{showBuffer(){let e=["show",...PZ(arguments,1)];return e.includes("--binary")||e.splice(1,0,"--binary"),this._runTask(R4h(e),_C(arguments))},show(){let e=["show",...PZ(arguments,1)];return this._runTask(r7(e),_C(arguments))}}}var QPB=za({"src/lib/tasks/show.ts"(){"use strict";wd(),Pq()}}),XLh,IVh,UPB=za({"src/lib/responses/FileStatusSummary.ts"(){"use strict";XLh=/^(.+)\0(.+)$/,IVh=class{constructor(e,t,r){if(this.path=e,this.index=t,this.working_dir=r,t==="R"||r==="R"){let i=XLh.exec(e)||[null,e,e];this.from=i[2]||"",this.path=i[1]||""}}}}});function ZLh(e){let[t,r]=e.split(O_a);return{from:r||t,to:t}}function vme(e,t,r){return[`${e}${t}`,r]}function e2c(e,...t){return t.map(r=>vme(e,r,(i,n)=>uP(i.conflicted,n)))}function LPB(e,t){let r=t.trim();switch(" "){case r.charAt(2):return i(r.charAt(0),r.charAt(1),r.substr(3));case r.charAt(1):return i(" ",r.charAt(0),r.substr(2));default:return}function i(n,a,o){let c=`${n}${a}`,d=CVh.get(c);d&&d(e,o),c!=="##"&&c!=="!!"&&e.files.push(new IVh(o,n,a))}}var kLh,CVh,qVh,VPB=za({"src/lib/responses/StatusSummary.ts"(){"use strict";wd(),UPB(),kLh=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=!1,this.isClean=()=>!this.files.length}},CVh=new Map([vme(" ","A",(e,t)=>uP(e.created,t)),vme(" ","D",(e,t)=>uP(e.deleted,t)),vme(" ","M",(e,t)=>uP(e.modified,t)),vme("A"," ",(e,t)=>uP(e.created,t)&&uP(e.staged,t)),vme("A","M",(e,t)=>uP(e.created,t)&&uP(e.staged,t)&&uP(e.modified,t)),vme("D"," ",(e,t)=>uP(e.deleted,t)&&uP(e.staged,t)),vme("M"," ",(e,t)=>uP(e.modified,t)&&uP(e.staged,t)),vme("M","M",(e,t)=>uP(e.modified,t)&&uP(e.staged,t)),vme("R"," ",(e,t)=>{uP(e.renamed,ZLh(t))}),vme("R","M",(e,t)=>{let r=ZLh(t);uP(e.renamed,r),uP(e.modified,r.to)}),vme("!","!",(e,t)=>{uP(e.ignored=e.ignored||[],t)}),vme("?","?",(e,t)=>uP(e.not_added,t)),...e2c("A","A","U"),...e2c("D","D","U"),...e2c("U","A","D","U"),["##",(e,t)=>{let r=/ahead (\d+)/,i=/behind (\d+)/,n=/^(.+?(?=(?:\.{3}|\s|$)))/,a=/\.{3}(\S*)/,o=/\son\s(\S+?)(?=\.{3}|$)/,c=r.exec(t);e.ahead=c&&+c[1]||0,c=i.exec(t),e.behind=c&&+c[1]||0,c=n.exec(t),e.current=gme(c?.[1],GQ,null),c=a.exec(t),e.tracking=gme(c?.[1],GQ,null),c=o.exec(t),c&&(e.current=gme(c?.[1],GQ,e.current)),e.detached=/\(no branch\)/.test(t)}]]),qVh=function(e){let t=e.split(O_a),r=new kLh;for(let i=0,n=t.length;i<n;){let a=t[i++].trim();a&&(a.charAt(0)==="R"&&(a+=O_a+(t[i++]||"")),LPB(r,a))}return r}}});function WPB(e){return{format:"utf-8",commands:["status","--porcelain","-b","-u","--null",...e.filter(r=>!TVh.includes(r))],parser(r){return qVh(r)}}}var TVh,xPB=za({"src/lib/tasks/status.ts"(){"use strict";VPB(),TVh=["--null","-z"]}});function HPu(e=0,t=0,r=0,i="",n=!0){return Object.defineProperty({major:e,minor:t,patch:r,agent:i,installed:n},"toString",{value(){return`${this.major}.${this.minor}.${this.patch}`},configurable:!1,enumerable:!1})}function GPB(){return HPu(0,0,0,"",!1)}function HPB(){return{version(){return this._runTask({commands:["--version"],format:"utf-8",parser:KPB,onError(e,t,r,i){if(e.exitCode===-2)return r(Buffer.from(N2c));i(t)}})}}}function KPB(e){return e===N2c?GPB():wZ(HPu(0,0,0,e),RVh,e)}var N2c,RVh,$PB=za({"src/lib/tasks/version.ts"(){"use strict";wd(),N2c="installed=false",RVh=[new Xp(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(e,[t,r,i,n=""])=>{Object.assign(e,HPu(kE(t),kE(r),kE(i),n))}),new Xp(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(e,[t,r,i,n=""])=>{Object.assign(e,HPu(kE(t),kE(r),i,n))})]}}),zVh={};jq(zVh,{SimpleGitApi:()=>p2c});var p2c,JPB=za({"src/lib/simple-git-api.ts"(){"use strict";ePB(),tPB(),iPB(),oPB(),fPB(),W4h(),pPB(),$4h(),hPB(),OPB(),bVh(),TPB(),BVh(),QPB(),xPB(),Pq(),$PB(),wd(),p2c=class{constructor(e){this._executor=e}_runTask(e,t){let r=this._executor.chain(),i=r.push(e);return t&&ZAB(e,i,t),Object.create(this,{then:{value:i.then.bind(i)},catch:{value:i.catch.bind(i)},_executor:{value:r}})}add(e){return this._runTask(r7(["add",...Ter(e)]),_C(arguments))}cwd(e){let t=_C(arguments);return typeof e=="string"?this._runTask(zLh(e,this._executor),t):typeof e?.path=="string"?this._runTask(zLh(e.path,e.root&&this._executor||void 0),t):this._runTask(jZ("Git.cwd: workingDirectory must be supplied as a string"),t)}hashObject(e,t){return this._runTask(_PB(e,t===!0),_C(arguments))}init(e){return this._runTask(gPB(e===!0,this._executor.cwd,PZ(arguments)),_C(arguments))}merge(){return this._runTask($Lh(PZ(arguments)),_C(arguments))}mergeFromTo(e,t){return GQ(e)&&GQ(t)?this._runTask($Lh([e,t,...PZ(arguments)]),_C(arguments,!1)):this._runTask(jZ("Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings"))}outputHandler(e){return this._executor.outputHandler=e,this}push(){let e=z2c({remote:gme(arguments[0],GQ),branch:gme(arguments[1],GQ)},PZ(arguments));return this._runTask(e,_C(arguments))}stash(){return this._runTask(r7(["stash",...PZ(arguments)]),_C(arguments))}status(){return this._runTask(WPB(PZ(arguments)),_C(arguments))}},Object.assign(p2c.prototype,rPB(),lPB(),QAB(),aPB(),dPB(),WAB(),MPB(),FPB(),HPB())}}),NVh={};jq(NVh,{Scheduler:()=>QVh});var e4h,QVh,YPB=za({"src/lib/runners/scheduler.ts"(){"use strict";wd(),k4h(),e4h=(()=>{let e=0;return()=>{e++;let{promise:t,done:r}=(0,FVh.createDeferred)();return{promise:t,done:r,id:e}}})(),QVh=class{constructor(e=2){this.concurrency=e,this.logger=S2c("","scheduler"),this.pending=[],this.running=[],this.logger("Constructed, concurrency=%s",e)}schedule(){if(!this.pending.length||this.running.length>=this.concurrency){this.logger("Schedule attempt ignored, pending=%s running=%s concurrency=%s",this.pending.length,this.running.length,this.concurrency);return}let e=uP(this.running,this.pending.shift());this.logger("Attempting id=%s",e.id),e.done(()=>{this.logger("Completing id=",e.id),JPu(this.running,e),this.schedule()})}next(){let{promise:e,id:t}=uP(this.pending,e4h());return this.logger("Scheduling id=%s",t),this.schedule(),e}}}}),UVh={};jq(UVh,{applyPatchTask:()=>XPB});function XPB(e,t){return r7(["apply",...t,...e])}var ZPB=za({"src/lib/tasks/apply-patch.ts"(){"use strict";Pq()}});function kPB(e,t){return{branch:e,hash:t,success:!0}}function ejB(e){return{branch:e,hash:null,success:!1}}var LVh,tjB=za({"src/lib/responses/BranchDeleteSummary.ts"(){"use strict";LVh=class{constructor(){this.all=[],this.branches={},this.errors=[]}get success(){return!this.errors.length}}}});function VVh(e,t){return t===1&&_2c.test(e)}var t4h,_2c,r4h,rju,rjB=za({"src/lib/parsers/parse-branch-delete.ts"(){"use strict";tjB(),wd(),t4h=/(\S+)\s+\(\S+\s([^)]+)\)/,_2c=/^error[^']+'([^']+)'/m,r4h=[new Xp(t4h,(e,[t,r])=>{let i=kPB(t,r);e.all.push(i),e.branches[t]=i}),new Xp(_2c,(e,[t])=>{let r=ejB(t);e.errors.push(r),e.all.push(r),e.branches[t]=r})],rju=(e,t)=>wZ(new LVh,r4h,[e,t])}}),WVh,ijB=za({"src/lib/responses/BranchSummary.ts"(){"use strict";WVh=class{constructor(){this.all=[],this.branches={},this.current="",this.detached=!1}push(e,t,r,i,n){e==="*"&&(this.detached=t,this.current=r),this.all.push(r),this.branches[r]={current:e==="*",linkedWorkTree:e==="+",name:r,commit:i,label:n}}}}});function i4h(e){return e?e.charAt(0):""}function xVh(e,t=!1){return wZ(new WVh,t?[HVh]:GVh,e)}var GVh,HVh,njB=za({"src/lib/parsers/parse-branch.ts"(){"use strict";ijB(),wd(),GVh=[new Xp(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(e,[t,r,i,n])=>{e.push(i4h(t),!0,r,i,n)}),new Xp(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(e,[t,r,i,n])=>{e.push(i4h(t),!1,r,i,n)})],HVh=new Xp(/^(\S+)$/s,(e,[t])=>{e.push("*",!1,t,"","")})}}),KVh={};jq(KVh,{branchLocalTask:()=>ojB,branchTask:()=>ajB,containsDeleteBranchCommand:()=>$Vh,deleteBranchTask:()=>sjB,deleteBranchesTask:()=>ujB});function $Vh(e){let t=["-d","-D","--delete"];return e.some(r=>t.includes(r))}function ajB(e){let t=$Vh(e),r=e.includes("--show-current"),i=["branch",...e];return i.length===1&&i.push("-a"),i.includes("-v")||i.splice(1,0,"-v"),{format:"utf-8",commands:i,parser(n,a){return t?rju(n,a).all[0]:xVh(n,r)}}}function ojB(){return{format:"utf-8",commands:["branch","-v"],parser(e){return xVh(e)}}}function ujB(e,t=!1){return{format:"utf-8",commands:["branch","-v",t?"-D":"-d",...e],parser(r,i){return rju(r,i)},onError({exitCode:r,stdOut:i},n,a,o){if(!VVh(String(n),r))return o(n);a(i)}}}function sjB(e,t=!1){let r={format:"utf-8",commands:["branch","-v",t?"-D":"-d",e],parser(i,n){return rju(i,n).branches[e]},onError({exitCode:i,stdErr:n,stdOut:a},o,c,d){if(!VVh(String(o),i))return d(o);throw new Ato(r.parser(Oto(a),Oto(n)),String(o))}};return r}var cjB=za({"src/lib/tasks/branch.ts"(){"use strict";m_a(),rjB(),njB(),wd()}});function ljB(e){let t=e.trim().replace(/^["']|["']$/g,"");return t&&(0,JVh.normalize)(t)}var YVh,fjB=za({"src/lib/responses/CheckIgnore.ts"(){"use strict";YVh=e=>e.split(/\n/g).map(ljB).filter(Boolean)}}),XVh={};jq(XVh,{checkIgnoreTask:()=>djB});function djB(e){return{commands:["check-ignore",...e],format:"utf-8",parser:YVh}}var pjB=za({"src/lib/tasks/check-ignore.ts"(){"use strict";fjB()}}),ZVh={};jq(ZVh,{cloneMirrorTask:()=>hjB,cloneTask:()=>kVh});function _jB(e){return/^--upload-pack(=|$)/.test(e)}function kVh(e,t,r){let i=["clone",...r];return GQ(e)&&i.push(e),GQ(t)&&i.push(t),i.find(_jB)?jZ("git.fetch: potential exploit argument blocked."):r7(i)}function hjB(e,t,r){return uP(r,"--mirror"),kVh(e,t,r)}var yjB=za({"src/lib/tasks/clone.ts"(){"use strict";Pq(),wd()}});function bjB(e,t){return wZ({raw:e,remote:null,branches:[],tags:[],updated:[],deleted:[]},e3h,[e,t])}var e3h,vjB=za({"src/lib/parsers/parse-fetch.ts"(){"use strict";wd(),e3h=[new Xp(/From (.+)$/,(e,[t])=>{e.remote=t}),new Xp(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(e,[t,r])=>{e.branches.push({name:t,tracking:r})}),new Xp(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(e,[t,r])=>{e.tags.push({name:t,tracking:r})}),new Xp(/- \[deleted]\s+\S+\s*-> (.+)$/,(e,[t])=>{e.deleted.push({tracking:t})}),new Xp(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(e,[t,r,i,n])=>{e.updated.push({name:i,tracking:n,to:r,from:t})})]}}),t3h={};jq(t3h,{fetchTask:()=>OjB});function gjB(e){return/^--upload-pack(=|$)/.test(e)}function OjB(e,t,r){let i=["fetch",...r];return e&&t&&i.push(e,t),i.find(gjB)?jZ("git.fetch: potential exploit argument blocked."):{commands:i,format:"utf-8",parser:bjB}}var mjB=za({"src/lib/tasks/fetch.ts"(){"use strict";vjB(),Pq()}});function AjB(e){return wZ({moves:[]},r3h,e)}var r3h,PjB=za({"src/lib/parsers/parse-move.ts"(){"use strict";wd(),r3h=[new Xp(/^Renaming (.+) to (.+)$/,(e,[t,r])=>{e.moves.push({from:t,to:r})})]}}),i3h={};jq(i3h,{moveTask:()=>jjB});function jjB(e,t){return{commands:["mv","-v",...Ter(e),t],format:"utf-8",parser:AjB}}var wjB=za({"src/lib/tasks/move.ts"(){"use strict";PjB(),wd()}}),n3h={};jq(n3h,{pullTask:()=>EjB});function EjB(e,t,r){let i=["pull",...r];return e&&t&&i.splice(1,0,e,t),{commands:i,format:"utf-8",parser(n,a){return R2c(n,a)},onError(n,a,o,c){let d=CPB(Oto(n.stdOut),Oto(n.stdErr));if(d)return c(new Ato(d));c(a)}}}var SjB=za({"src/lib/tasks/pull.ts"(){"use strict";m_a(),EVh(),wd()}});function MjB(e){let t={};return a3h(e,([r])=>t[r]={name:r}),Object.values(t)}function DjB(e){let t={};return a3h(e,([r,i,n])=>{Object.hasOwn(t,r)||(t[r]={name:r,refs:{fetch:"",push:""}}),n&&i&&(t[r].refs[n.replace(/[^a-z]/g,"")]=i)}),Object.values(t)}function a3h(e,t){b2c(e,r=>t(r.split(/\s+/)))}var BjB=za({"src/lib/responses/GetRemoteSummary.ts"(){"use strict";wd()}}),o3h={};jq(o3h,{addRemoteTask:()=>IjB,getRemotesTask:()=>CjB,listRemotesTask:()=>qjB,remoteTask:()=>TjB,removeRemoteTask:()=>RjB});function IjB(e,t,r){return r7(["remote","add",...r,e,t])}function CjB(e){let t=["remote"];return e&&t.push("-v"),{commands:t,format:"utf-8",parser:e?DjB:MjB}}function qjB(e){let t=[...e];return t[0]!=="ls-remote"&&t.unshift("ls-remote"),r7(t)}function TjB(e){let t=[...e];return t[0]!=="remote"&&t.unshift("remote"),r7(t)}function RjB(e){return r7(["remote","remove",e])}var zjB=za({"src/lib/tasks/remote.ts"(){"use strict";BjB(),Pq()}}),u3h={};jq(u3h,{stashListTask:()=>NjB});function NjB(e={},t){let r=yVh(e),i=["stash","list",...r.commands,...t],n=dVh(r.splitter,r.fields,D2c(i));return tju(i)||{commands:i,format:"utf-8",parser:n}}var FjB=za({"src/lib/tasks/stash-list.ts"(){"use strict";Eto(),_Vh(),T2c(),bVh()}}),s3h={};jq(s3h,{addSubModuleTask:()=>QjB,initSubModuleTask:()=>UjB,subModuleTask:()=>iju,updateSubModuleTask:()=>LjB});function QjB(e,t){return iju(["add",e,t])}function UjB(e){return iju(["init",...e])}function iju(e){let t=[...e];return t[0]!=="submodule"&&t.unshift("submodule"),r7(t)}function LjB(e){return iju(["update",...e])}var VjB=za({"src/lib/tasks/sub-module.ts"(){"use strict";Pq()}});function WjB(e,t){let r=Number.isNaN(e),i=Number.isNaN(t);return r!==i?r?1:-1:r?c3h(e,t):0}function c3h(e,t){return e===t?0:e>t?1:-1}function xjB(e){return e.trim()}function NPu(e){return typeof e=="string"&&parseInt(e.replace(/^\D+/g,""),10)||0}var n4h,l3h,GjB=za({"src/lib/responses/TagList.ts"(){"use strict";n4h=class{constructor(e,t){this.all=e,this.latest=t}},l3h=function(e,t=!1){let r=e.split(`
@@ -2048,7 +2048,7 @@ ${W1E.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&Mvp(th
2048
2048
  `+R2n.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?R2n.default.cyan(Z1E(t,this.opt.mask)):R2n.default.italic(R2n.default.dim("[hidden]")):this.opt.mask?Z1E(t,this.opt.mask):R2n.default.italic(R2n.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 yrc=ue(PF(),1);var ZTE=ue(cgp(),1),_rc=require("child_process"),fWa=require("fs"),prc=ue(require("path"),1),kTE=ue(require("os"),1),eRE=require("crypto"),Kgp=ue(YTE(),1);var lrc=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var TQo=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var frc=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var drc=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function hrc(e="",t,r){let i=new $gp(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 XTE(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function BY5(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 $gp=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=BY5(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??kTE.default.tmpdir(),r=(0,eRE.randomUUID)(),i=XTE(this.fileOptions.prefix),n=XTE(this.fileOptions.postfix),a=`${i}${r}${n}`,o=prc.default.resolve(t,a),c=prc.default.resolve(t)+prc.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,fWa.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new lrc(t)}}readTemporaryFile(){try{let t=(0,fWa.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,ZTE.detect)(t)??"utf8";Kgp.default.encodingExists(r)||(r="utf8"),this.text=Kgp.default.decode(t,r)}}catch(t){throw new frc(t)}}removeTemporaryFile(){try{(0,fWa.unlinkSync)(this.tempFile)}catch(t){throw new drc(t)}}launchEditor(){try{let t=(0,_rc.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new TQo(t)}}launchEditorAsync(t){try{(0,_rc.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new TQo(r)}}};var tRE=ue(B0e(),1);var RQo=class extends jF{_run(t){this.done=t,this.editorResult=new tRE.Subject;let r=V8(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"?yrc.default.dim("Received"):yrc.default.dim("Press <enter> to launch your preferred editor."),t&&(r=yrc.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),hrc(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 oRE=require("stream");var nRE=ue(require("readline"),1),aRE=ue(iRE(),1),Q2n=class{constructor(t){this.rl||=nRE.default.createInterface(CY5(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 CY5(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 aRE.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var zQo=class extends Q2n{constructor(t={}){super(t),this.log=new oRE.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return gQo(this.rl,this.bottomBar.split(`
2049
2049
  `).length),this}updateBottomBar(t){return gQo(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+`
2050
2050
  `}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&&Ftc(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var lA=ue(B0e(),1),cRE=ue(YFo(),1);var brc=ue(B0e(),1),uRE=ue(YFo(),1),vrc=function(e,t,r){return typeof e[t]!="function"?(0,brc.of)(e):(0,brc.from)((0,uRE.default)(e[t])(r).then(i=>(e[t]=i,e)))};var sRE={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}},dWa=class extends Q2n{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,lA.from)(t):(0,lA.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,lA.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,lA.from)([t]),this.process=i.pipe((0,lA.concatMap)(this.processQuestion.bind(this)),(0,lA.publish)()),this.process.connect(),this.process.pipe((0,lA.reduce)((n,a)=>(sRE.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,lA.defer)(()=>(0,lA.of)(t).pipe((0,lA.concatMap)(this.setDefaultType.bind(this)),(0,lA.concatMap)(this.filterIfRunnable.bind(this)),(0,lA.concatMap)(()=>vrc(t,"message",this.answers)),(0,lA.concatMap)(()=>vrc(t,"default",this.answers)),(0,lA.concatMap)(()=>vrc(t,"choices",this.answers)),(0,lA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,lA.defer)(()=>(0,lA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,lA.defer)(()=>(0,lA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&sRE.get(this.answers,t.name)!==void 0)return lA.EMPTY;if(t.when===!1)return lA.EMPTY;if(typeof t.when!="function")return(0,lA.of)(t);let{answers:r}=this;return(0,lA.defer)(()=>(0,lA.from)((0,cRE.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,lA.filter)(i=>i!=null)))}};function lRE(e){let t=function(r,i){let n;try{n=new dWa(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",mQo),this.registerPrompt("input",T2n),this.registerPrompt("number",AQo),this.registerPrompt("confirm",PQo),this.registerPrompt("rawlist",jQo),this.registerPrompt("expand",wQo),this.registerPrompt("checkbox",EQo),this.registerPrompt("password",SQo),this.registerPrompt("editor",RQo)},t.restoreDefaultPrompts(),t}var Ygp=lRE();function TY5(e,t){Ygp.registerPrompt(e,t)}function RY5(){Ygp.restoreDefaultPrompts()}var zY5={prompt:Ygp,ui:{BottomBar:zQo,Prompt:dWa},createPromptModule:lRE,registerPrompt:TY5,restoreDefaultPrompts:RY5,Separator:jge},grc=zY5;var pWa=require("path");function dRE(){let e=NY5();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function NY5(e=process.argv[1]?(0,pWa.dirname)(process.argv[1]):process.cwd(),t=pWa.sep==="\\"){let r=t?fRE(e):e;return i=>{if(!i)return;let n=t?fRE(i):i,{dir:a,base:o,ext:c}=pWa.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 fRE(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Xgp=e=>{if("flags"in e){let t=pRE(e.flags),r=_RE(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,hRE(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,FY5(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function FY5(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 pRE=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,U2n(r)]).filter(([,t])=>t!==void 0)),_RE=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?hRE(i):void 0]}))};var U2n=e=>e===void 0?void 0:e.variant??e.enabled,hRE=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Orc="0123456789abcdef",mrc=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+=Orc.charAt(this.bytes[r]>>>4),t+=Orc.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+=Orc.charAt(this.bytes[r]>>>4),t+=Orc.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}},Zgp=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??QY5()}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 mrc.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,mrc.ofInner(t)}},QY5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),yRE,JQi=()=>UY5().toString(),UY5=()=>(yRE||(yRE=new Zgp)).generate();var LY5=["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"],bRE=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return LY5.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var Ege=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e})({});var WY5=Array.isArray,vRE=Object.prototype,u32=vRE.hasOwnProperty,kgp=vRE.toString,gRE=WY5||function(e){return kgp.call(e)==="[object Array]"};var _Wa=e=>e===void 0,NQo=e=>kgp.call(e)=="[object String]",ORE=e=>NQo(e)&&e.trim().length===0;var mRE=e=>kgp.call(e)=="[object Number]";var eOp=e=>e instanceof Error;function xY5(e,t){try{return e instanceof t}catch{return!1}}function FQo(e){return e===null||typeof e!="object"}function L2n(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function ARE(e){return L2n(e,"ErrorEvent")}function Arc(e){return!_Wa(Event)&&xY5(e,Event)}function PRE(e){return L2n(e,"Object")}function QQo(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),mRE(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),QQo(n||r,t,r,i))}var GY5=864e5,Prc=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=QQo(t.bucketSize,0,100,t._logger),this._refillRate=QQo(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=QQo(t.refillInterval,0,GY5,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 jrc=class{add(t){let r=JQi();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 HY5(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var jRE=(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=>jRE(`${e} ${a}`,t,r)}},KY5=e=>e();function wRE(e,t=KY5){return jRE(e,t,HY5())}var yWa="Mobile",Erc="iOS",hWa="Android",ERE="Tablet",g32=hWa+" "+ERE;var $Y5="Apple",O32=$Y5+" Watch",SRE="Safari",Src="BlackBerry",MRE="Samsung",JY5=MRE+"Browser",YY5=MRE+" Internet",Mrc="Chrome",XY5=Mrc+" OS",ZY5=Mrc+" "+Erc,DRE="Internet Explorer",kY5=DRE+" "+yWa,rOp="Opera",m32=rOp+" Mini",BRE="Edge",eX5="Microsoft "+BRE,iOp="Firefox",tX5=iOp+" "+Erc,nOp="Nintendo",aOp="PlayStation",wrc="Xbox",rX5=hWa+" "+yWa,iX5=yWa+" "+SRE,UQo="Windows",nX5=UQo+" Phone";var IRE="Generic",A32=IRE+" "+yWa.toLowerCase(),P32=IRE+" "+ERE.toLowerCase(),aX5="Konqueror",XJ="(\\d+(\\.\\d+)?)",tOp=new RegExp("Version/"+XJ),j32=new RegExp(wrc,"i"),w32=new RegExp(aOp+" \\w+","i"),E32=new RegExp(nOp+" \\w+","i"),oX5=new RegExp(Src+"|PlayBook|BB10","i"),uX5={"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 S32={[kY5]:[new RegExp("rv:"+XJ)],[eX5]:[new RegExp(BRE+"?\\/"+XJ)],[Mrc]:[new RegExp("("+Mrc+"|CrMo)\\/"+XJ)],[ZY5]:[new RegExp("CriOS\\/"+XJ)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+XJ)],[SRE]:[tOp],[iX5]:[tOp],[rOp]:[new RegExp("("+rOp+"|OPR)\\/"+XJ)],[iOp]:[new RegExp(iOp+"\\/"+XJ)],[tX5]:[new RegExp("FxiOS\\/"+XJ)],[aX5]:[new RegExp("Konqueror[:/]?"+XJ,"i")],[Src]:[new RegExp(Src+" "+XJ),tOp],[rX5]:[new RegExp("android\\s"+XJ,"i")],[YY5]:[new RegExp(JY5+"\\/"+XJ)],[DRE]:[new RegExp("(rv:|MSIE )"+XJ)],Mozilla:[new RegExp("rv:"+XJ)]};var M32=[[new RegExp(wrc+"; "+wrc+" (.*?)[);]","i"),e=>[wrc,e&&e[1]||""]],[new RegExp(nOp,"i"),[nOp,""]],[new RegExp(aOp,"i"),[aOp,""]],[oX5,[Src,""]],[new RegExp(UQo,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[nX5,""];if(new RegExp(yWa).test(t)&&!/IEMobile\b/.test(t))return[UQo+" "+yWa,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=uX5[i]||"";return/arm/i.test(t)&&(n="RT"),[UQo,n]}return[UQo,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Erc,t.join(".")]}return[Erc,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=_Wa(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+hWa+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+hWa+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[hWa,t.join(".")]}return[hWa,""]}],[/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/,[XY5,""]],[/Linux|debian/i,["Linux",""]]];var CRE="utf8";function qRE(e,t){if(!e||typeof e!="string"||sX5(e))throw new Error(t)}function sX5(e){return e.trim().length===0}function TRE(e){return e?.replace(/\/+$/,"")}async function RRE(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 Drc(){return new Date().toISOString()}function V2n(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var zRE=e=>e instanceof Error;function oOp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var Brc=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 NRE(){return"CompressionStream"in globalThis}async function uOp(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 bWa=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()}},LQo=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function FRE(e){if(e instanceof bWa){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 sOp(e){return typeof e=="object"&&(e instanceof bWa||e instanceof LQo)}function QRE(e){return typeof e=="object"&&e instanceof bWa&&e.status===413}var VQo=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new jrc,this._events=new Brc,this._isInitialized=!1,qRE(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=TRE(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:sOp},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.evaluationEnvironments=r?.evaluationEnvironments,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=wRE("[PostHog]",this.logMsgIfDebug.bind(this)),this.disableCompression=!NRE()||(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(Ege.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Ege.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Ege.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.evaluationEnvironments&&this.evaluationEnvironments.length>0&&(s.evaluation_environments=this.evaluationEnvironments);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=>Xgp(f)).catch(f=>{this._events.emit("error",f)})}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=U2n(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!==void 0)return d.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),d.quotaLimited?.includes("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:d?.requestId}):d}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(Ege.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(Ege.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(Ege.Props,this.props)})}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),a=this.getPersistedProperty(Ege.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(Ege.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=V2n(()=>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={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:Drc()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=`${this.host}/batch/`,c=this.disableCompression?null:await uOp(a,this.isDebug),d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||a};try{await this.fetchWithRetry(o,d)}catch(s){this._events.emit("error",s)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:Drc(),uuid:i?.uuid?i.uuid:JQi()};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 FRE(t)})}async flush(){let t=oOp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),oOp([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(Ege.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(_=>_.message),o=()=>{let h=(this.getPersistedProperty(Ege.Queue)||[]).slice(n.length);this.setPersistedProperty(Ege.Queue,h),t=h},c={api_key:this.apiKey,batch:a,sent_at:Drc()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await uOp(d,this.isDebug),f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:_=>QRE(_)?!1:sOp(_)};try{await this.fetchWithRetry(s,f,p)}catch(_){if(QRE(_)&&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 _ instanceof LQo||o(),this._events.emit("error",_),_}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,CRE)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await RRE(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new LQo(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new bWa(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(Ege.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!sOp(n))throw n;await FRE(n)}};return Promise.race([new Promise((n,a)=>{V2n(()=>{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 Sge={};Jt(Sge,{DOMExceptionCoercer:()=>lOp,ErrorCoercer:()=>fOp,ErrorEventCoercer:()=>dOp,ErrorPropertiesBuilder:()=>cOp,EventCoercer:()=>hOp,ObjectCoercer:()=>_Op,PrimitiveCoercer:()=>yOp,PromiseRejectionEventCoercer:()=>bOp,ReduceableCache:()=>vOp,StringCoercer:()=>pOp,chromeStackLineParser:()=>VRE,createStackParser:()=>AX5,geckoStackLineParser:()=>xRE,nodeStackLineParser:()=>$RE,opera10StackLineParser:()=>GRE,opera11StackLineParser:()=>HRE,reverseAndStripFrames:()=>XRE,winjsStackLineParser:()=>WRE});var Irc,URE,Crc;function LRE(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return Crc&&r.length===URE||(URE=r.length,Crc=r.reduce((i,n)=>{Irc||(Irc={});let a=Irc[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,Irc[n]=[s,u];break}}}return i},{})),Crc}var cX5=4,cOp=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&&gRE(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:LRE(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=cX5){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 x8="?";function YQi(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?x8:r,in_app:!0};return _Wa(i)||(a.lineno=i),_Wa(n)||(a.colno=n),a}var qrc=(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]:x8,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var lX5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,fX5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dX5=/\((\S*)(?::(\d+))(?::(\d+))\)/,VRE=(e,t)=>{let r=lX5.exec(e);if(r){let[,n,a,o]=r;return YQi(t,n,x8,+a,+o)}let i=fX5.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=dX5.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=qrc(i[1]||x8,i[2]);return YQi(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var pX5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,WRE=(e,t)=>{let r=pX5.exec(e);return r?YQi(t,r[2],r[1]||x8,+r[3],r[4]?+r[4]:void 0):void 0};var _X5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,hX5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,xRE=(e,t)=>{let r=_X5.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=hX5.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]||x8;return[a,n]=qrc(a,n),YQi(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var yX5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,GRE=(e,t)=>{let r=yX5.exec(e);return r?YQi(t,r[2],r[3]||x8,+r[1]):void 0},bX5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,HRE=(e,t)=>{let r=bX5.exec(e);return r?YQi(t,r[5],r[3]||r[4]||x8,+r[1],+r[2]):void 0};var vX5=/^\s*[-]{4,}$/,gX5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,$RE=(e,t)=>{let r=e.match(gX5);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||x8,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:KRE(r[3]),colno:KRE(r[4]),in_app:OX5(d||"",s),platform:t}}if(e.match(vX5))return{filename:e,platform:t}};function OX5(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 KRE(e){return parseInt(e||"",10)||void 0}var JRE=/\(error: (.*)\)/,YRE=50;function XRE(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,YRE).map(r=>({...r,filename:r.filename||mX5(t).filename,function:r.function||x8}))}function mX5(e){return e[e.length-1]||{}}function AX5(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
2051
- `);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=JRE.test(c)?c.replace(JRE,"$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>=YRE)break}}return XRE(n)}}var lOp=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=NQo(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 L2n(t,"DOMException")}isDOMError(t){return L2n(t,"DOMError")}};var fOp=class{match(t){return eOp(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 dOp=class{constructor(){}match(t){return ARE(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 PX5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,pOp=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(PX5);return n&&(r=n[1],i=n[2]),[r,i]}};var ZRE=["fatal","error","warning","log","info","debug"];function Trc(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 _Op=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 Arc(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=Trc(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return NQo(t)&&!ORE(t)&&ZRE.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(zRE(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var hOp=class{match(t){return Arc(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Trc(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var yOp=class{match(t){return FQo(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var bOp=class{match(t){return L2n(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return FQo(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(FQo(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 vOp=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 tzE=require("fs"),rzE=require("readline"),Rrc=new Sge.ReduceableCache(25),izE=new Sge.ReduceableCache(20),gOp=7,jX5=1e3,wX5=1e4;async function nzE(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"||DX5(o)||BX5(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(izE.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=CX5(a);if(o.every(d=>IX5(n,d)))continue;let c=qX5(Rrc,n,{});i.push(EX5(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&SX5(e,Rrc),Rrc.reduce(),e}function EX5(e,t,r){return new Promise(i=>{let n=(0,tzE.createReadStream)(e),a=(0,rzE.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(){izE.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=TX5(_,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],f=h[1]}})})}function SX5(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;MX5(r.lineno,r,i)}}function MX5(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=azE(e);n<e;n++){let a=r[n];if(a===void 0)return void kRE(t);t.pre_context.push(a)}if(r[e]===void 0)return void kRE(t);t.context_line=r[e];let i=ozE(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 kRE(e){delete e.pre_context,delete e.context_line,delete e.post_context}function DX5(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function BX5(e){return e.lineno!==void 0&&e.lineno>wX5||e.colno!==void 0&&e.colno>jX5}function IX5(e,t){let r=Rrc.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 CX5(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=ezE(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+gOp:(n.push(i),i=ezE(a)),t++}return n}function ezE(e){return[azE(e),ozE(e)]}function azE(e){return Math.max(1,e-gOp)}function ozE(e){return e+gOp}function qX5(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function TX5(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 RX5(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 uzE(e,t){globalThis.process?.on("uncaughtException",RX5(e,t))}function szE(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var zX5=2e3,H7i=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new Prc({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}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||JQi(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(uzE(this.onException.bind(this),this.onFatalError.bind(this)),szE(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{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(zX5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var czE="5.17.4";async function lzE(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 NX5=6e4,FX5=1152921504606847e3,QX5=["is_not"],vWa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},F0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},XQi=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},zrc=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.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 XQi||d instanceof F0?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:_}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,_&&(c[f.key]=_)}catch(p){p instanceof XQi||p instanceof F0?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 F0("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 F0("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 F0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new F0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new F0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new F0(`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 F0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new F0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new F0(`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 XQi)throw u;if(u instanceof F0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new F0("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"?hzE(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):_zE(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await fzE(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await fzE(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}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),!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 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(NX5,this.pollingInterval*2**this.backOffCount):this.pollingInterval}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.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new vWa(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new vWa(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new vWa(`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.shouldBeginExponentialBackoff=!1,this.backOffCount=0,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);break}default:return}}catch(t){t instanceof vWa&&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=V2n(()=>{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 fzE(e,t,r=""){let i=await lzE(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/FX5}function _zE(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 F0("Operator is_not_set is not supported")}else throw new F0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!QX5.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 dzE(String(n))&&String(o).match(String(n))!==null;case"not_regex":return dzE(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 F0("Date operations cannot be performed on boolean values");let s=LX5(String(n));if(s==null&&(s=pzE(n)),s==null)throw new F0(`Invalid date: ${n}`);let u=pzE(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new F0(`Unknown operator: ${a}`)}}function UX5(e,t){if(!(e in t))throw new XQi(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function hzE(e,t,r,i=!1){let n=String(e.value);UX5(n,r);let a=r[n];return yzE(a,t,r,i)}function yzE(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=yzE(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof XQi)throw d;if(d instanceof F0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new F0("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=hzE(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=_zE(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 XQi)throw d;if(d instanceof F0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new F0("can't match cohort without a given cohort property value");return n==="AND"}function dzE(e){try{return new RegExp(e),!0}catch{return!1}}function pzE(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 F0(`${e} is in an invalid date format`)}throw new F0(`The date provided ${e} must be a string, number, or date object`)}function LX5(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 Nrc=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var VX5=100,bzE=3e4,WX5=5e4,Frc=class extends VQo{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Nrc,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,VX5):bzE,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 zrc({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}))}this.errorTracking=new H7i(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||WX5}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 czE}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=bzE){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let f=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=f!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,f=U2n(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${f}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:f,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:f,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),f}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let f;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,f=y.payload)}catch(y){if(y instanceof XQi||y instanceof F0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(f!==void 0)&&!c&&(f=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),f}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=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},_=!0;if(u&&(f=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,...h.flags||{}},p={...p,...h.payloads||{}}}return{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)}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=V2n(()=>{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(PRE(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??!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){let n=new Error("PostHog syntheticException");this.addPendingPromise(H7i.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(H7i.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=JQi(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.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,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&bRE(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.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 vzE=require("async_hooks"),Qrc=class{constructor(){this.storage=new vzE.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 gzE="posthog-node";function xX5(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[OOp.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(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$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&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var OOp=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=gzE,this.name=gzE,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(xX5(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};H7i.errorPropertiesBuilder=new Sge.ErrorPropertiesBuilder([new Sge.EventCoercer,new Sge.ErrorCoercer,new Sge.ObjectCoercer,new Sge.StringCoercer,new Sge.PrimitiveCoercer],Sge.createStackParser("node:javascript",Sge.nodeStackLineParser),[dRE(),nzE]);var gWa=class extends Frc{getLibraryId(){return"posthog-node"}initializeContext(){return new Qrc}};var Urc=class{posthog;constructor({posthogApiKey:t}){this.posthog=new gWa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.55.4",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var WQo=class{async sendEvent(){}async identify(){}async flush(){}};var OWa=require("fs/promises"),OzE=require("os"),mzE=require("path");var GX5="id",HX5=".fern",xQo=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new gWa(r),this.userId=t==null?void 0:T1c(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.55.4",...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 PV({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=at(vr.of((0,OzE.homedir)()),Oe.of(HX5),Oe.of(GX5));await ei(t)||(await(0,OWa.mkdir)((0,mzE.dirname)(t),{recursive:!0}),await(0,OWa.writeFile)(t,kOe())),this.persistedDistinctId=(await(0,OWa.readFile)(t)).toString()}return this.persistedDistinctId}};var mOp;async function mWa(){return mOp==null&&(mOp=await KX5()),mOp}async function KX5(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new WQo;let r=await x$o();return r!=null?new xQo({token:r,posthogApiKey:e}):await Qaa()!=null?new Urc({posthogApiKey:e}):new xQo({token:void 0,posthogApiKey:e})}catch{return new WQo}}var GQo=ue(require("process"),1);var jzE=ue(Lzc(),1),wzE=ue(PzE(),1);function D4(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=CWt(e),e.length===0))return 0;e=e.replace((0,wzE.default)()," ");let r=t.ambiguousIsNarrow?1:2,i=0;for(let n of e){let a=n.codePointAt(0);if(a<=31||a>=127&&a<=159||a>=768&&a<=879)continue;switch(jzE.default.eastAsianWidth(n)){case"F":case"W":i+=2;break;case"A":i+=r;break;default:i+=1}}return i}function Lrc(e){let t=0;for(let r of e.split(`
2051
+ `);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=JRE.test(c)?c.replace(JRE,"$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>=YRE)break}}return XRE(n)}}var lOp=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=NQo(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 L2n(t,"DOMException")}isDOMError(t){return L2n(t,"DOMError")}};var fOp=class{match(t){return eOp(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 dOp=class{constructor(){}match(t){return ARE(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 PX5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,pOp=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(PX5);return n&&(r=n[1],i=n[2]),[r,i]}};var ZRE=["fatal","error","warning","log","info","debug"];function Trc(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 _Op=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 Arc(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=Trc(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return NQo(t)&&!ORE(t)&&ZRE.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(zRE(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var hOp=class{match(t){return Arc(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Trc(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var yOp=class{match(t){return FQo(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var bOp=class{match(t){return L2n(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return FQo(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(FQo(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 vOp=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 tzE=require("fs"),rzE=require("readline"),Rrc=new Sge.ReduceableCache(25),izE=new Sge.ReduceableCache(20),gOp=7,jX5=1e3,wX5=1e4;async function nzE(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"||DX5(o)||BX5(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(izE.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=CX5(a);if(o.every(d=>IX5(n,d)))continue;let c=qX5(Rrc,n,{});i.push(EX5(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&SX5(e,Rrc),Rrc.reduce(),e}function EX5(e,t,r){return new Promise(i=>{let n=(0,tzE.createReadStream)(e),a=(0,rzE.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(){izE.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=TX5(_,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],f=h[1]}})})}function SX5(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;MX5(r.lineno,r,i)}}function MX5(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=azE(e);n<e;n++){let a=r[n];if(a===void 0)return void kRE(t);t.pre_context.push(a)}if(r[e]===void 0)return void kRE(t);t.context_line=r[e];let i=ozE(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 kRE(e){delete e.pre_context,delete e.context_line,delete e.post_context}function DX5(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function BX5(e){return e.lineno!==void 0&&e.lineno>wX5||e.colno!==void 0&&e.colno>jX5}function IX5(e,t){let r=Rrc.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 CX5(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=ezE(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+gOp:(n.push(i),i=ezE(a)),t++}return n}function ezE(e){return[azE(e),ozE(e)]}function azE(e){return Math.max(1,e-gOp)}function ozE(e){return e+gOp}function qX5(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function TX5(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 RX5(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 uzE(e,t){globalThis.process?.on("uncaughtException",RX5(e,t))}function szE(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var zX5=2e3,H7i=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new Prc({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}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||JQi(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(uzE(this.onException.bind(this),this.onFatalError.bind(this)),szE(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{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(zX5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var czE="5.17.4";async function lzE(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 NX5=6e4,FX5=1152921504606847e3,QX5=["is_not"],vWa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},F0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},XQi=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},zrc=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.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 XQi||d instanceof F0?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:_}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,_&&(c[f.key]=_)}catch(p){p instanceof XQi||p instanceof F0?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 F0("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 F0("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 F0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new F0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new F0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new F0(`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 F0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new F0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new F0(`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 XQi)throw u;if(u instanceof F0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new F0("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"?hzE(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):_zE(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await fzE(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await fzE(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}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),!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 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(NX5,this.pollingInterval*2**this.backOffCount):this.pollingInterval}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.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new vWa(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new vWa(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new vWa(`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.shouldBeginExponentialBackoff=!1,this.backOffCount=0,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);break}default:return}}catch(t){t instanceof vWa&&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=V2n(()=>{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 fzE(e,t,r=""){let i=await lzE(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/FX5}function _zE(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 F0("Operator is_not_set is not supported")}else throw new F0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!QX5.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 dzE(String(n))&&String(o).match(String(n))!==null;case"not_regex":return dzE(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 F0("Date operations cannot be performed on boolean values");let s=LX5(String(n));if(s==null&&(s=pzE(n)),s==null)throw new F0(`Invalid date: ${n}`);let u=pzE(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new F0(`Unknown operator: ${a}`)}}function UX5(e,t){if(!(e in t))throw new XQi(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function hzE(e,t,r,i=!1){let n=String(e.value);UX5(n,r);let a=r[n];return yzE(a,t,r,i)}function yzE(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=yzE(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof XQi)throw d;if(d instanceof F0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new F0("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=hzE(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=_zE(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 XQi)throw d;if(d instanceof F0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new F0("can't match cohort without a given cohort property value");return n==="AND"}function dzE(e){try{return new RegExp(e),!0}catch{return!1}}function pzE(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 F0(`${e} is in an invalid date format`)}throw new F0(`The date provided ${e} must be a string, number, or date object`)}function LX5(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 Nrc=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var VX5=100,bzE=3e4,WX5=5e4,Frc=class extends VQo{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Nrc,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,VX5):bzE,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 zrc({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}))}this.errorTracking=new H7i(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||WX5}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 czE}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=bzE){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let f=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=f!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,f=U2n(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${f}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:f,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:f,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),f}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let f;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,f=y.payload)}catch(y){if(y instanceof XQi||y instanceof F0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(f!==void 0)&&!c&&(f=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),f}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=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},_=!0;if(u&&(f=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,...h.flags||{}},p={...p,...h.payloads||{}}}return{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)}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=V2n(()=>{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(PRE(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??!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){let n=new Error("PostHog syntheticException");this.addPendingPromise(H7i.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(H7i.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=JQi(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.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,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&bRE(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.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 vzE=require("async_hooks"),Qrc=class{constructor(){this.storage=new vzE.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 gzE="posthog-node";function xX5(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[OOp.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(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$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&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var OOp=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=gzE,this.name=gzE,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(xX5(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};H7i.errorPropertiesBuilder=new Sge.ErrorPropertiesBuilder([new Sge.EventCoercer,new Sge.ErrorCoercer,new Sge.ObjectCoercer,new Sge.StringCoercer,new Sge.PrimitiveCoercer],Sge.createStackParser("node:javascript",Sge.nodeStackLineParser),[dRE(),nzE]);var gWa=class extends Frc{getLibraryId(){return"posthog-node"}initializeContext(){return new Qrc}};var Urc=class{posthog;constructor({posthogApiKey:t}){this.posthog=new gWa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.55.5",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var WQo=class{async sendEvent(){}async identify(){}async flush(){}};var OWa=require("fs/promises"),OzE=require("os"),mzE=require("path");var GX5="id",HX5=".fern",xQo=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new gWa(r),this.userId=t==null?void 0:T1c(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.55.5",...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 PV({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=at(vr.of((0,OzE.homedir)()),Oe.of(HX5),Oe.of(GX5));await ei(t)||(await(0,OWa.mkdir)((0,mzE.dirname)(t),{recursive:!0}),await(0,OWa.writeFile)(t,kOe())),this.persistedDistinctId=(await(0,OWa.readFile)(t)).toString()}return this.persistedDistinctId}};var mOp;async function mWa(){return mOp==null&&(mOp=await KX5()),mOp}async function KX5(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new WQo;let r=await x$o();return r!=null?new xQo({token:r,posthogApiKey:e}):await Qaa()!=null?new Urc({posthogApiKey:e}):new xQo({token:void 0,posthogApiKey:e})}catch{return new WQo}}var GQo=ue(require("process"),1);var jzE=ue(Lzc(),1),wzE=ue(PzE(),1);function D4(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=CWt(e),e.length===0))return 0;e=e.replace((0,wzE.default)()," ");let r=t.ambiguousIsNarrow?1:2,i=0;for(let n of e){let a=n.codePointAt(0);if(a<=31||a>=127&&a<=159||a>=768&&a<=879)continue;switch(jzE.default.eastAsianWidth(n)){case"F":case"W":i+=2;break;case"A":i+=r;break;default:i+=1}}return i}function Lrc(e){let t=0;for(let r of e.split(`
2052
2052
  `))t=Math.max(t,D4(r));return t}var GzE=ue(POp(),1);var JX5=/[\p{Lu}]/u,YX5=/[\p{Ll}]/u,MzE=/^[\p{Lu}](?![\p{Lu}])/gu,IzE=/([\p{Alpha}\p{N}_]|$)/u,jOp=/[_.\- ]+/,XX5=new RegExp("^"+jOp.source),DzE=new RegExp(jOp.source+IzE.source,"gu"),BzE=new RegExp("\\d+"+IzE.source,"gu"),ZX5=(e,t,r,i)=>{let n=!1,a=!1,o=!1,c=!1;for(let d=0;d<e.length;d++){let s=e[d];c=d>2?e[d-3]==="-":!0,n&&JX5.test(s)?(e=e.slice(0,d)+"-"+e.slice(d),n=!1,o=a,a=!0,d++):a&&o&&YX5.test(s)&&(!c||i)?(e=e.slice(0,d-1)+"-"+e.slice(d-1),o=a,a=!1,n=!0):(n=t(s)===s&&r(s)!==s,o=a,a=r(s)===s&&t(s)!==s)}return e},kX5=(e,t)=>(MzE.lastIndex=0,e.replace(MzE,r=>t(r))),eZ5=(e,t)=>(DzE.lastIndex=0,BzE.lastIndex=0,e.replace(DzE,(r,i)=>t(i)).replace(BzE,r=>t(r)));function wOp(e,t){if(!(typeof e=="string"||Array.isArray(e)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(e)?e=e.map(a=>a.trim()).filter(a=>a.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?a=>a.toLowerCase():a=>a.toLocaleLowerCase(t.locale),i=t.locale===!1?a=>a.toUpperCase():a=>a.toLocaleUpperCase(t.locale);return e.length===1?jOp.test(e)?"":t.pascalCase?i(e):r(e):(e!==r(e)&&(e=ZX5(e,r,i,t.preserveConsecutiveUppercase)),e=e.replace(XX5,""),e=t.preserveConsecutiveUppercase?kX5(e,r):r(e),t.pascalCase&&(e=i(e.charAt(0))+e.slice(1)),eZ5(e,i))}var DOp=ue(qzE(),1);var TzE=(e=0)=>t=>`\x1B[${t+e}m`,RzE=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,zzE=(e=0)=>(t,r,i)=>`\x1B[${38+e};2;${t};${r};${i}m`,cB={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]}},j52=Object.keys(cB.modifier),nZ5=Object.keys(cB.color),aZ5=Object.keys(cB.bgColor),w52=[...nZ5,...aZ5];function oZ5(){let e=new Map;for(let[t,r]of Object.entries(cB)){for(let[i,n]of Object.entries(r))cB[i]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},r[i]=cB[i],e.set(n[0],n[1]);Object.defineProperty(cB,t,{value:r,enumerable:!1})}return Object.defineProperty(cB,"codes",{value:e,enumerable:!1}),cB.color.close="\x1B[39m",cB.bgColor.close="\x1B[49m",cB.color.ansi=TzE(),cB.color.ansi256=RzE(),cB.color.ansi16m=zzE(),cB.bgColor.ansi=TzE(10),cB.bgColor.ansi256=RzE(10),cB.bgColor.ansi16m=zzE(10),Object.defineProperties(cB,{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=>cB.rgbToAnsi256(...cB.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)=>cB.ansi256ToAnsi(cB.rgbToAnsi256(t,r,i)),enumerable:!1},hexToAnsi:{value:t=>cB.ansi256ToAnsi(cB.hexToAnsi256(t)),enumerable:!1}}),cB}var uZ5=oZ5(),NzE=uZ5;var Vrc=new Set(["\x1B","\x9B"]),sZ5=39,SOp="\x07",UzE="[",cZ5="]",LzE="m",MOp=`${cZ5}8;;`,FzE=e=>`${Vrc.values().next().value}${UzE}${e}${LzE}`,QzE=e=>`${Vrc.values().next().value}${MOp}${e}${SOp}`,lZ5=e=>e.split(" ").map(t=>D4(t)),EOp=(e,t,r)=>{let i=[...t],n=!1,a=!1,o=D4(CWt(e[e.length-1]));for(let[c,d]of i.entries()){let s=D4(d);if(o+s<=r?e[e.length-1]+=d:(e.push(d),o=0),Vrc.has(d)&&(n=!0,a=i.slice(c+1).join("").startsWith(MOp)),n){a?d===SOp&&(n=!1,a=!1):d===LzE&&(n=!1);continue}o+=s,o===r&&c<i.length-1&&(e.push(""),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},fZ5=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(D4(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},dZ5=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let i="",n,a,o=lZ5(e),c=[""];for(let[s,u]of e.split(" ").entries()){r.trim!==!1&&(c[c.length-1]=c[c.length-1].trimStart());let f=D4(c[c.length-1]);if(s!==0&&(f>=t&&(r.wordWrap===!1||r.trim===!1)&&(c.push(""),f=0),(f>0||r.trim===!1)&&(c[c.length-1]+=" ",f++)),r.hard&&o[s]>t){let p=t-f,_=1+Math.floor((o[s]-p-1)/t);Math.floor((o[s]-1)/t)<_&&c.push(""),EOp(c,u,t);continue}if(f+o[s]>t&&f>0&&o[s]>0){if(r.wordWrap===!1&&f<t){EOp(c,u,t);continue}c.push("")}if(f+o[s]>t&&r.wordWrap===!1){EOp(c,u,t);continue}c[c.length-1]+=u}r.trim!==!1&&(c=c.map(s=>fZ5(s)));let d=[...c.join(`
2053
2053
  `)];for(let[s,u]of d.entries()){if(i+=u,Vrc.has(u)){let{groups:p}=new RegExp(`(?:\\${UzE}(?<code>\\d+)m|\\${MOp}(?<uri>.*)${SOp})`).exec(d.slice(s).join(""))||{groups:{}};if(p.code!==void 0){let _=Number.parseFloat(p.code);n=_===sZ5?void 0:_}else p.uri!==void 0&&(a=p.uri.length===0?void 0:p.uri)}let f=NzE.codes.get(Number(n));d[s+1]===`
2054
2054
  `?(a&&(i+=QzE("")),n&&f&&(i+=FzE(f))):u===`
@@ -2223,7 +2223,7 @@ ${g}${O}${A}${nxa}`});var E4o=class{result=OA.Success;logImmediately;logPrefix;s
2223
2223
  Run ${Lt.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
2224
2224
  Run ${Lt.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),AWa(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function xDp({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!UKE(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+=`
2225
2225
  ${await POx(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Lt.dim(c.currentVersion)+Lt.reset(" \u2192 ")+Lt.green(c.latestVersion);return n+=`
2226
- `,i?AWa(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function POx(e){let r=await new QKE.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 jOx({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await VKE({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=R2i(u.name,f),_=await rxt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await VKE({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=R2i(s.name,u),p=await rxt({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 VKE({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 Ome({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?xQ(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 WKE(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=SZ(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 Jcc({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await jOx({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(...WKE(s,d,t.logger));else o.push(...WKE(c.versions,void 0,t.logger))}return o}async function khn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:LZa(e.packageName,{version:t?"prerelease":"latest"})}var xKE=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Ycc=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ja.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new aOn(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.55.4"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Lt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new WE}failWithoutThrowing(t,r){this.didSucceed=!1,RJa({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await mWa()).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 LKE({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
2226
+ `,i?AWa(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function POx(e){let r=await new QKE.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 jOx({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await VKE({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=R2i(u.name,f),_=await rxt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await VKE({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=R2i(s.name,u),p=await rxt({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 VKE({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 Ome({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?xQ(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 WKE(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=SZ(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 Jcc({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await jOx({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(...WKE(s,d,t.logger));else o.push(...WKE(c.versions,void 0,t.logger))}return o}async function khn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:LZa(e.packageName,{version:t?"prerelease":"latest"})}var xKE=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Ycc=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ja.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new aOn(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.55.5"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Lt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new WE}failWithoutThrowing(t,r){this.didSucceed=!1,RJa({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await mWa()).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 LKE({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
2227
2227
  `)||(r+=`
2228
2228
  `),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=xbc(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 E4o(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 WE}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await mWa()).sendEvent(t)}logger=uOe((t,...r)=>this.log(t,...r));stderr=uOe((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=GKE(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?GKE(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=xKE[this.numTasks++%xKE.length],o=Lt.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===OA.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=>IWt.indexOf(n.level)>=IWt.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===ja.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 khn({cliEnvironment:this.environment,includePreReleases:t}),i=SZ(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await Jcc({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await VDp({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Lt.yellow("?"),style:{answer:n=>Lt.cyan(n),message:n=>Lt.bold(n),highlight:n=>Lt.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
2229
2229
  Cancelled by user.`),new WE):i}}async getInput(t){return await FDp({message:t.message,default:t.default})}};function GKE(e){return`[${e}]:`}var HKE=require("fs/promises");async function GDp({context:e,nameOverride:t,...r}){let i=await wM(t);return i==null?e.failAndThrow(`Directory "${t??J0}" not found.`):await KKE({absolutePathToFernDirectory:i,context:e,nameOverride:t,...r})}async function KKE({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n,context:a}){let o=[];(await ei(at(e,Oe.of(DH)))||await ei(at(e,Oe.of(vM)))||await ei(at(e,Oe.of(gM)))||await ei(at(e,Oe.of(Pua)))||await ei(at(e,Oe.of(SXa)))||await ei(at(e,Oe.of(h3c))))&&(o=await $KE({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n}));let c=await Kfp({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:
@@ -2259,7 +2259,7 @@ The generator configuration must be an object with a 'name' property, but the cu
2259
2259
 
2260
2260
  Please check your generators.yml file and ensure the generator is properly configured.`);let o=n,c=await r$E({generatorName:t,logger:a});if(c==null)return;let d=EOx({migrations:c.migrations,from:r,to:i,logger:a});if(d.length!==0)return i$E({migrations:d,config:o,logger:a})}function n$E(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 MOx({absolutePathToWorkspace:e,context:t,generatorFilter:r,groupFilter:i,includeMajor:n,channel:a,cliVersion:o}){let c=await Q2i({absolutePathToWorkspace:e});if(c==null||!await ei(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,kcc.readFile)(c);t.logger.debug(`Found generators: ${d.toString()}`);let s=uxa.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(!uxa.default.isMap(u))return t.failAndThrow(`Expected 'groups' to be a map in ${M4o.default.relative(process.cwd(),c)}`),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};t.logger.debug(`Groups found: ${u.toString()}`);let f=[],p=[],_=[];for(let h of u.items){let y=h.key.value,b=h.value;if(!uxa.default.isMap(b)){t.failAndThrow(`Expected group ${y} to be a map in ${M4o.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(!uxa.default.isSeq(v)){t.failAndThrow(`Expected group ${y} to have a 'generators' key in ${M4o.default.relative(process.cwd(),c)}`);continue}t.logger.debug(`Generators found: ${v.toString()}`);for(let O of v.items){uxa.default.isMap(O)||t.failAndThrow(`Expected generator in group ${y} to be a map in ${M4o.default.relative(process.cwd(),c)}`);let m=O.get("name"),g=R2i(m,t),A=r!=null?xQ(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 rxt({generatorName:g,cliVersion:o,currentGeneratorVersion:j,channel:a,includeMajor:n,context:t}),w=S??j;if(S!=null)if(S!==j){t.logger.debug(Lt.green(`Upgrading ${m} from ${j} to ${S}`)),O.set("version",S);let D=0,B=[],R=O.toJSON(),T=await HDp({generatorName:g,from:j,to:S,config:R,logger:t.logger});if(T!=null){D=T.migrationsApplied,B=T.appliedVersions;let q=new Set(Object.keys(R)),z=new Set(Object.keys(T.config));for(let N of q)z.has(N)||O.delete(N);for(let[N,H]of Object.entries(T.config))O.set(N,H);t.logger.debug(Lt.dim(`Applied ${D} migration(s): ${B.join(", ")}`))}p.push({generatorName:m,groupName:y,previousVersion:j,newVersion:S,migrationsApplied:D>0?D:void 0,migrationVersions:B.length>0?B:void 0})}else t.logger.debug(Lt.gray(`${m} is already on the latest version: ${j}`)),_.push({generatorName:m,groupName:y,version:j});if(!n){let D=await rxt({generatorName:g,cliVersion:o,currentGeneratorVersion:w,channel:a,includeMajor:!0,context:t});if(D!=null){let B=KDp.default.parse(w),R=KDp.default.parse(D);B!=null&&R!=null&&R.major>B.major&&f.push({generatorName:m,currentVersion:w,latestMajorVersion:D})}}}}return{updatedConfiguration:s.toString(),skippedMajorUpgrades:f,appliedUpgrades:p,alreadyUpToDate:_}}async function a$E({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 P_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 MOx({absolutePathToWorkspace:s.absoluteFilePath,context:u,generatorFilter:t,groupFilter:r,includeMajor:n,channel:a,cliVersion:e.environment.packageVersion}),_=await Q2i({absolutePathToWorkspace:s.absoluteFilePath});_!=null&&p.updatedConfiguration!=null&&await(0,kcc.writeFile)(_,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(Lt.green("Successfully upgraded generators:"));for(let{workspace:s,upgrades:u}of c){let f=new Map;for(let p of u){let _=f.get(p.groupName)??[];_.push(p),f.set(p.groupName,_)}for(let[p,_]of f){let h=s!=null?`[${s}] `:"";e.logger.info(Lt.green(`${h}Group ${p}:`));for(let y of _){e.logger.info(Lt.green(` - ${y.generatorName}: ${Lt.dim(y.previousVersion)} \u2192 ${y.newVersion}`)),y.migrationsApplied!=null&&y.migrationsApplied>0&&e.logger.info(Lt.dim(` Applied ${y.migrationsApplied} migration(s): ${y.migrationVersions?.join(", ")??""}`));let b=n$E(xQ(y.generatorName));b!=null&&e.logger.info(Lt.dim(` Changelog: ${b}`))}}}}if(d.length>0){e.logger.info(""),e.logger.info(Lt.dim("Generators already on latest version:"));for(let{workspace:s,upToDate:u}of d){let f=new Map;for(let p of u){let _=f.get(p.groupName)??[];_.push(p),f.set(p.groupName,_)}for(let[p,_]of f){let h=s!=null?`[${s}] `:"";e.logger.info(Lt.dim(`${h}Group ${p}:`));for(let y of _)e.logger.info(Lt.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(Lt.gray(`No generators found${s}.`))}if(o.length>0){e.logger.info(""),e.logger.info(Lt.yellow("Major version upgrades available:"));for(let s of o){e.logger.info(Lt.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(Lt.yellow(` Run: ${u}`));let f=n$E(xQ(s.generatorName));f!=null&&e.logger.info(Lt.yellow(` Changelog: ${f}`))}}}function s$E(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 e$E({project:await fm(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),context:t,outputLocation:r.output})})}function c$E(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(oxa),type:"array",description:"The generator output modes to include within the outputted list."}).option("exclude-mode",{choices:Object.values(oxa),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 XKE({project:await fm(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(o$E.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 fm(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0});if(i.list){t.suppressUpgradeMessage();let a=await Jcc({cliContext:t,project:n,generatorFilter:i.generator,groupFilter:i.group,includeMajor:i.includeMajor,channel:i.channel}),o=await xDp({generatorUpgradeInfo:a,header:`Generator Upgrades
2261
2261
  `,includeBoxen:!0});o!=null&&t.logger.info(o)}else await a$E({cliContext:t,generator:i.generator,group:i.group,project:await fm(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 ZKE({cliContext:t,generatorFilter:i.generator,groupFilter:i.group,apiFilter:i.api,project:await fm(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,u$E.writeFile)(i.output,JSON.stringify(a,null,2))}catch(o){t.failAndThrow(`Could not write file to the specified location: ${i.output}`,o)}})})}var l$E=require("fs/promises");async function f$E({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 P_a({absolutePathToWorkspace:n.absoluteFilePath,context:a})??{},c=await HZc({generatorName:t,generatorsConfiguration:o,groupName:r,context:a,cliVersion:i.environment.packageVersion}),d=n.generatorsConfiguration?.absolutePathToConfiguration??await Q2i({absolutePathToWorkspace:n.absoluteFilePath});d!=null&&(await(0,l$E.writeFile)(d,`# yaml-language-server: $schema=https://schema.buildwithfern.dev/generators-yml.json
2262
- `+Ii.dump(c)),a.logger.info(Lt.green(`Added ${t} generator`)))})}))}var p$E=require("fs/promises"),_$E=ue(EY(),1);async function h$E({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new DZa,o=DOx(await a.check({from:await d$E({context:e,filepath:t,flagName:"from"}),to:await d$E({context:e,filepath:r,flagName:"to"})})),c=COx(e,n),{bump:d,errors:s}=BOx(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=_$E.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new WE;return{bump:u,nextVersion:f,errors:s}}async function d$E({context:e,filepath:t,flagName:r}){let i=vr.of(Uo(oO(),t));if(!await ei(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new WE;let n=await(0,p$E.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 WE;return a.value}function DOx(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function BOx(e,t){return{bump:IOx(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function IOx(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 COx(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=qOx(Mvc(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 WE}}function qOx(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}var zeS=ue(YDp(),1),NeS=ue(Ulc(),1),Ofc=require("fs/promises"),FeS=ue(require("http"),1),QeS=ue(require("path"),1);var b2E=require("events"),Glc=ue(require("fs"),1),gea=ue(require("path"),1);var kZE=ue(require("os"),1),e2E=300,oyn=20,X4o=1e7,t2E=kZE.default.platform();var XEx=t2E==="darwin",yIp=t2E==="win32",uyn=XEx||yIp,r2E=3e3,i2E=2e4,bIp=1250;var qUi;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(qUi||(qUi={}));var vea;(function(e){e.CHANGE="change",e.RENAME="rename"})(vea||(vea={}));var Z4o;(function(e){e.CHANGE="change",e.ERROR="error"})(Z4o||(Z4o={}));var Df;(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"})(Df||(Df={}));var dY;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(dY||(dY={}));var ZEx=(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)},_=()=>{c&&(p(),f(Date.now()))},h=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,D=Math.min(S,w);return O(D)},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):h(A)};return m.cancel=p,m.flush=_,m},Llc=ZEx;var mIp=ue(require("fs"),1),Wlc=ue(require("path"),1);var fA=ue(require("fs"),1),$8=require("util");var CKi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},TUi=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var vIp=ue(require("process"),1),n2E=vIp.default.getuid?!vIp.default.getuid():!1,a2E=1e4,Wge=()=>{};var k4o={isChangeErrorOk:e=>{if(!k4o.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!n2E&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!k4o.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(!k4o.isNodeError(e))throw e;if(!k4o.isChangeErrorOk(e))throw e}},tT=k4o;var gIp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=a2E,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()}}}}},o2E=new gIp;var qKi=(e,t)=>function(i){return function n(...a){return o2E.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)})}},TKi=(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 kEx={attempt:{chmod:CKi((0,$8.promisify)(fA.default.chmod),tT.onChangeError),chown:CKi((0,$8.promisify)(fA.default.chown),tT.onChangeError),close:CKi((0,$8.promisify)(fA.default.close),Wge),fsync:CKi((0,$8.promisify)(fA.default.fsync),Wge),mkdir:CKi((0,$8.promisify)(fA.default.mkdir),Wge),realpath:CKi((0,$8.promisify)(fA.default.realpath),Wge),stat:CKi((0,$8.promisify)(fA.default.stat),Wge),unlink:CKi((0,$8.promisify)(fA.default.unlink),Wge),chmodSync:TUi(fA.default.chmodSync,tT.onChangeError),chownSync:TUi(fA.default.chownSync,tT.onChangeError),closeSync:TUi(fA.default.closeSync,Wge),existsSync:TUi(fA.default.existsSync,Wge),fsyncSync:TUi(fA.default.fsync,Wge),mkdirSync:TUi(fA.default.mkdirSync,Wge),realpathSync:TUi(fA.default.realpathSync,Wge),statSync:TUi(fA.default.statSync,Wge),unlinkSync:TUi(fA.default.unlinkSync,Wge)},retry:{close:qKi((0,$8.promisify)(fA.default.close),tT.isRetriableError),fsync:qKi((0,$8.promisify)(fA.default.fsync),tT.isRetriableError),open:qKi((0,$8.promisify)(fA.default.open),tT.isRetriableError),readFile:qKi((0,$8.promisify)(fA.default.readFile),tT.isRetriableError),rename:qKi((0,$8.promisify)(fA.default.rename),tT.isRetriableError),stat:qKi((0,$8.promisify)(fA.default.stat),tT.isRetriableError),write:qKi((0,$8.promisify)(fA.default.write),tT.isRetriableError),writeFile:qKi((0,$8.promisify)(fA.default.writeFile),tT.isRetriableError),closeSync:TKi(fA.default.closeSync,tT.isRetriableError),fsyncSync:TKi(fA.default.fsyncSync,tT.isRetriableError),openSync:TKi(fA.default.openSync,tT.isRetriableError),readFileSync:TKi(fA.default.readFileSync,tT.isRetriableError),renameSync:TKi(fA.default.renameSync,tT.isRetriableError),statSync:TKi(fA.default.statSync,tT.isRetriableError),writeSync:TKi(fA.default.writeSync,tT.isRetriableError),writeFileSync:TKi(fA.default.writeFileSync,tT.isRetriableError)}},u2E=kEx;var Vlc=ue(require("fs"),1),eVo=ue(require("path"),1);var OIp=()=>{};var eSx=()=>{let e=OIp,t=OIp,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}},s2E=eSx;var tSx=()=>{let{promise:e,resolve:t,isPending:r}=s2E(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},c2E=tSx;var l2E={then:e=>{e()}};var f2E=e=>Array.isArray(e)?e:[e],d2E=e=>typeof e=="function";var rSx=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=f2E(a).map(G=>d2E(G)?G:V=>G.test(V)),c=G=>o.some(V=>V(G)),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:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:m},{promise:S,increment:w,decrement:D}=c2E(),B=0,R=(G,V,Se,se)=>{g.has(V)||B>=n||(B+=1,G.directories.push(V),G.directoriesNames.add(Se),u.push(V),f.add(Se),p.propertyIsEnumerable(Se)||(p[Se]=[]),p[Se].push(V),g.add(V),!(se>=i)&&(B>=n||J(V,se+1)))},T=(G,V,Se)=>{g.has(V)||B>=n||(B+=1,G.files.push(V),G.filesNames.add(Se),_.push(V),h.add(Se),y.propertyIsEnumerable(Se)||(y[Se]=[]),y[Se].push(V),g.add(V))},q=(G,V,Se,se)=>{g.has(V)||B>=n||(B+=1,G.symlinks.push(V),G.symlinksNames.add(Se),b.push(V),v.add(Se),O.propertyIsEnumerable(Se)||(O[Se]=[]),O[Se].push(V),g.add(V),r&&(se>=i||B>=n||be(V,se+1)))},z=(G,V,Se,se,Ae)=>{d.aborted||c(V)||(se.isDirectory()?R(G,V,Se,Ae):se.isFile()?T(G,V,Se):se.isSymbolicLink()&&q(G,V,Se,Ae))},N=(G,V,Se,se)=>{if(d.aborted)return;let Ae=V===eVo.default.sep?"":eVo.default.sep,Ue=Se.name,ae=`${V}${Ae}${Ue}`;c(ae)||(Se.isDirectory()?R(G,ae,Ue,se):Se.isFile()?T(G,ae,Ue):Se.isSymbolicLink()&&q(G,ae,Ue,se))},H=(G,V,Se,se)=>{for(let Ae=0,Ue=Se.length;Ae<Ue;Ae++)N(G,V,Se[Ae],se)},J=(G,V)=>{d.aborted||V>i||B>=n||(w(),Vlc.default.readdir(G,{withFileTypes:!0},(Se,se)=>{if(Se||d.aborted||!se.length)return D();(s(se)||l2E).then(()=>{let Ue=m[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};H(Ue,G,se,V),D()})}))},be=(G,V)=>{w(),Vlc.default.realpath(G,(Se,se)=>{if(Se||d.aborted)return D();Vlc.default.stat(se,(Ae,Ue)=>{if(Ae||d.aborted)return D();let ae=eVo.default.basename(se),re=m[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(re,se,ae,Ue,V),D()})})};return(async(G,V=1)=>(G=eVo.default.normalize(G),g.add(G),J(G,V),await S,d.aborted?A:j))(e)},p2E=rSx;var RUi={lang:{debounce:Llc,attempt:e=>{try{return e()}catch(t){return RUi.lang.castError(t)}},castArray:e=>RUi.lang.isArray(e)?e:[e],castError:e=>RUi.lang.isError(e)?e:RUi.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(RUi.lang.isNaN(e))return RUi.lang.isNaN(t);if(RUi.lang.isPrimitive(e)||RUi.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(Wlc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?mIp.default.realpathSync.native(e):mIp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===Wlc.default.sep&&t.length-e.length>Wlc.default.sep.length,poll:(e,t=i2E)=>u2E.retry.stat(t)(e,{bigint:!0}).catch(RUi.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 p2E(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},yh=RUi;var xlc=ue(require("path"),1);var AIp=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||yh.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=e2E){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=yh.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===Df.CHANGE&&c===Df.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===Df.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Df.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??oyn:Math.min(1,this.options.depth??oyn),o=this.options.limit??X4o,[c,d]=await yh.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())yh.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(Df.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!uyn&&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(Df.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Df.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(xlc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Df.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(xlc.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(Df.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Df.ADD?this.onTargetAdd(i):r===Df.ADD_DIR?this.onTargetAddDir(i):r===Df.CHANGE?this.onTargetChange(i):r===Df.UNLINK?this.onTargetUnlink(i):r===Df.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=vea.CHANGE,r){if(this.watcher.isClosed())return;let i=xlc.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){yIp&&t.code==="EPERM"?this.onWatcherChange(vea.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(Z4o.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(Z4o.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(vea.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&uyn&&this.options.native!==!1?this.options.depth??oyn:Math.min(1,this.options.depth??oyn),i=this.options.limit??X4o,[n,a]=await yh.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(vea.CHANGE,c,t)}))}}},_2E=AIp;var pY={interval:100,intervalId:void 0,fns:new Map,init:()=>{pY.intervalId||(pY.intervalId=setInterval(pY.resolve,pY.interval))},reset:()=>{pY.intervalId&&(clearInterval(pY.intervalId),delete pY.intervalId)},add:(e,t)=>{pY.fns.set(e,Date.now()+t),pY.init()},remove:e=>{pY.fns.delete(e)},resolve:()=>{if(!pY.fns.size)return pY.reset();let e=Date.now();for(let[t,r]of pY.fns)r>=e||(pY.remove(t),t())}},tVo=pY;var rVo=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=bIp){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(yh.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),tVo.remove(s)},s=()=>{d(),c()};tVo.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=bIp){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),tVo.remove(s)},s=()=>{d(),c()};tVo.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,Df.ADD,qUi.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,Df.ADD_DIR,qUi.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,Df.UNLINK,qUi.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,Df.UNLINK_DIR,qUi.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}}};rVo.DIR_EVENTS={add:Df.ADD_DIR,rename:Df.RENAME_DIR,unlink:Df.UNLINK_DIR};rVo.FILE_EVENTS={add:Df.ADD,change:Df.CHANGE,rename:Df.RENAME,unlink:Df.UNLINK};var h2E=rVo;var PIp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(yh.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(yh.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(yh.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(yh.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return yh.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);yh.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},jIp=PIp;var wIp=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}},y2E=wIp;var EIp=class{constructor(){this.inos={},this.paths=new jIp,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 yh.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new y2E(i)}reset(){this.inos={},this.paths=new jIp,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,Df.ADD,n),[Df.ADD];if(n.isDirectory())return this.updateIno(t,Df.ADD_DIR,n),[Df.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Df.UNLINK,i),[Df.UNLINK];if(i.isDirectory())return this.updateIno(t,Df.UNLINK_DIR,i),[Df.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Df.CHANGE,n),[Df.CHANGE]);if(n.isDirectory())return this.updateIno(t,Df.UNLINK,i),this.updateIno(t,Df.ADD_DIR,n),[Df.UNLINK,Df.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Df.UNLINK_DIR,i),this.updateIno(t,Df.ADD,n),[Df.UNLINK_DIR,Df.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Df.UNLINK_DIR,i),this.updateIno(t,Df.ADD_DIR,n),[Df.UNLINK_DIR,Df.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?qUi.FILE:qUi.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)}}},SIp=EIp;var MIp=class e extends b2E.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(dY.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(dY.CLOSE,n)),this._readyWait=new Promise(n=>this.on(dY.READY,n)),this._locker=new h2E(this),this._roots=new Set,this._poller=new SIp,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&&(yh.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(dY.CLOSE))}error(t){if(this.isClosed())return!1;let r=yh.lang.castError(t);return this.emit(dY.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(dY.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(dY.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&yh.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&yh.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)yh.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 _2E(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=yh.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=gea.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??oyn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&uyn&&u.options.native!==!1)))return!0;if(!uyn)break;let s=gea.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=yh.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||uyn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:Glc.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 _={...r,ignoreInitial:!0,recursive:!1},h=gea.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||uyn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??oyn,c=r.limit??X4o,[d]=await yh.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=yh.fs.getDepth(t);for(let f of d){let p=yh.fs.getDepth(f),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([f],h,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(dY.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(dY.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=gea.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new SIp,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 yh.lang.noop;if(this.pollerExists(t,r))return yh.lang.noop;let n={...r,interval:r.pollingInterval??r2E},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(dY.CLOSE,c),Glc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(dY.CLOSE,c),Glc.default.unwatchFile(t,i)};return yh.lang.attempt(o),()=>yh.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=yh.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!yh.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=gea.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await yh.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=gea.default.dirname(t);return(await yh.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=yh.lang.noop){if(yh.lang.isFunction(t))return this.watch([],{},t);if(yh.lang.isUndefined(t))return this.watch([],r,i);if(yh.lang.isFunction(r))return this.watch(t,{},r);if(yh.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=yh.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==yh.lang.noop&&this.on(dY.ALL,i),r.readdirMap=void 0,this.ready())}},Hlc=MIp;koc();var Pxa=require("fs/promises"),v2E=require("os"),g2E=ue(require("path"),1),iSx=".fern",nSx="logs";function aSx(){return"cli@3.55.4"}var iVo=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=at(vr.of((0,v2E.homedir)()),Oe.of(iSx)),r=at(t,Oe.of(nSx));await ei(r)||await(0,Pxa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=at(r,Oe.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${g2E.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
2262
+ `+Ii.dump(c)),a.logger.info(Lt.green(`Added ${t} generator`)))})}))}var p$E=require("fs/promises"),_$E=ue(EY(),1);async function h$E({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new DZa,o=DOx(await a.check({from:await d$E({context:e,filepath:t,flagName:"from"}),to:await d$E({context:e,filepath:r,flagName:"to"})})),c=COx(e,n),{bump:d,errors:s}=BOx(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=_$E.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new WE;return{bump:u,nextVersion:f,errors:s}}async function d$E({context:e,filepath:t,flagName:r}){let i=vr.of(Uo(oO(),t));if(!await ei(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new WE;let n=await(0,p$E.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 WE;return a.value}function DOx(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function BOx(e,t){return{bump:IOx(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function IOx(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 COx(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=qOx(Mvc(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 WE}}function qOx(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}var zeS=ue(YDp(),1),NeS=ue(Ulc(),1),Ofc=require("fs/promises"),FeS=ue(require("http"),1),QeS=ue(require("path"),1);var b2E=require("events"),Glc=ue(require("fs"),1),gea=ue(require("path"),1);var kZE=ue(require("os"),1),e2E=300,oyn=20,X4o=1e7,t2E=kZE.default.platform();var XEx=t2E==="darwin",yIp=t2E==="win32",uyn=XEx||yIp,r2E=3e3,i2E=2e4,bIp=1250;var qUi;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(qUi||(qUi={}));var vea;(function(e){e.CHANGE="change",e.RENAME="rename"})(vea||(vea={}));var Z4o;(function(e){e.CHANGE="change",e.ERROR="error"})(Z4o||(Z4o={}));var Df;(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"})(Df||(Df={}));var dY;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(dY||(dY={}));var ZEx=(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)},_=()=>{c&&(p(),f(Date.now()))},h=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,D=Math.min(S,w);return O(D)},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):h(A)};return m.cancel=p,m.flush=_,m},Llc=ZEx;var mIp=ue(require("fs"),1),Wlc=ue(require("path"),1);var fA=ue(require("fs"),1),$8=require("util");var CKi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},TUi=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var vIp=ue(require("process"),1),n2E=vIp.default.getuid?!vIp.default.getuid():!1,a2E=1e4,Wge=()=>{};var k4o={isChangeErrorOk:e=>{if(!k4o.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!n2E&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!k4o.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(!k4o.isNodeError(e))throw e;if(!k4o.isChangeErrorOk(e))throw e}},tT=k4o;var gIp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=a2E,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()}}}}},o2E=new gIp;var qKi=(e,t)=>function(i){return function n(...a){return o2E.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)})}},TKi=(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 kEx={attempt:{chmod:CKi((0,$8.promisify)(fA.default.chmod),tT.onChangeError),chown:CKi((0,$8.promisify)(fA.default.chown),tT.onChangeError),close:CKi((0,$8.promisify)(fA.default.close),Wge),fsync:CKi((0,$8.promisify)(fA.default.fsync),Wge),mkdir:CKi((0,$8.promisify)(fA.default.mkdir),Wge),realpath:CKi((0,$8.promisify)(fA.default.realpath),Wge),stat:CKi((0,$8.promisify)(fA.default.stat),Wge),unlink:CKi((0,$8.promisify)(fA.default.unlink),Wge),chmodSync:TUi(fA.default.chmodSync,tT.onChangeError),chownSync:TUi(fA.default.chownSync,tT.onChangeError),closeSync:TUi(fA.default.closeSync,Wge),existsSync:TUi(fA.default.existsSync,Wge),fsyncSync:TUi(fA.default.fsync,Wge),mkdirSync:TUi(fA.default.mkdirSync,Wge),realpathSync:TUi(fA.default.realpathSync,Wge),statSync:TUi(fA.default.statSync,Wge),unlinkSync:TUi(fA.default.unlinkSync,Wge)},retry:{close:qKi((0,$8.promisify)(fA.default.close),tT.isRetriableError),fsync:qKi((0,$8.promisify)(fA.default.fsync),tT.isRetriableError),open:qKi((0,$8.promisify)(fA.default.open),tT.isRetriableError),readFile:qKi((0,$8.promisify)(fA.default.readFile),tT.isRetriableError),rename:qKi((0,$8.promisify)(fA.default.rename),tT.isRetriableError),stat:qKi((0,$8.promisify)(fA.default.stat),tT.isRetriableError),write:qKi((0,$8.promisify)(fA.default.write),tT.isRetriableError),writeFile:qKi((0,$8.promisify)(fA.default.writeFile),tT.isRetriableError),closeSync:TKi(fA.default.closeSync,tT.isRetriableError),fsyncSync:TKi(fA.default.fsyncSync,tT.isRetriableError),openSync:TKi(fA.default.openSync,tT.isRetriableError),readFileSync:TKi(fA.default.readFileSync,tT.isRetriableError),renameSync:TKi(fA.default.renameSync,tT.isRetriableError),statSync:TKi(fA.default.statSync,tT.isRetriableError),writeSync:TKi(fA.default.writeSync,tT.isRetriableError),writeFileSync:TKi(fA.default.writeFileSync,tT.isRetriableError)}},u2E=kEx;var Vlc=ue(require("fs"),1),eVo=ue(require("path"),1);var OIp=()=>{};var eSx=()=>{let e=OIp,t=OIp,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}},s2E=eSx;var tSx=()=>{let{promise:e,resolve:t,isPending:r}=s2E(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},c2E=tSx;var l2E={then:e=>{e()}};var f2E=e=>Array.isArray(e)?e:[e],d2E=e=>typeof e=="function";var rSx=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=f2E(a).map(G=>d2E(G)?G:V=>G.test(V)),c=G=>o.some(V=>V(G)),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:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:m},{promise:S,increment:w,decrement:D}=c2E(),B=0,R=(G,V,Se,se)=>{g.has(V)||B>=n||(B+=1,G.directories.push(V),G.directoriesNames.add(Se),u.push(V),f.add(Se),p.propertyIsEnumerable(Se)||(p[Se]=[]),p[Se].push(V),g.add(V),!(se>=i)&&(B>=n||J(V,se+1)))},T=(G,V,Se)=>{g.has(V)||B>=n||(B+=1,G.files.push(V),G.filesNames.add(Se),_.push(V),h.add(Se),y.propertyIsEnumerable(Se)||(y[Se]=[]),y[Se].push(V),g.add(V))},q=(G,V,Se,se)=>{g.has(V)||B>=n||(B+=1,G.symlinks.push(V),G.symlinksNames.add(Se),b.push(V),v.add(Se),O.propertyIsEnumerable(Se)||(O[Se]=[]),O[Se].push(V),g.add(V),r&&(se>=i||B>=n||be(V,se+1)))},z=(G,V,Se,se,Ae)=>{d.aborted||c(V)||(se.isDirectory()?R(G,V,Se,Ae):se.isFile()?T(G,V,Se):se.isSymbolicLink()&&q(G,V,Se,Ae))},N=(G,V,Se,se)=>{if(d.aborted)return;let Ae=V===eVo.default.sep?"":eVo.default.sep,Ue=Se.name,ae=`${V}${Ae}${Ue}`;c(ae)||(Se.isDirectory()?R(G,ae,Ue,se):Se.isFile()?T(G,ae,Ue):Se.isSymbolicLink()&&q(G,ae,Ue,se))},H=(G,V,Se,se)=>{for(let Ae=0,Ue=Se.length;Ae<Ue;Ae++)N(G,V,Se[Ae],se)},J=(G,V)=>{d.aborted||V>i||B>=n||(w(),Vlc.default.readdir(G,{withFileTypes:!0},(Se,se)=>{if(Se||d.aborted||!se.length)return D();(s(se)||l2E).then(()=>{let Ue=m[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};H(Ue,G,se,V),D()})}))},be=(G,V)=>{w(),Vlc.default.realpath(G,(Se,se)=>{if(Se||d.aborted)return D();Vlc.default.stat(se,(Ae,Ue)=>{if(Ae||d.aborted)return D();let ae=eVo.default.basename(se),re=m[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(re,se,ae,Ue,V),D()})})};return(async(G,V=1)=>(G=eVo.default.normalize(G),g.add(G),J(G,V),await S,d.aborted?A:j))(e)},p2E=rSx;var RUi={lang:{debounce:Llc,attempt:e=>{try{return e()}catch(t){return RUi.lang.castError(t)}},castArray:e=>RUi.lang.isArray(e)?e:[e],castError:e=>RUi.lang.isError(e)?e:RUi.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(RUi.lang.isNaN(e))return RUi.lang.isNaN(t);if(RUi.lang.isPrimitive(e)||RUi.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(Wlc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?mIp.default.realpathSync.native(e):mIp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===Wlc.default.sep&&t.length-e.length>Wlc.default.sep.length,poll:(e,t=i2E)=>u2E.retry.stat(t)(e,{bigint:!0}).catch(RUi.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 p2E(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},yh=RUi;var xlc=ue(require("path"),1);var AIp=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||yh.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=e2E){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=yh.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===Df.CHANGE&&c===Df.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===Df.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Df.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??oyn:Math.min(1,this.options.depth??oyn),o=this.options.limit??X4o,[c,d]=await yh.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())yh.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(Df.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!uyn&&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(Df.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Df.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(xlc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Df.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(xlc.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(Df.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Df.ADD?this.onTargetAdd(i):r===Df.ADD_DIR?this.onTargetAddDir(i):r===Df.CHANGE?this.onTargetChange(i):r===Df.UNLINK?this.onTargetUnlink(i):r===Df.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=vea.CHANGE,r){if(this.watcher.isClosed())return;let i=xlc.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){yIp&&t.code==="EPERM"?this.onWatcherChange(vea.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(Z4o.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(Z4o.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(vea.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&uyn&&this.options.native!==!1?this.options.depth??oyn:Math.min(1,this.options.depth??oyn),i=this.options.limit??X4o,[n,a]=await yh.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(vea.CHANGE,c,t)}))}}},_2E=AIp;var pY={interval:100,intervalId:void 0,fns:new Map,init:()=>{pY.intervalId||(pY.intervalId=setInterval(pY.resolve,pY.interval))},reset:()=>{pY.intervalId&&(clearInterval(pY.intervalId),delete pY.intervalId)},add:(e,t)=>{pY.fns.set(e,Date.now()+t),pY.init()},remove:e=>{pY.fns.delete(e)},resolve:()=>{if(!pY.fns.size)return pY.reset();let e=Date.now();for(let[t,r]of pY.fns)r>=e||(pY.remove(t),t())}},tVo=pY;var rVo=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=bIp){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(yh.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),tVo.remove(s)},s=()=>{d(),c()};tVo.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=bIp){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),tVo.remove(s)},s=()=>{d(),c()};tVo.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,Df.ADD,qUi.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,Df.ADD_DIR,qUi.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,Df.UNLINK,qUi.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,Df.UNLINK_DIR,qUi.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}}};rVo.DIR_EVENTS={add:Df.ADD_DIR,rename:Df.RENAME_DIR,unlink:Df.UNLINK_DIR};rVo.FILE_EVENTS={add:Df.ADD,change:Df.CHANGE,rename:Df.RENAME,unlink:Df.UNLINK};var h2E=rVo;var PIp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(yh.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(yh.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(yh.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(yh.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return yh.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);yh.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},jIp=PIp;var wIp=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}},y2E=wIp;var EIp=class{constructor(){this.inos={},this.paths=new jIp,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 yh.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new y2E(i)}reset(){this.inos={},this.paths=new jIp,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,Df.ADD,n),[Df.ADD];if(n.isDirectory())return this.updateIno(t,Df.ADD_DIR,n),[Df.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Df.UNLINK,i),[Df.UNLINK];if(i.isDirectory())return this.updateIno(t,Df.UNLINK_DIR,i),[Df.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Df.CHANGE,n),[Df.CHANGE]);if(n.isDirectory())return this.updateIno(t,Df.UNLINK,i),this.updateIno(t,Df.ADD_DIR,n),[Df.UNLINK,Df.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Df.UNLINK_DIR,i),this.updateIno(t,Df.ADD,n),[Df.UNLINK_DIR,Df.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Df.UNLINK_DIR,i),this.updateIno(t,Df.ADD_DIR,n),[Df.UNLINK_DIR,Df.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?qUi.FILE:qUi.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)}}},SIp=EIp;var MIp=class e extends b2E.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(dY.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(dY.CLOSE,n)),this._readyWait=new Promise(n=>this.on(dY.READY,n)),this._locker=new h2E(this),this._roots=new Set,this._poller=new SIp,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&&(yh.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(dY.CLOSE))}error(t){if(this.isClosed())return!1;let r=yh.lang.castError(t);return this.emit(dY.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(dY.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(dY.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&yh.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&yh.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)yh.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 _2E(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=yh.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=gea.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??oyn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&uyn&&u.options.native!==!1)))return!0;if(!uyn)break;let s=gea.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=yh.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||uyn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:Glc.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 _={...r,ignoreInitial:!0,recursive:!1},h=gea.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||uyn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??oyn,c=r.limit??X4o,[d]=await yh.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=yh.fs.getDepth(t);for(let f of d){let p=yh.fs.getDepth(f),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([f],h,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(dY.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(dY.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=gea.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new SIp,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 yh.lang.noop;if(this.pollerExists(t,r))return yh.lang.noop;let n={...r,interval:r.pollingInterval??r2E},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(dY.CLOSE,c),Glc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(dY.CLOSE,c),Glc.default.unwatchFile(t,i)};return yh.lang.attempt(o),()=>yh.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=yh.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!yh.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=gea.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await yh.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=gea.default.dirname(t);return(await yh.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=yh.lang.noop){if(yh.lang.isFunction(t))return this.watch([],{},t);if(yh.lang.isUndefined(t))return this.watch([],r,i);if(yh.lang.isFunction(r))return this.watch(t,{},r);if(yh.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=yh.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==yh.lang.noop&&this.on(dY.ALL,i),r.readdirMap=void 0,this.ready())}},Hlc=MIp;koc();var Pxa=require("fs/promises"),v2E=require("os"),g2E=ue(require("path"),1),iSx=".fern",nSx="logs";function aSx(){return"cli@3.55.5"}var iVo=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=at(vr.of((0,v2E.homedir)()),Oe.of(iSx)),r=at(t,Oe.of(nSx));await ei(r)||await(0,Pxa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=at(r,Oe.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${g2E.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
2263
2263
  `);await(0,Pxa.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)+`
2264
2264
  `;try{await(0,Pxa.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:aSx(),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 JIp=ue(NIp(),1),yeS=ue(J7s(),1),xge=require("fs/promises"),beS=require("os"),veS=ue(oQ(),1),geS=ue(_eS(),1),lfc=process.platform==="win32",$Ip=Lt.cyan("[docs]:"),BSx="etag",ISx=23,heS=e=>e.padEnd(ISx," "),CSx="preview",qSx="app-preview",TSx="bundle",RSx=".next",zSx="standalone",NSx=".fern",FSx="packages/fern-docs/bundle/.next/server/instrumentation.js",QSx=".npmrc",USx=".pnpmfile.cjs",LSx="pnpm-workspace.yaml",VSx='Cannot find matching keyid: {"signatures":';function WSx(){return at(vr.of((0,beS.homedir)()),Oe.of(NSx))}function jxa({app:e=!1}){return at(WSx(),Oe.of(e?qSx:CSx))}function lyn({app:e=!1}){return at(jxa({app:e}),Oe.of(e?RSx:TSx))}function oVo({app:e=!1}){return at(lyn({app:e}),Oe.of(zSx))}function xSx({app:e=!1}){return at(oVo({app:e}),Oe.of(FSx))}function GSx({app:e=!1}){return at(oVo({app:e}),Oe.of(LSx))}function HSx({app:e=!1}){return at(oVo({app:e}),Oe.of(USx))}function KSx({app:e=!1}){return at(oVo({app:e}),Oe.of(QSx))}function Aea(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function $Sx({app:e=!1}){return at(jxa({app:e}),Oe.of(BSx))}var JSx=`module.exports = {
2265
2265
  hooks: {
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "3.55.4",
2
+ "version": "3.55.5",
3
3
  "repository": {
4
4
  "type": "git",
5
5
  "url": "git+https://github.com/fern-api/fern.git",