fimo 0.19.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/skills/fimo-cli/SKILL.md +2 -0
- package/assets/skills/fimo-cli/references/agents.md +4 -1
- package/assets/skills/fimo-cli/references/deploy.md +8 -0
- package/assets/skills/fimo-migration/references/qa.md +7 -0
- package/dist/cli/bundle.json +2 -2
- package/dist/cli/index.js +14 -11
- package/package.json +1 -1
- package/templates/react-router/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { createRequire as __fimoCreateRequire } from 'node:module';
|
|
3
3
|
const require = __fimoCreateRequire(import.meta.url);
|
|
4
4
|
var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0}),__require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __esm=(fn,res,err)=>function(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e){throw err=[e],e}};var __commonJS=(cb,mod)=>function(){try{return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e){throw mod=0,e}};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p2=process||{},argv=p2.argv||[],env=p2.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p2.platform==="win32"||(p2.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=__name((open2,close,replace=open2)=>input=>{let string2=""+input,index2=string2.indexOf(close,open2.length);return~index2?open2+replaceClose(string2,close,replace,index2)+close:open2+string2+close},"formatter"),replaceClose=__name((string2,close,replace,index2)=>{let result="",cursor=0;do result+=string2.substring(cursor,index2)+replace,cursor=index2+close.length,index2=string2.indexOf(close,cursor);while(~index2);return result+string2.substring(cursor)},"replaceClose"),createColors=__name((enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return{isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}},"createColors");module2.exports=createColors();module2.exports.createColors=createColors}});function makePalette(enabled){return enabled?{success:import_picocolors.default.green,warn:import_picocolors.default.yellow,error:import_picocolors.default.red,hint:import_picocolors.default.cyan,dim:import_picocolors.default.dim,accent:import_picocolors.default.bold}:{success:identity,warn:identity,error:identity,hint:identity,dim:identity,accent:identity}}var import_picocolors,identity,init_colors=__esm({"../../packages/cli-kit/dist/colors.js"(){"use strict";import_picocolors=__toESM(require_picocolors(),1),identity=__name(s=>s,"identity");__name(makePalette,"makePalette")}});var SCHEMA_VERSION,init_types=__esm({"../../packages/cli-kit/dist/types.js"(){"use strict";SCHEMA_VERSION=1}});function makeJsonRenderer(opts){let{stdout,stderr}=opts;function emit(stream,envelope){stream.write(`${JSON.stringify(envelope)}
|
|
5
|
-
`)}__name(emit,"emit");function okEnvelope(event){let base={status:"ok",command:event.command,schema_version:1};switch(event.kind){case"message":{let data2={headline:event.headline};return event.details&&(data2.details=event.details),base.data=data2,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}case"table":{let rows=event.rows.map(row2=>{let out={};for(let col of event.columns)out[col.key]=row2[col.key];return event.isActive?.(row2)===!0&&(out.__active=!0),out}),data2={columns:event.columns.map(c2=>c2.key),rows};return event.headline&&(data2.headline=event.headline),base.data=data2,event.hint&&(base.hint=event.hint),base}case"kv":{let data2={fields:event.fields};return event.headline&&(data2.headline=event.headline),base.data=data2,event.hint&&(base.hint=event.hint),base}case"script":return base.data={shell:event.shell,script:event.script},base;case"raw":{let field=event.field??"value";return base.data={[field]:event.value},base}case"result":return base.data=event.data,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}}return __name(okEnvelope,"okEnvelope"),{ok(event){emit(stdout,okEnvelope(event))},error(event){emit(stderr,{status:"error",command:event.command,schema_version:1,error:{code:event.code,message:event.message,...event.hint?{hint:event.hint}:{}}})},warn(event){emit(stdout,{status:"ok",command:event.command,schema_version:1,warnings:[event.message]})},info(event){let env={status:"ok",command:event.command,schema_version:1,data:{message:event.message}};event.hint&&(env.hint=event.hint),emit(stdout,env)}}}var init_renderer_json=__esm({"../../packages/cli-kit/dist/renderer-json.js"(){"use strict";__name(makeJsonRenderer,"makeJsonRenderer")}});function stripAnsi(input){return input.replace(OSC_PATTERN,"").replace(CSI_PATTERN,"")}function displayWidth(input){return stripAnsi(input).length}function padToWidth(input,target){let visible=displayWidth(input);return visible>=target?input:input+" ".repeat(target-visible)}var CSI_PATTERN,OSC_PATTERN,init_width=__esm({"../../packages/cli-kit/dist/width.js"(){"use strict";CSI_PATTERN=/\x1B\[[0-9;]*[A-Za-z]/g,OSC_PATTERN=/\x1B\][\s\S]*?(?:\x07|\x1B\\)/g;__name(stripAnsi,"stripAnsi");__name(displayWidth,"displayWidth");__name(padToWidth,"padToWidth")}});function makePrettyRenderer(opts){let{palette:palette2,symbols,context,stdout,stderr}=opts;function write(stream,line){stream.write(`${line}
|
|
5
|
+
`)}__name(emit,"emit");function okEnvelope(event){let base={status:"ok",command:event.command,schema_version:1};switch(event.kind){case"message":{let data2={headline:event.headline};return event.details&&(data2.details=event.details),base.data=data2,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}case"table":{let rows=event.rows.map(row2=>{let out={};for(let col of event.columns)out[col.key]=row2[col.key];return event.isActive?.(row2)===!0&&(out.__active=!0),out}),data2={columns:event.columns.map(c2=>c2.key),rows};return event.headline&&(data2.headline=event.headline),base.data=data2,event.hint&&(base.hint=event.hint),base}case"kv":{let data2={fields:event.fields};return event.headline&&(data2.headline=event.headline),base.data=data2,event.hint&&(base.hint=event.hint),base}case"script":return base.data={shell:event.shell,script:event.script},base;case"raw":{let field=event.field??"value";return base.data={[field]:event.value},base}case"result":return base.data=event.data,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}}return __name(okEnvelope,"okEnvelope"),{ok(event){emit(stdout,okEnvelope(event))},error(event){emit(stderr,{status:"error",command:event.command,schema_version:1,error:{code:event.code,message:event.message,...event.details?{details:event.details}:{},...event.hint?{hint:event.hint}:{}}})},warn(event){emit(stdout,{status:"ok",command:event.command,schema_version:1,warnings:[event.message]})},info(event){let env={status:"ok",command:event.command,schema_version:1,data:{message:event.message}};event.hint&&(env.hint=event.hint),emit(stdout,env)}}}var init_renderer_json=__esm({"../../packages/cli-kit/dist/renderer-json.js"(){"use strict";__name(makeJsonRenderer,"makeJsonRenderer")}});function stripAnsi(input){return input.replace(OSC_PATTERN,"").replace(CSI_PATTERN,"")}function displayWidth(input){return stripAnsi(input).length}function padToWidth(input,target){let visible=displayWidth(input);return visible>=target?input:input+" ".repeat(target-visible)}var CSI_PATTERN,OSC_PATTERN,init_width=__esm({"../../packages/cli-kit/dist/width.js"(){"use strict";CSI_PATTERN=/\x1B\[[0-9;]*[A-Za-z]/g,OSC_PATTERN=/\x1B\][\s\S]*?(?:\x07|\x1B\\)/g;__name(stripAnsi,"stripAnsi");__name(displayWidth,"displayWidth");__name(padToWidth,"padToWidth")}});function makePrettyRenderer(opts){let{palette:palette2,symbols,context,stdout,stderr}=opts;function write(stream,line){stream.write(`${line}
|
|
6
6
|
`)}__name(write,"write");function renderMessage(event){if(write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`),event.details&&renderAlignedFields(event.details," "),event.warnings)for(let w3 of event.warnings)write(stdout,` ${palette2.warn(symbols.warn)} ${w3}`);maybeHint(event.hint)}__name(renderMessage,"renderMessage");function renderAlignedFields(fields,indent){let keys=Object.keys(fields),longest=keys.reduce((m,k)=>Math.max(m,k.length),0);for(let k of keys){let value=fields[k];value!=null&&write(stdout,`${indent}${palette2.dim(`${k}:`.padEnd(longest+2))}${formatScalar(value)}`)}}__name(renderAlignedFields,"renderAlignedFields");function renderTable2(event){event.headline&&write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`);let{columns,rows}=event;if(rows.length===0){write(stdout,palette2.dim(" (no rows)")),maybeHint(event.hint);return}let widths=columns.map(c2=>Math.max(displayWidth(c2.label),...rows.map(r=>displayWidth(String(r[c2.key]??""))))),header=columns.map((c2,i)=>padToWidth(c2.label,widths[i])).join(" ");write(stdout,` ${palette2.dim(header)}`);for(let row2 of rows){let active=event.isActive?.(row2)===!0,cells=columns.map((c2,i)=>{let raw=String(row2[c2.key]??""),padded=padToWidth(raw,widths[i]),role=event.cellStyle?.(row2,c2.key);return role?paintCell(padded,role):active?palette2.accent(padded):padded}),marker=active?palette2.success(symbols.active):" ";write(stdout,`${marker} ${cells.join(" ")}`)}maybeHint(event.hint)}__name(renderTable2,"renderTable");function paintCell(cell,role){switch(role){case"success":return palette2.success(cell);case"warn":return palette2.warn(cell);case"error":return palette2.error(cell);case"dim":return palette2.dim(cell);case"accent":return palette2.accent(cell)}}__name(paintCell,"paintCell");function renderKv(event){event.headline&&write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`),renderAlignedFields(event.fields,""),maybeHint(event.hint)}__name(renderKv,"renderKv");function renderScript(event){stdout.write(event.script.endsWith(`
|
|
7
7
|
`)?event.script:`${event.script}
|
|
8
8
|
`)}__name(renderScript,"renderScript");function renderRaw(event){stdout.write(`${event.value}
|
|
@@ -39,13 +39,13 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
|
|
|
39
39
|
`),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code2=config.code||"commander.error";this._exit(exitCode,code2,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process9.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process9.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=__name(optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey)),"hasCustomOptionValue");this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=__name(option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},"findBestOptionFromValue"),getErrorMessage=__name(option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},"getErrorMessage"),message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag2){if(this._allowUnknownOption)return;let suggestion="";if(flag2.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag2,candidateFlags)}let message=`error: unknown option '${flag2}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
|
|
40
40
|
`),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases2){return aliases2===void 0?this._aliases:(aliases2.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path50.basename(filename,path50.extname(filename)),this}executableDir(path51){return path51===void 0?this._executableDir:(this._executableDir=path51,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error?(baseWrite=__name(str=>this._outputConfiguration.writeErr(str),"baseWrite"),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=__name(str=>this._outputConfiguration.writeOut(str),"baseWrite"),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error,write:__name(str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),"write"),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process9.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
|
|
41
41
|
Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text3=="function"?helpStr=text3({error:context.error,command:context.command}):helpStr=text3,helpStr&&context.write(`${helpStr}
|
|
42
|
-
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue2=data2[key];result[key]=filterUnknownProperties(fieldValue2,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","datetime","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ARCHIVE_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:20971520},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:20971520},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:20971520},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:20971520},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:5242880},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:5242880},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:5242880},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:5242880},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:5242880},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880},{mime:"application/zip",extensions:[".zip"],category:"archive",maxSizeBytes:20971520},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:10485760},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:10485760},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:10485760},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:10485760},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:20971520},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:20971520},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:20971520},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:20971520},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:20971520},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:20971520},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:20971520}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ARCHIVE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="archive").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z5}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(env);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z5.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv");__name(fnv1a8,"fnv1a8");__name(envResourceKey,"envResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl")}});import{z as z6}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z6.union([z6.literal(PRODUCTION_ENVIRONMENT_KEY),z6.literal(PREVIEW_ENVIRONMENT_KEY),z6.uuid()]),CustomEnvironmentSchema=z6.object({id:z6.uuid(),projectId:z6.uuid(),name:z6.string().trim().min(1).max(64),branchPatterns:z6.array(z6.string().min(1).max(255)).min(1),description:z6.string().max(255).nullable()}),ResolvedEnvironmentSchema=z6.object({branch:EnvSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});import{z as z7}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z7.preprocess(referenceValuePreprocess,z7.object({documentId:z7.uuid()})),ReferenceInputValueSchema=z7.preprocess(referenceValuePreprocess,z7.union([z7.object({documentId:z7.uuid()}),z7.object({slug:z7.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z7.preprocess(polymorphicReferenceValuePreprocess,z7.object({contentType:z7.string().min(1),documentId:z7.uuid()})),PolymorphicReferenceInputValueSchema=z7.preprocess(polymorphicReferenceValuePreprocess,z7.union([z7.object({contentType:z7.string().min(1),documentId:z7.uuid()}),z7.object({contentType:z7.string().min(1),slug:z7.string().min(1)})]))}});import{z as z8}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path50){let conditionPath=[...path50,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path50)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path50));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path50,fieldName,variant.uid]);else walk(field.schema.fields,[...path50,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path50,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path50,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z8.union([z8.object({field:z8.string().min(1),equals:z8.union([z8.string(),z8.number(),z8.boolean()])}).strict(),z8.object({field:z8.string().min(1),in:z8.array(z8.union([z8.string(),z8.number(),z8.boolean()])).min(1)}).strict()]),commonFieldShape={label:z8.string().min(1).optional(),description:z8.string().optional(),editable:z8.boolean().optional(),required:z8.boolean().optional(),default:z8.unknown().optional(),showIf:z8.union([showIfClauseSchema,z8.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z8.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z8.object({...commonFieldShape,type:z8.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z8.number().optional(),max:z8.number().optional(),minLength:z8.number().int().nonnegative().optional(),maxLength:z8.number().int().nonnegative().optional(),regex:z8.string().optional(),multiple:z8.boolean().optional(),allowedMimeTypes:z8.array(z8.string()).optional(),options:z8.array(z8.string().min(1)).min(1).optional(),unique:z8.boolean().optional(),i18n:z8.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z8.object({...commonFieldShape,type:z8.literal("reference"),target:z8.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z8.array(z8.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z8.boolean().optional(),i18n:z8.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z8.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z8.record(z8.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z8.object({uid:z8.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z8.string().min(1),description:z8.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z8.object({fields:blockFieldsSchema}).strict(),blocksSchema=z8.object({oneOf:z8.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z8.object({...commonFieldShape,type:z8.literal("blocks"),min:z8.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z8.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z8.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z8.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z9}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","cutover_step","agent_delegate","version_restore","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","admin_resource_read","merge_force"],AuditActionSchema=z9.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z9.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z9.enum(AUDIT_ACTOR_KINDS)}});import{z as z10}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z10.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z10.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z10.object({permissions:z10.array(OpsPermissionSchema).min(1),backendProfiles:z10.array(OpsBackendProfileSchema).min(1),enabled:z10.boolean().default(!0)}),OpsServiceTokenInputSchema=z10.object({name:z10.string().trim().min(1).max(120),permissions:z10.array(OpsPermissionSchema).min(1),backendProfiles:z10.array(OpsBackendProfileSchema).min(1),expiresAt:z10.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z10.object({importanceReason:z10.string().trim().min(1).max(1e3),ownerUserId:z10.string().trim().min(1).nullable().optional(),framework:z10.string().trim().max(120).nullable().optional(),packageManager:z10.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z10.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z10.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z10.object({projectId:z10.uuid(),title:z10.string().trim().min(1).max(240),userReport:z10.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z10.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z10.string().trim().max(1e4).nullable().optional(),outcome:z10.string().trim().max(1e4).nullable().optional(),evidence:z10.array(z10.record(z10.string(),z10.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z10.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z10.object({fingerprint:z10.string().trim().min(1).max(240),title:z10.string().trim().min(1).max(240),description:z10.string().trim().min(1).max(1e4),affectedVersions:z10.array(z10.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z10.array(z10.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z10.string().trim().min(1).max(64).nullable().optional(),workaround:z10.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z10.array(z10.string().trim().min(1).max(120)).max(100),detectionQueries:z10.array(z10.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z10.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z10.object({changeReference:z10.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z10.string().trim().min(1).max(1e4),evidence:z10.array(z10.record(z10.string(),z10.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z10.object({recipientEmail:z10.email().optional(),subject:z10.string().trim().min(1).max(200).default("An update from Fimo"),message:z10.string().trim().min(1).max(5e3),locale:z10.string().trim().min(2).max(20),reason:z10.string().trim().min(1).max(1e3),acknowledgePolicy:z10.literal(!0)}),OpsSentryIssueIdSchema=z10.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z10.object({reason:z10.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z10.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z10.object({projectId:z10.uuid(),from:z10.coerce.date(),to:z10.coerce.date(),reason:z10.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBillingCacheInvalidateInputSchema=z10.object({reason:z10.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z10.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z10.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z10.discriminatedUnion("kind",[z10.object({kind:z10.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z10.object({kind:z10.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z10.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z10.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z10.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z10.object({migrationId:OpsMigrationIdSchema,projectEnv:z10.string().trim().min(1).max(255).default("main"),reason:z10.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z10.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z10.string().trim().min(1).max(1e3),OpsProjectFileReadInputSchema=z10.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z10.object({pattern:z10.string().min(1).max(300).optional(),limit:z10.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z10.object({pattern:z10.string().min(1).max(200),include:z10.string().min(1).max(300).optional(),caseInsensitive:z10.boolean().default(!1),maxMatches:z10.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z10.object({path:OpsProjectFilePathSchema,content:z10.string().max(256*1024),overwrite:z10.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z10.string().trim().length(64),consentReference:z10.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z10.intersection(OpsProjectOperationPlanInputSchema,z10.object({planHash:z10.string().trim().length(64),reason:z10.string().trim().min(1).max(1e3),consentReference:z10.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z10.object({planHash:z10.string().trim().length(64),reason:z10.string().trim().min(1).max(1e3),consentReference:z10.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)})}});import{z as z11}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt)}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z11.object({kind:z11.literal("say"),label:z11.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z11.string().min(1).max(240).optional(),message:z11.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z11.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z11.object({kind:z11.literal("app"),command:z11.literal("publish")}).strict(),BlockBaseSchema=z11.object({fallback:z11.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z11.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z11.literal("choices"),text:z11.string().max(500).optional(),actions:z11.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z11.discriminatedUnion("kind",[z11.object({kind:z11.literal("entry"),collection:z11.string().min(1).max(80),entryId:z11.string().min(1).max(120)}),z11.object({kind:z11.literal("asset"),assetId:z11.string().min(1).max(120)}),z11.object({kind:z11.literal("url"),url:z11.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z11.literal("table"),columns:z11.array(z11.object({label:z11.string().min(1).max(24)})).min(2).max(4),rows:z11.array(z11.object({cells:z11.array(z11.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z11.literal("cards"),layout:z11.enum(["rail","stack"]).optional(),items:z11.array(z11.object({title:z11.string().min(1).max(60),subtitle:z11.string().min(1).max(120).optional(),imageUrl:z11.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z11.literal("entry"),label:z11.string().min(1).max(80),collection:z11.string().min(1).max(80),entryId:z11.string().min(1).max(120),path:z11.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z11.literal("assets"),items:z11.array(z11.object({url:z11.url({protocol:/^https$/}).max(2e3),alt:z11.string().min(1).max(120),label:z11.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z11.literal("callout"),title:z11.string().min(1).max(80),text:z11.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z11.literal("stat"),items:z11.array(z11.object({label:z11.string().min(1).max(24),value:z11.string().min(1).max(16),delta:z11.string().min(1).max(12).optional(),tone:z11.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z11.literal("chart"),unit:z11.string().min(1).max(12).optional(),points:z11.array(z11.object({label:z11.string().min(1).max(12),value:z11.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),ChatFormBodySchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z11.object({question:z11.string().min(1).max(500),header:z11.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z11.boolean(),recommended:z11.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."})}),FormBlockSchema=BlockBaseSchema.extend({type:z11.literal("form"),steps:z11.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z11.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z11.object({header:z11.string().min(1).max(25),question:z11.string().min(1).max(500),answer:z11.string().min(1).max(3e3),selectedLabels:z11.array(z11.string().min(1).max(120)).max(8),freeText:z11.string().max(2e3),skipped:z11.boolean()}),ChatFormAnswerMetadataSchema=z11.object({toolCallId:z11.string().max(255).optional(),shortTitle:z11.string().max(80).optional(),questions:z11.array(ChatFormAnswerItemSchema).max(4)}),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z11.string().min(1).max(255)})}});import{z as z12}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z12.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z12.object({dev:z12.string().trim().min(1).optional(),build:z12.string().trim().min(1).optional(),install:z12.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z12.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z12.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z12.object({type:z12.enum(["header","cookie","query","host"]),key:z12.string().min(1).optional(),value:z12.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z12.array(FimoHostingConditionSchema).min(1).optional(),missing:z12.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z12.object({source:z12.string().min(1),destination:z12.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z12.object({source:z12.string().min(1),destination:z12.string().min(1),permanent:z12.boolean().optional(),statusCode:z12.union([z12.literal(301),z12.literal(302),z12.literal(307),z12.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z12.object({source:z12.string().min(1),headers:z12.array(z12.object({key:z12.string().min(1),value:z12.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z12.object({rewrites:z12.array(FimoHostingRewriteSchema).optional(),redirects:z12.array(FimoHostingRedirectSchema).optional(),headers:z12.array(FimoHostingHeaderSchema).optional(),cleanUrls:z12.boolean().optional(),trailingSlash:z12.boolean().optional()}).strict(),FimoAppConfigSchema=z12.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path50){return[...path50.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path50){return pageRouteParamNames(path50).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record2=value;return typeof record2.id=="string"?record2.id:Object.fromEntries(Object.entries(record2).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});import{z as z13}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z13.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z13.string(),displayName:z13.string().nullable(),subdomain:z13.string().nullable().optional(),subdomainUpdatedAt:z13.date().nullable().optional(),organizationId:z13.string().nullable(),createdBy:z13.string().nullable(),previewEnabled:z13.boolean().default(!0),enabledChatModels:z13.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z13.string(),thumbnailUrl:z13.string().nullable(),publishedThumbnailUrl:z13.string().nullable(),category:z13.string().nullable(),appUrl:z13.string().nullable(),lastPublishedAt:z13.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z13.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z13.object({id:z13.uuid(),name:z13.string(),displayName:z13.string().nullable(),thumbnailUrl:z13.string().nullable(),category:z13.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z13.object({id:z13.string(),name:z13.string(),avatar:z13.string().nullable(),color:z13.object({bg:z13.string(),text:z13.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z13.object({path:z13.string(),content:z13.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z13.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z13.object({id:z13.string(),messageId:z13.string(),versionId:z13.string().nullable(),role:ProjectChatMessageRole,parts:z13.array(z13.any()),createdAt:z13.coerce.date()}),MessageUserMetadataSchema=z13.object({id:z13.string(),name:z13.string().nullable().optional(),image:z13.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z13.number(),metadata:z13.object({user:MessageUserMetadataSchema,changeManifest:z13.array(z13.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z13.object({versionId:z13.uuid(),commitHash:z13.string(),name:z13.string(),description:z13.string().nullable(),kind:z13.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z13.object({versionCount:z13.number().int().nonnegative(),snapshotBytes:z13.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z13.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z13.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z13.object({content:z13.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z13.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z13.object({success:z13.boolean(),message:z13.string().optional(),warning:z13.string().optional(),durationMs:z13.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z13.object({isPublished:z13.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z13.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z13.object({success:z13.boolean(),message:z13.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z13.boolean()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z14}from"zod";var ProjectEnvStatusSchema,ProjectEnvKindSchema,ProjectEnvDTOSchema,ProjectEnvDTO,ResolvedBranchEnvironmentDTOSchema,ProjectEnvListItemDTOSchema,ProjectEnvListItemDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectEnvStatusSchema=z14.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z14.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z14.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,parentEnv:EnvSchema.nullable(),createdBy:z14.string().nullable(),deletedAt:z14.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),ResolvedBranchEnvironmentDTOSchema=z14.object({id:z14.union([z14.literal(PREVIEW_ENVIRONMENT_KEY),z14.uuid()]),name:z14.string()}),ProjectEnvListItemDTOSchema=ProjectEnvDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectEnvListItemDTO=createDTO(ProjectEnvListItemDTOSchema),CreateProjectEnvRequestSchema=z14.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z14.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z14.array(ProjectEnvListItemDTOSchema)),EnvSurfaceDiffSchema=z14.object({surface:z14.enum(["code","schemas","content","translations","assets","forms"]),status:z14.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z14.number().int().nonnegative(),conflictCount:z14.number().int().nonnegative()}),EnvDiffResultSchema=z14.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z14.coerce.date(),surfaces:z14.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z15}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z15.object({projectId:z15.uuid(),name:z15.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z15.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z15.literal("production"),sourceBranch:EnvSchema,isPublished:z15.boolean(),url:z15.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z15.literal(PREVIEW_ENVIRONMENT_KEY),kind:z15.literal("preview"),matchedBranchCount:z15.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z15.literal("custom"),matchedBranchCount:z15.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z15.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z15.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z15.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z15.object({deletedId:z15.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z16}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z16.object({kind:z16.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z16.object({kind:z16.enum(["variable","secret"]),value:z16.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z16.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z16.object({kind:z16.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z16.object({id:z16.uuid(),projectId:z16.uuid(),key:z16.string(),kind:z16.literal("secret"),exposure:z16.literal("private"),environment:EnvironmentKeySchema,maskedValue:z16.string().optional(),createdAt:z16.date().transform(value=>value.toISOString()),updatedAt:z16.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z16.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z17}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z17.object({success:z17.literal(!0),downloadUrl:z17.string(),expiresAt:z17.string(),fileSize:z17.number(),duration:z17.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z17.object({success:z17.literal(!0),projectId:z17.string(),projectName:z17.string(),displayName:z17.string(),projectUrl:z17.string(),duration:z17.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z17.object({contentTypes:z17.number(),entries:z17.number(),assets:z17.number(),translations:z17.number(),forms:z17.number(),codeFiles:z17.number(),assetFiles:z17.number()}),ImportPreviewSurfaceDTOSchema=z17.object({name:z17.string(),included:z17.boolean(),count:z17.number().optional(),note:z17.string().optional()}),ImportPreviewDTOSchema=z17.object({projectName:z17.string(),displayName:z17.string().nullable(),category:z17.string().nullable(),exportedAt:z17.string(),version:z17.string(),envScope:z17.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z17.array(ImportPreviewSurfaceDTOSchema),fileSize:z17.number(),fileName:z17.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z17.object({success:z17.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z18}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z18.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z18.object({type:z18.literal("manual")}),ScheduleTriggerSchema=z18.object({type:z18.literal("schedule"),cron:z18.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z18.string().optional()}),WebhookTriggerSchema=z18.object({type:z18.literal("webhook"),path:z18.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z18.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z19}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z19.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z19.object({token:z19.string().min(1),risk:CapabilityRiskTierSchema,description:z19.string()}),AgentSubAgentSummarySchema=z19.object({name:z19.string().min(1),grant:z19.enum(["inherit","explicit"]),effectiveCaps:z19.array(z19.string().min(1))}),AgentInstallSummaryDTOSchema=z19.object({agentName:z19.string().min(1),env:z19.string().min(1),declaredCapabilities:z19.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z19.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z19.array(CapabilitySummaryEntrySchema),criticalCapabilities:z19.array(CapabilitySummaryEntrySchema),subAgents:z19.array(AgentSubAgentSummarySchema),declaresDelegate:z19.boolean(),cycle:z19.array(z19.string()).nullable(),missingSubAgents:z19.array(z19.string()),warnings:z19.array(z19.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z20}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z20.object({kind:TriggerKindSchema,summary:z20.string()}),AgentListItemTriggerStateSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z20.boolean(),wired:z20.boolean(),syncError:z20.string().nullable()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),triggerStates:z20.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z21.object({args:z21.unknown().optional(),requestId:z21.string().min(1).max(128).optional()}),DispatchSkippedSchema=z21.object({skipped:z21.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z21.object({sessionId:z21.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z21.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({env:EnvSchema,vs:EnvSchema,syncState:z22.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),agents:z22.array(z22.object({id:z22.string(),name:z22.string(),status:z22.enum(["active","paused","failed"]),lastRunAt:z22.coerce.date().nullable()})).optional(),crossSurface:z22.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z22.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z22.array(z22.object({surface:SurfaceNameSchema,count:z22.number().int().nonnegative()})),conflicts:z22.array(ConflictSchema).optional(),summary:z22.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z22.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z22.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z22.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z22.boolean().optional()}),ResolvedStrategySchema=z22.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z22.boolean()}),MergeRequestSchema=z22.object({from:EnvSchema,allowDirectMerge:z22.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z22.object({mergeId:z22.string().uuid(),streamUrl:z22.string(),strategy:ResolvedStrategySchema,acceptedAt:z22.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z22.object({mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z23.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z23.object({cpuMs:z23.number().nonnegative().default(0),netBytes:z23.number().nonnegative().default(0),walltimeMs:z23.number().nonnegative().default(0),llmTokensIn:z23.number().nonnegative().optional(),llmTokensOut:z23.number().nonnegative().optional(),stepCount:z23.number().int().nonnegative().optional(),toolCallCounts:z23.record(z23.string().min(1).max(120),z23.number().int().nonnegative()).optional()}),AgentSessionReviewPublicationSchema=z23.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z23.object({capturedAt:z23.coerce.date(),fingerprint:z23.string().min(1).max(256),counts:z23.object({code:z23.number().int().nonnegative(),content:z23.number().int().nonnegative(),schemas:z23.number().int().nonnegative(),labels:z23.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z23.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z23.object({diff:DiffReportSchema,code:z23.array(CodeFileDiffSchema.extend({raw:z23.string().max(24576)})).max(200),schemas:z23.array(SchemaTypeDiffSchema).max(200),content:z23.array(z23.object({key:z23.string().min(1).max(512),collection:z23.string().min(1).max(256),slug:z23.string().max(512).optional(),verb:z23.enum(["added","modified","deleted"]),fields:z23.array(z23.object({name:z23.string().min(1).max(256),before:z23.unknown().optional(),after:z23.unknown().optional()})).max(20)})).max(200),labels:z23.array(z23.object({key:z23.string().min(1).max(512),locale:z23.string().min(1).max(64).optional(),before:z23.unknown().nullable(),after:z23.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),env:EnvSchema,agentName:z23.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z23.unknown().optional(),capabilities:z23.array(z23.string()).optional(),dataSources:z23.array(z23.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z23.string().nullable(),startedAt:z23.coerce.date().nullable(),finishedAt:z23.coerce.date().nullable(),cancelledAt:z23.coerce.date().nullable(),costUsd:z23.number().nonnegative(),costCeilingUsd:z23.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z23.boolean(),lastCheckpointId:z23.uuid().nullable(),branchEnvId:z23.uuid().nullable(),parentSessionId:z23.uuid().nullable(),terminalReason:z23.string().nullable(),errorMessage:z23.string().nullable(),report:z23.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z23.string().nullable(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z23.object({id:z23.uuid(),sessionId:z23.uuid(),checkpointIdx:z23.number().int().nonnegative(),payloadRef:z23.string(),payloadSizeBytes:z23.number().int().nonnegative(),checksum:z23.string().length(64),createdAt:z23.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z23.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z23.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z23.object({session:AgentSessionDTOSchema,checkpoints:z23.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress"]),CancelSessionRequestSchema=z23.object({reason:z23.string().min(1).max(120).optional()})}});import{z as z24}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z25.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z25.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z25.enum(["secret_text"]),IntegrationCredentialUsageSchema=z25.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z25.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z25.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z25.object({mode:IntegrationAuthModeSchema,label:z25.string().min(1),description:z25.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z25.object({id:z25.string().min(1),label:z25.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z25.boolean()}),IntegrationToolDefinitionDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),description:z25.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z25.object({title:z25.string().min(1),description:z25.string().min(1),command:z25.string().min(1).optional()}),IntegrationInfoDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z25.array(IntegrationAuthModeDTOSchema),credentials:z25.array(IntegrationCredentialDefinitionDTOSchema),tools:z25.array(IntegrationToolDefinitionDTOSchema),recipes:z25.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),installed:z25.boolean(),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z25.string().nullable(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),connectionStatus:z25.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),installedAt:z25.coerce.date().nullable(),updatedAt:z25.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z25.string(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z25.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z25.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z25.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z25.object({value:z25.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z25.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z25.object({id:z25.uuid(),organizationId:z25.string().min(1),integrationKey:z25.string().min(1),alias:z25.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z25.string().min(1),externalAccountName:z25.string().nullable(),externalBotUserId:z25.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z25.array(z25.string()),connectedAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z25.object({alias:z25.string().min(1).max(120).optional(),token:z25.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z25.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z25.discriminatedUnion("mode",[z25.object({mode:z25.literal("personal"),alias:z25.string().min(1).max(120),token:z25.string().min(1)}),z25.object({mode:z25.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z25.object({integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z25.discriminatedUnion("mode",[z25.object({mode:z25.literal("personal"),integrationKey:z25.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z25.object({mode:z25.literal("oauth"),integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()})]),BindProjectChannelRequestSchema=z25.object({ref:z25.string().min(1),connectionAlias:z25.string().min(1).optional(),agentName:z25.string().min(1).max(160).nullable().optional(),force:z25.boolean().optional()}),ListProjectChannelsQuerySchema=z25.object({integrationKey:z25.string().min(1)}),SearchProjectChannelsQuerySchema=z25.object({integrationKey:z25.string().min(1),connectionAlias:z25.string().min(1),query:z25.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),connectionId:z25.uuid(),externalWorkspaceId:z25.string().min(1),externalChannelId:z25.string().min(1),externalChannelName:z25.string().nullable(),agentName:z25.string().nullable(),enabled:z25.boolean(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z25.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z25.object({id:z25.string().min(1),name:z25.string().min(1),visibility:z25.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z25.string().min(1).nullable(),canMove:z25.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z25.object({markdown:z25.boolean().optional(),summary:z25.boolean().optional(),links:z25.boolean().optional(),images:z25.boolean().optional(),html:z25.union([z25.literal("cleaned"),z25.literal("raw"),z25.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z25.object({url:z25.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z25.object({query:z25.string().min(1),maxResults:z25.number().int().positive().max(20).optional(),sources:z25.array(z25.enum(["web","news","images"])).min(1).max(3).optional(),categories:z25.array(z25.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z25.enum(["hour","day","week","month","year"]).optional(),location:z25.string().min(1).max(160).optional(),country:z25.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z25.object({url:z25.string().url(),search:z25.string().min(1).optional(),limit:z25.number().int().positive().max(200).optional(),includeSubdomains:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z25.object({url:z25.string().url(),limit:z25.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z25.object({text:z25.string().min(1).max(200).optional(),cron:z25.string().min(1).max(120).optional(),timezone:z25.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z25.object({type:z25.enum(["scrape","crawl"]).default("scrape"),urls:z25.array(z25.string().url()).min(1).max(50),scrapeOptions:z25.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z25.object({name:z25.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z25.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z25.string().min(1).max(2e3).optional(),judgeEnabled:z25.boolean().optional(),retentionDays:z25.number().int().min(1).max(365).optional(),notification:z25.object({email:z25.object({enabled:z25.boolean().default(!0),recipients:z25.array(z25.string().email()).min(1).max(20),includeDiffs:z25.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z25.object({monitorId:z25.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z25.string().uuid()}),RunProjectIntegrationToolRequestSchema=z25.object({tool:z25.string().min(1),input:z25.record(z25.string(),z25.unknown()),connectionAlias:z25.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z25.object({provider:z25.string().min(1),providerCredits:z25.number().nonnegative().optional(),providerCostUsd:z25.number().nonnegative().optional(),requests:z25.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z25.object({credits:z25.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()}),FirecrawlSearchToolOutputSchema=z25.object({query:z25.string(),provider:z25.literal("firecrawl"),warning:z25.string().optional(),results:z25.array(z25.object({title:z25.string(),url:z25.string(),snippet:z25.string().optional(),content:z25.string().optional(),score:z25.number().optional(),publishedAt:z25.string().optional()}))}),FirecrawlMapToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),count:z25.number(),links:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),description:z25.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),total:z25.number(),pages:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()})),warning:z25.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z25.object({cron:z25.string().optional(),text:z25.string().optional(),timezone:z25.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z25.object({id:z25.string().optional(),urls:z25.array(z25.string()).optional(),scrapeOptions:z25.record(z25.string(),z25.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z25.object({id:z25.string(),name:z25.string(),status:z25.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z25.string().nullable().optional(),lastRunAt:z25.string().nullable().optional(),currentCheckId:z25.string().nullable().optional(),targets:z25.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z25.string().nullable().optional(),judgeEnabled:z25.boolean().optional(),estimatedCreditsPerMonth:z25.number().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z25.object({id:z25.string(),monitorId:z25.string(),scheduledFor:z25.string().nullable().optional(),startedAt:z25.string().nullable().optional(),finishedAt:z25.string().nullable().optional(),estimatedCredits:z25.number().optional(),reservedCredits:z25.number().optional(),actualCredits:z25.number().optional(),billingStatus:z25.string().nullable().optional(),summary:z25.object({totalPages:z25.number().optional(),same:z25.number().optional(),changed:z25.number().optional(),new:z25.number().optional(),removed:z25.number().optional(),error:z25.number().optional()}).passthrough().optional(),error:z25.string().nullable().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitors:z25.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),deleted:z25.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),checks:z25.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),check:FirecrawlMonitorCheckOutputSchema,next:z25.string().optional()}),FirecrawlToolKeySchema=z25.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z25.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),tool:z25.string().min(1),connectionAlias:z25.string().min(1).nullable().optional(),output:z25.record(z25.string(),z25.unknown()),executedAt:z25.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z25.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z25.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z25.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z25.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z25.array(ProjectChannelCandidateDTOSchema))}});import{z as z26}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z26.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z26.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z26.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z26.object({userId:z26.string().min(1),name:z26.string(),email:z26.string().min(1),subscribed:z26.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z26.object({maxSubscribers:z26.number().int().positive(),subscriberCount:z26.number().int().nonnegative(),effectiveRecipientCount:z26.number().int().nonnegative(),currentUserSubscribed:z26.boolean(),candidates:z26.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z26.object({userIds:z26.array(z26.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z26.object({topic:UserManagedNotificationTopicSchema,enabled:z26.boolean(),source:z26.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z26.object({topics:z26.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z26.object({enabled:z26.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z26.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z26.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z26.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z26.string().nullable(),maskedEmail:z26.string().min(1),applied:z26.boolean(),expiresAt:z26.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z26.object({scheduleId:z26.string().min(1),scheduleName:z26.string(),projectId:z26.string().min(1),projectName:z26.string(),env:z26.string().min(1)}),FollowedSchedulesSchema=z26.object({schedules:z26.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z27}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z27.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z27.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z27.uuid(),env:z27.string().min(1),name:z27.string().min(1),cron:z27.string().min(1),command:z27.string().min(1),secretKeys:z27.array(z27.string().min(1)),enabled:z27.boolean(),lastRunAt:z27.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z27.string().nullable(),overPolicyReasons:z27.array(z27.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z27.object({name:z27.string().min(1).max(120),cron:z27.string().min(1).max(120),command:z27.string().min(1).max(500),secretKeys:z27.array(ProjectSecretKeySchema).default([]),enabled:z27.boolean().optional()}),UpdateProjectScheduleRequestSchema=z27.object({name:z27.string().min(1).max(120).optional(),cron:z27.string().min(1).max(120).optional(),command:z27.string().min(1).max(500).optional(),secretKeys:z27.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z27.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z27.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z27.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z27.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z27.object({maxRuns:z27.number().int().positive(),retentionDays:z27.number().int().positive().nullable(),outputRetentionDays:z27.number().int().positive(),maxOutputBytes:z27.number().int().positive()}),SchedulePolicyStateSchema=z27.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z27.object({code:z27.enum(["Free","Premium"]),source:z27.enum(["cached_subscription","free_fallback"]),activeSchedules:z27.object({used:z27.number().int().nonnegative(),limit:z27.number().int().positive()}),minCadenceMinutes:z27.number().int().positive(),maxRunMs:z27.number().int().positive(),concurrency:z27.object({used:z27.number().int().nonnegative(),limit:z27.number().int().positive()}),compute:z27.object({settledMs:z27.number().int().nonnegative(),reservedMs:z27.number().int().nonnegative(),includedMs:z27.number().int().positive(),remainingMs:z27.number().int().nonnegative(),resetsAt:z27.coerce.date()}),upgrade:z27.object({code:z27.literal("Premium"),activeSchedulesLimit:z27.number().int().positive(),minCadenceMinutes:z27.number().int().positive(),maxRunMs:z27.number().int().positive(),maxConcurrentRuns:z27.number().int().positive(),computeIncludedMs:z27.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z27.array(z27.string())}),ProjectScheduleUsageSchema=z27.object({runCount:z27.number().int().nonnegative(),runsWithOutput:z27.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z27.object({id:z27.uuid(),scheduleId:z27.uuid(),projectId:z27.uuid(),env:z27.string().min(1),scheduleName:z27.string().min(1),command:z27.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z27.object({id:z27.string().min(1),name:z27.string().min(1)}).nullable(),queuedAt:z27.coerce.date(),startedAt:z27.coerce.date().nullable(),finishedAt:z27.coerce.date().nullable(),exitCode:z27.number().int().nullable(),errorCode:z27.string().nullable(),error:z27.string().nullable(),outputBytes:z27.number().int().nonnegative(),outputTruncated:z27.boolean(),outputExpiresAt:z27.coerce.date().nullable(),metadataExpiresAt:z27.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z27.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z27.coerce.date().nullable(),items:z27.array(z27.object({key:z27.string().min(1),updatedAt:z27.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z27.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z27.object({trigger:z27.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z27.object({limit:z27.coerce.number().int().min(1).max(100).default(25),cursor:z27.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z27.object({items:z27.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z27.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z27.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z27.object({items:z27.array(ProjectScheduleRunDTOSchema),nextCursor:z27.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z28}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z28.object({id:z28.uuid(),occurredAt:z28.coerce.date(),projectId:z28.uuid().nullable(),env:z28.string().nullable(),actor:z28.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z28.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z28.unknown().optional(),ipAddress:z28.string().nullable().optional(),userAgent:z28.string().nullable().optional(),error:z28.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z28.object({rows:z28.array(AuditLogRowDTOSchema),nextCursor:z28.string().nullable()})),AuditLogQuerySchema=z28.object({env:z28.string().optional(),action:AuditActionSchema.optional(),actor:z28.string().optional(),from:z28.coerce.date().optional(),to:z28.coerce.date().optional(),limit:z28.coerce.number().int().min(1).max(200).optional(),cursor:z28.string().optional()})}});import{z as z29}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z29.object({surface:SurfaceNameSchema,key:z29.string(),label:z29.string()}),InlineSchema=z29.object({text:z29.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z29.discriminatedUnion("type",[z29.object({type:z29.literal("paragraph"),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("preview"),ref:DiffRefSchema,caption:z29.string().optional()}),z29.object({type:z29.literal("code"),code:z29.string(),lang:z29.string().optional(),caption:z29.string().optional()}),z29.object({type:z29.literal("risk"),level:z29.enum(["warning","error"]),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("list"),items:z29.array(z29.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z29.object({headline:z29.string(),blocks:z29.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z29.object({summary:EnvDiffSummarySchema,fingerprint:z29.string(),generatedAt:z29.coerce.date(),cached:z29.boolean().optional(),credits:z29.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z30}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z30.object({date:z30.string(),visitors:z30.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z30.object({key:z30.string(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z30.object({path:z30.string(),pageName:z30.string().nullable().optional(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z30.object({preset:z30.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z30.string(),requestedTo:z30.string(),effectiveFrom:z30.string(),effectiveTo:z30.string(),isRetentionLimited:z30.boolean(),groupBy:z30.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z30.object({date:z30.string(),content:z30.string(),updatedAt:z30.string(),updatedByUserId:z30.string()}),ProjectPageviewAnalyticsDTOSchema=z30.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative(),bounceRate:z30.number().min(0).max(100),viewsPerVisit:z30.number().nonnegative(),averageVisitDurationSeconds:z30.number().nonnegative(),visitorsSeries:z30.array(ProjectDailyVisitorsDTOSchema),topPages:z30.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z30.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z31}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z31.object({id:z31.string(),email:z31.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z31.coerce.date(),createdAt:z31.coerce.date(),inviterUserId:z31.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z31.object({id:z31.string(),token:z31.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z31.object({success:z31.boolean(),projectId:z31.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z32}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z32.object({id:z32.string(),name:z32.string(),image:z32.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z32.object({count:z32.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z32.object({counts:z32.object({signed_up:z32.int(),activated:z32.int()}),credits:z32.object({total:z32.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z32.email(),emailVerified:z32.boolean(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z33}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z33.object({id:z33.string(),principalType:ProjectPrincipalTypeSchema,principalId:z33.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z33.coerce.date(),expiresAt:z33.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z33.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z33.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z33.record(z33.string(),z33.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z33.object({access:z33.array(ProjectAccessItemDTOSchema),invites:z33.array(ProjectInviteDTOSchema),organization:z33.object({name:z33.string().nullable(),logo:z33.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z33.object({success:z33.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z33.object({success:z33.boolean(),projectId:z33.uuid()}))}});import{z as z34}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z34.object({publicationStatus:PublicationStatusSchema,appUrl:z34.string().nullable(),lastPublishedAt:z34.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z35}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z35.object({url:z35.url(),expiresAt:z35.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z36}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z36.string(),slug:z36.string().nullable(),logo:z36.string().nullable(),metadata:z36.record(z36.string(),z36.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z36.object({id:z36.string(),name:z36.string(),email:z36.email(),image:z36.string().nullable()}),OrganizationMemberDTOSchema=z36.object({id:z36.string(),userId:z36.string(),organizationId:z36.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z36.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z37}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z37.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z37.object({reason:CancellationReasonCodeSchema,details:z37.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z37.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z37.object({included:z37.number().optional(),unitPrice:z37.number().optional(),dailyCap:z37.number().nullable().optional()}),EntitlementsDTOSchema=z37.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z37.object({retentionDays:z37.number().int().positive(),canUseExtendedDateRanges:z37.boolean()}).optional(),history:z37.object({retentionDays:z37.number().int().positive()}).optional(),members:z37.object({canInvite:z37.boolean(),maxMembers:z37.number().int().positive().nullable()}).optional(),domains:z37.object({canUseCustomDomains:z37.boolean(),maxDomains:z37.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z37.object({id:z37.string(),external_id:z37.string(),customerId:z37.string(),planId:z37.string(),planCode:TemplateCodeSchema,currentPeriod:z37.object({start:z37.string(),end:z37.string().nullable()}),cancelAt:z37.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z37.string(),nextPaymentAt:z37.string().nullable(),baseAmount:z37.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z37.object({totalCap:z37.number(),dailyCap:z37.number(),usedTotal:z37.number()}),CreditBalanceDTOSchema=z37.object({total:z37.number(),base:z37.number(),dailyBase:z37.number(),purchases:z37.number(),awards:z37.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z37.object({total:z37.number(),nearLimit:z37.boolean(),canChat:z37.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z37.object({dailyFreeAvailable:z37.number(),monthlyAvailable:z37.number(),purchasedAvailable:z37.number(),awardedAvailable:z37.number()}),ProjectDailyCreditAllowanceDTOSchema=z37.object({periodCap:z37.number(),dailyGrant:z37.number(),usedThisPeriod:z37.number(),remainingThisPeriod:z37.number()}),ProjectCreditBalanceDTOSchema=z37.object({projectId:z37.uuid(),organizationId:z37.string(),balance:z37.object({totalAvailable:z37.number(),nearLimit:z37.boolean(),canUseAi:z37.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z37.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z37.discriminatedUnion("enabled",[z37.object({enabled:z37.literal(!0),thresholdUsd:z37.number().nonnegative(),refillAmountUsd:z37.number().nonnegative()}),z37.object({enabled:z37.literal(!1),thresholdUsd:z37.number().nonnegative().nullable(),refillAmountUsd:z37.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z37.discriminatedUnion("enabled",[z37.object({enabled:z37.literal(!0),thresholdUsd:z37.number().min(.01).multipleOf(.01),refillAmountUsd:z37.number().min(.01).multipleOf(.01)}).strict(),z37.object({enabled:z37.literal(!1),thresholdUsd:z37.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z37.object({invoiceId:z37.string(),newBalance:z37.int(),creditCount:z37.int(),amountUsd:z37.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z37.object({url:z37.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z38}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z38.object({brand:z38.string(),last4:z38.string(),exp:z38.string(),isDefault:z38.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z39}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z39.string().superRefine((path50,ctx)=>{let segments=path50.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z39.object({type:z39.literal("renameField"),contentType:z39.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z39.object({enabled:z39.boolean()}).strict(),ContentTypeDTOSchema=z39.object({id:z39.string(),name:z39.string(),label:z39.string(),isSingleton:z39.boolean(),i18n:ContentTypeI18nSchema,fields:z39.record(z39.string(),FieldDefinitionSchema),createdAt:z39.string(),updatedAt:z39.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z39.object({contentTypes:z39.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z39.object({id:z39.string(),entryId:z39.string(),documentId:z39.string(),slug:z39.string(),locale:z39.string().optional(),createdAt:z39.string(),updatedAt:z39.string(),__fimo:z39.object({contentType:z39.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({limit:z39.number(),offset:z39.number(),total:z39.number(),hasMore:z39.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z39.object({contentType:z39.string(),count:z39.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z39.object({counts:z39.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z39.object({count:z39.number().int().nonnegative(),sourceLocale:z39.string(),targetLocale:z39.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z39.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z39.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z39.union([z39.string(),z39.number(),z39.boolean(),z39.null()]),entryWhereOperatorSchema=z39.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z39.array(entryWhereScalarSchema).optional(),$nin:z39.array(entryWhereScalarSchema).optional(),$contains:z39.string().optional(),$startsWith:z39.string().optional(),$null:z39.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z39.object({data:z39.record(z39.string(),z39.unknown()),locale:z39.string().min(1).optional(),documentId:z39.uuid().optional()}),entryIdsSchema=z39.array(z39.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z39.object({sql:z39.string().min(1)}),BulkCreateEntriesRequestSchema=z39.object({entries:z39.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z39.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z39.object({updates:z39.array(z39.object({id:z39.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,locale:z39.string().min(1).optional()}),z39.object({where:EntryWhereSchema,locale:z39.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z39.object({data:z39.array(z39.record(z39.string(),z39.unknown())),meta:z39.object({rowCount:z39.number().int().nonnegative(),truncated:z39.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({created:z39.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({updated:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({deleted:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z40}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z40.object({index:z40.number().int().nonnegative(),contentType:z40.string(),field:z40.string(),value:z40.string(),against:z40.enum(["stored","batch"]),ownerDocumentId:z40.uuid().optional(),ownerIndex:z40.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z40.object({code:z40.literal("unique_conflict"),message:z40.string(),conflicts:z40.array(UniqueConflictSchema),truncated:z40.boolean().optional()})}});import{z as z41}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z41.object({kind:z41.literal("unique_conflict"),contentType:z41.string(),field:z41.string(),value:z41.string(),documentCount:z41.number().int().positive(),documentIds:z41.array(z41.uuid()),documentIdsTruncated:z41.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z41.object({code:z41.literal("schema_transition_rejected"),message:z41.string(),issues:z41.array(SchemaTransitionIssueSchema),truncated:z41.boolean().optional()})}});import{z as z42}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z42.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z42.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z42.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z42.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z42.object({field:CmsFieldNameSchema,direction:z42.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z42.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z42.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z42.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z42.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z42.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z43}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z43.object({id:z43.string(),name:z43.string()}),AssetDTOSchema=z43.object({id:z43.string(),name:z43.string(),type:AssetTypeSchema,originalFileName:z43.string().nullable(),parentId:z43.string().nullable(),mimeType:z43.string().nullable(),fileSize:z43.number().nullable(),url:z43.string().nullable(),storageKey:z43.string().nullable(),createdAt:z43.string(),updatedAt:z43.string(),altText:z43.string().nullable().optional(),caption:z43.string().nullable().optional(),aiCaption:z43.string().nullable().optional(),aiAltText:z43.string().nullable().optional(),aiTags:z43.array(z43.string()).nullable().optional(),aiPrimaryColor:z43.string().nullable().optional(),aiProcessingStatus:z43.string().nullable().optional(),width:z43.number().nullable().optional(),height:z43.number().nullable().optional(),path:z43.array(AssetPathItemSchema).optional(),hasChildren:z43.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z43.lazy(()=>z43.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z43.array(AssetDTOSchema))}});import{z as z44}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z44.object({key:z44.string(),value:z44.string().optional(),defaultValue:z44.string(),locale:z44.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z45}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z45.object({id:z45.string(),name:z45.string(),type:z45.enum(["file","folder"]),path:z45.string(),children:z45.lazy(()=>z45.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z45.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z45.object({path:z45.string(),exists:z45.boolean(),type:z45.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z46}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z46.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z46.object({items:z46.array(ProjectMessagePublicDTOSchema),nextCursor:z46.string().nullable()}),ChatLiveTurnDTOSchema=z46.object({invocationId:z46.string(),step:z46.enum(["preparing","working","compacting","merging"]),startedAt:z46.string()}),ChatLiveTurnStateDTOSchema=z46.object({threadId:z46.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z46.object({id:z46.string(),role:z46.enum(["user","assistant"]),parts:z46.array(z46.unknown()),metadata:z46.record(z46.string(),z46.unknown()).nullable(),versionId:z46.string().nullable().optional(),createdAt:z46.date().transform(value=>value.toISOString()),providerMessageId:z46.string().nullable().optional(),invocationId:z46.string().nullable().optional(),invocationStatus:z46.string().nullable().optional(),invocationTerminalReason:z46.string().nullable().optional()}),ChatAttentionDTOSchema=z46.object({type:z46.literal("merge_conflict"),merge:z46.object({mergeId:z46.string().uuid(),projectId:z46.string(),fromEnv:z46.string(),toEnv:z46.string()}),publishAfterMerge:z46.boolean()}),ChatThreadMessagesPageDTOSchema=z46.object({threadId:z46.string().nullable(),title:z46.string().nullable(),messages:z46.array(ChatThreadMessageDTOSchema),nextCursor:z46.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z46.object({kind:z46.literal("replay"),threadId:z46.string(),userMessageId:z46.string()}),ChatQueuedOutcomeDTOSchema=z46.object({kind:z46.literal("queued"),threadId:z46.string(),userMessageId:z46.string(),blockingRootId:z46.string()}),ChatBusyOutcomeDTOSchema=z46.object({kind:z46.literal("busy"),threadId:z46.string(),userMessageId:z46.string(),blockingRootId:z46.string().optional()}),ChatRefusedOutcomeDTOSchema=z46.object({kind:z46.literal("refused"),threadId:z46.string(),userMessageId:z46.string(),refusedInvocationId:z46.string(),terminalReason:z46.string()}),ChatNonStreamingOutcomeDTOSchema=z46.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z46.object({success:z46.boolean(),deletedCount:z46.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z46.object({code:z46.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z46.string()})}});import{z as z47}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z47.object({url:z47.string().url(),key:z47.string(),size:z47.number(),contentType:z47.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z48}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z48.object({canAccess:z48.boolean(),permissions:z48.record(z48.string(),z48.boolean()),role:z48.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z49}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z49.string().trim().default(""),sort:z49.enum(["recent","name","relevance"]).default("recent"),category:z49.string().optional()})}});import{z as z50}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z50.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z50.enum(["fimo","external"]),PaymentStatusSchema=z50.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z50.object({id:z50.string().uuid(),domain:z50.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z50.boolean(),price:z50.number().int().nullable(),renewalPrice:z50.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z50.string().nullable(),failureReason:z50.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z50.object({domain:z50.string(),available:z50.boolean(),premium:z50.boolean(),price:z50.number().nullable(),renewalPrice:z50.number().nullable(),purchaseType:z50.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z50.object({domain:z50.string(),price:z50.number().nullable(),renewalPrice:z50.number().nullable(),premium:z50.boolean(),allowedYears:z50.array(z50.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z50.object({firstName:z50.string().max(100),lastName:z50.string().max(100),companyName:z50.string().max(100).optional(),address1:z50.string().max(255),address2:z50.string().max(255).optional(),city:z50.string().max(100),state:z50.string().max(100),zip:z50.string().max(20),country:z50.string().max(2),phone:z50.string().max(30),email:z50.union([z50.string().email().max(255),z50.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z50.object({firstName:z50.string().min(1).max(100),lastName:z50.string().min(1).max(100),companyName:z50.string().max(100).optional(),address1:z50.string().min(1).max(255),address2:z50.string().max(255).optional(),city:z50.string().min(1).max(100),state:z50.string().min(1).max(100),zip:z50.string().min(1).max(20),country:z50.string().min(1).max(2),phone:z50.string().min(1).max(30),email:z50.string().email().max(255)}),SearchDomainsRequestSchema=z50.object({keyword:z50.string().min(1).max(100),tldFilter:z50.array(z50.string()).optional()}),CheckAvailabilityRequestSchema=z50.object({domains:z50.array(z50.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z50.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z50.object({domain:DomainNameSchema,years:z50.number().int().min(1).max(10).optional().default(3),autoRenew:z50.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z50.object({autoRenew:z50.boolean().optional()}),RenewDomainRequestSchema=z50.object({years:z50.number().int().min(1).max(10).optional().default(1),autoRenew:z50.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z50.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z50.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z50.object({verified:z50.boolean(),email:z50.string().nullable(),verifyBy:z50.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z51}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z51.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z51.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z51.object({txtName:z51.string().nullable().optional(),txtValue:z51.string().nullable().optional(),httpUrl:z51.string().nullable().optional(),httpBody:z51.string().nullable().optional(),cname:z51.string().nullable().optional(),cnameTarget:z51.string().nullable().optional()}),SSLValidationErrorSchema=z51.object({message:z51.string()}),OwnershipVerificationSchema=z51.object({type:z51.string(),name:z51.string(),value:z51.string()}),ProjectDomainSSLDTOSchema=z51.object({status:z51.string(),method:z51.string().nullable(),type:z51.string().nullable(),validationRecords:z51.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z51.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z51.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z51.enum(["subdomain","apex"]),RedirectConfigSchema=z51.object({type:z51.literal("apex_to_www"),linkedDomainId:z51.string()}).nullable().optional(),ProjectDomainDTOSchema=z51.object({id:z51.string(),hostname:z51.string(),status:z51.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z51.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z51.string(),scdCnameTarget:z51.string().optional(),apexTargets:z51.array(z51.string()),dnsAutoConfigured:z51.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z51.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z51.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z51.object({hostname:z51.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z51.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z51.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z51.object({available:z51.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z51.object({success:z51.boolean(),hostname:z51.string()}))}});import{z as z52}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z52.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z52.object({available:z52.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z52.object({slug:z52.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z52.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z52.object({subdomain:z52.string(),subdomainUpdatedAt:z52.coerce.date()})),SubdomainSuggestionsQuerySchema=z52.object({base:z52.string().max(100).optional(),max:z52.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z52.object({suggestions:z52.array(z52.string())}))}});import{z as z53}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z53.object({translated:z53.number().int().nonnegative(),total:z53.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z53.object({locale:z53.string(),isDefault:z53.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z53.object({defaultLocale:z53.string(),locales:z53.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z53.object({locale:z53.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z53.object({locale:z53.string().min(1).max(40)}),ProjectLocaleMutationSchema=z53.object({locale:z53.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z53.object({locale:z53.string(),entriesDeleted:z53.number().int().nonnegative(),labelsDeleted:z53.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z54}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z54.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z54.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z54.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z54.number(),credits:z54.number().optional(),billingMode:z54.enum(["fimo-credits","provider-account"]).optional(),confidence:z54.enum(["exact","estimated","metered"]),basis:z54.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z55}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z55.object({options:z55.record(z55.string(),z55.unknown()),name:z55.string().optional(),parentId:z55.string().nullable().optional(),altText:z55.string().optional(),caption:z55.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z55.string().min(1).optional(),model:z55.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z55.object({jobId:z55.string(),status:z55.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z55.string().nullable().optional(),credits:z55.number().optional(),costUsd:z55.number().optional(),billingMode:z55.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z55.object({error:z55.string(),code:z55.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z55.array(GenerationTaskIdSchema).optional(),availableModels:z55.array(z55.string()).optional(),issues:z55.array(z55.unknown()).optional()})}});import{z as z56}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z56.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z56.object({name:z56.string(),key:z56.string(),description:z56.string(),type:FlagTypeSchema,required:z56.boolean(),defaultValue:z56.unknown().optional(),enumValues:z56.array(z56.string()).optional(),isArray:z56.boolean()}),AssetModelPriceSchema=z56.object({unitPrice:z56.number(),unit:z56.string(),confidence:z56.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z56.object({id:z56.string(),shortName:z56.string(),provider:z56.string(),source:z56.string(),modality:z56.enum(["image","video","audio"]),tags:z56.array(z56.string()),displayName:z56.string(),description:z56.string(),flags:z56.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z56.object({model:z56.string(),costUsd:z56.number(),credits:z56.number(),billingMode:z56.enum(["fimo-credits","provider-account"]),confidence:z56.enum(["exact","estimated","metered"]),basis:z56.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z57}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z57.object({tourId:z57.string(),version:z57.string(),status:z57.string(),completedAt:z57.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z57.array(UserTourDTOSchema))}});import{z as z58}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z58.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z58.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z58.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z58.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z58.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z58.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z58.enum(["user","agent","system"]),SupportReportTagSchema=z58.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z58.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z58.object({organization:z58.object({id:z58.string().trim().min(1).max(255),name:z58.string().trim().max(240).optional()}),project:z58.object({id:z58.uuid(),name:z58.string().trim().max(240).optional(),createdAt:z58.coerce.date().optional()}).optional(),environment:z58.string().trim().max(255).optional(),clientVersion:z58.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z58.object({message:z58.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z58.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z58.string().trim().max(200).optional(),limit:z58.coerce.number().int().min(1).max(100).default(50),offset:z58.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z58.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z58.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z58.uuid().nullable().optional(),note:z58.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z58.object({message:z58.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z58.object({kind:SupportReportLinkKindSchema,label:z58.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z58.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z58.object({kind:SupportReportActorKindSchema,id:z58.string().nullable(),name:z58.string().nullable()}),SupportReportLinkDTOSchema=z58.object({id:z58.uuid(),kind:SupportReportLinkKindSchema,label:z58.string(),url:SupportReportHttpUrlSchema,externalId:z58.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z58.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z58.object({id:z58.uuid(),kind:SupportReportEventKindSchema,body:z58.string().nullable(),metadata:z58.record(z58.string(),z58.unknown()),actor:SupportReportActorDTOSchema,createdAt:z58.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z58.object({id:z58.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z58.array(z58.string()),source:SupportReportSourceSchema,message:z58.string(),reporter:z58.object({id:z58.string().nullable(),name:z58.string().nullable(),email:z58.string().nullable()}),organization:z58.object({id:z58.string().nullable(),name:z58.string()}),project:z58.object({id:z58.uuid().nullable(),name:z58.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z58.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z58.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}).nullable(),duplicateOfReportId:z58.uuid().nullable(),resolvedAt:z58.coerce.date().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z58.string().nullable(),clientVersion:z58.string().nullable(),links:z58.array(SupportReportLinkDTOSchema),events:z58.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z58.object({reports:z58.array(SupportReportSummaryDTOSchema),total:z58.number().int().nonnegative(),statusCounts:z58.object({new:z58.number().int().nonnegative(),in_progress:z58.number().int().nonnegative(),waiting:z58.number().int().nonnegative(),resolved:z58.number().int().nonnegative(),duplicate:z58.number().int().nonnegative(),irrelevant:z58.number().int().nonnegative(),ignored:z58.number().int().nonnegative()}),limit:z58.number().int().positive(),offset:z58.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z58.object({id:z58.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z58.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z59}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z59.iso.datetime({offset:!0}).pipe(z59.coerce.date()),OpsRecentChatInputSchema=z59.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z59.string().trim().min(1).max(255).optional(),limit:z59.coerce.number().int().min(1).max(200).default(100),cursor:z59.string().trim().min(1).max(2e3).optional(),slim:z59.boolean().default(!0),reason:z59.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z59.object({id:z59.string(),threadId:z59.string(),providerMessageId:z59.string().nullable(),invocationId:z59.string().nullable(),env:z59.string().nullable(),role:z59.string(),parts:z59.array(z59.record(z59.string(),z59.unknown())),metadata:z59.object({status:z59.string().optional(),traceUrl:z59.string().optional(),externalFileChanges:z59.array(z59.unknown()).optional()}),stats:z59.object({toolCount:z59.number().int().nonnegative(),failedToolCount:z59.number().int().nonnegative()}),createdAt:z59.iso.datetime({offset:!0}),project:z59.object({id:z59.string(),name:z59.string(),displayName:z59.string().nullable(),organizationId:z59.string().nullable()})}),OpsRecentChatResponseSchema=z59.object({target:z59.object({backendProfile:OpsBackendProfileSchema,projectEnv:z59.string().nullable()}),window:z59.object({from:z59.iso.datetime({offset:!0}),to:z59.iso.datetime({offset:!0})}),messages:z59.object({items:z59.array(OpsRecentChatMessageSchema),nextCursor:z59.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z60}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z60.object({backendProfile:OpsBackendProfileSchema,provider:z60.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z60.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z60.object({backendProfile:OpsBackendProfileSchema,provider:z60.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z60.literal(!1),reason:z60.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z61}from"zod";function createAgentRunWebhookEventDataSchema(status){return z61.object({run:z61.object({id:z61.string(),agentName:z61.string(),trigger:z61.string(),status:z61.literal(status),startedAt:z61.string().nullable(),finishedAt:z61.string().nullable(),reason:z61.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z61.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z61.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z61.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z61.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z61.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z61.union([z61.literal(0),z61.literal(5),z61.literal(30),z61.literal(60)]),EntryChangedWebhookEventDataSchema=z61.object({reason:WebhookEntryChangeReasonSchema,operationId:z61.string().optional(),batch:z61.object({index:z61.number().int().positive(),total:z61.number().int().positive()}).optional(),changes:z61.array(z61.object({action:WebhookEntryChangeActionSchema,contentType:z61.string(),id:z61.string(),documentId:z61.string(),locale:z61.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z61.object({form:z61.object({id:z61.string(),label:z61.string()}),submission:z61.object({id:z61.string(),data:z61.record(z61.string(),z61.unknown()),submittedAt:z61.string()})}),PublishStartedWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("publishing"),startedAt:z61.string()})}),PublishSucceededWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("published"),url:z61.string(),publishedAt:z61.string(),firstPublish:z61.boolean()})}),PublishFailedWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("failed"),reason:z61.string()})}),PublishUnpublishedWebhookEventDataSchema=z61.object({publication:z61.object({previousUrl:z61.string(),unpublishedAt:z61.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z61.object({review:z61.object({id:z61.string(),runId:z61.string(),agentName:z61.string(),classification:z61.string(),summary:z61.string(),reasons:z61.array(z61.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z61.object({review:z61.object({id:z61.string(),runId:z61.string(),agentName:z61.string(),resolution:z61.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z61.object({report:z61.object({weekStart:z61.string(),weekEnd:z61.string(),pageviews:z61.number(),visitors:z61.number(),previousPageviews:z61.number(),previousVisitors:z61.number()})}),MediaAssetWebhookEventDataSchema=z61.object({id:z61.string().nullable(),name:z61.string().nullable(),type:z61.string(),mimeType:z61.string().nullable(),fileSize:z61.number().nullable()}),MediaUploadedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.enum(["updated","moved","analysis"]),analysis:z61.object({category:z61.string(),status:z61.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("generated"),generation:z61.object({model:z61.string(),mode:z61.string()})}),MediaProcessingFailedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.enum(["analysis","generation"]),failure:z61.object({code:z61.string()})}),DomainCreatedWebhookEventDataSchema=z61.object({domain:z61.object({id:z61.string(),hostname:z61.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z61.object({domain:z61.object({id:z61.string(),hostname:z61.string()})}),LabelChangedWebhookEventDataSchema=z61.object({changes:z61.array(z61.object({action:z61.enum(["created","updated","deleted"]),key:z61.string(),locale:z61.string(),value:z61.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),isDefault:z61.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),previousCode:z61.string()})}),LocaleDeletedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),entriesDeleted:z61.number().int().nonnegative(),labelsDeleted:z61.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z61.object({merge:z61.object({id:z61.string(),from:EnvSchema,to:EnvSchema,applied:z61.array(z61.object({surface:SurfaceNameSchema,count:z61.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema}),version:z61.object({versionId:z61.uuid(),name:z61.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z61.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z61.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z61.discriminatedUnion("source",[z61.object({source:z61.literal("literal"),value:z61.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z61.object({source:z61.literal("secret"),key:z61.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z61.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z61.object({name:z61.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z61.object({name:z61.string(),source:z61.enum(["literal","secret"]),secretKey:z61.string().nullable(),secretPrefix:z61.string().nullable(),configured:z61.literal(!0)}),WebhookFilterSchema=z61.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z61.string().min(1).max(255).optional(),agentName:z61.string().min(1).max(120).optional(),mediaType:z61.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z61.string().min(1).max(255).optional(),locale:z61.string().min(1).max(120).optional()}),JsonValueSchema=z61.lazy(()=>z61.union([z61.string(),z61.number(),z61.boolean(),z61.null(),z61.array(JsonValueSchema),z61.record(z61.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z61.object({name:z61.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z61.url(),enabled:z61.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z61.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z61.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z61.object({name:z61.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z61.url().optional(),enabled:z61.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z61.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z61.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z61.object({eventType:WebhookEventTypeSchema.optional(),data:z61.record(z61.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z61.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z61.uuid(),name:z61.string(),eventType:WebhookEventTypeSchema,enabled:z61.boolean(),destination:z61.object({host:z61.string(),maskedUrl:z61.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z61.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z61.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z61.coerce.date().nullable(),deliveryStats24h:z61.object({succeeded:z61.number().int().nonnegative(),failed:z61.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z61.uuid(),projectId:z61.uuid(),env:EnvSchema,environment:EnvironmentKeySchema,branch:EnvSchema,eventId:z61.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z61.number().int().positive(),test:z61.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z61.number().int().nonnegative(),responseStatus:z61.number().int().nullable(),lastErrorCode:z61.string().nullable(),lastErrorMessage:z61.string().nullable(),payloadAvailable:z61.boolean(),destination:z61.object({host:z61.string(),maskedUrl:z61.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z61.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z61.string().nullable(),qstashMessageId:z61.string().nullable(),deliveredAt:z61.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z61.object({items:z61.array(WebhookDeliveryDTOSchema),pagination:z61.object({page:z61.number().int().positive(),limit:z61.number().int().positive(),total:z61.number().int().nonnegative(),totalPages:z61.number().int().positive(),hasMore:z61.boolean()}),stats:z61.object({total:z61.number().int().nonnegative(),succeeded:z61.number().int().nonnegative(),failed:z61.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z61.object({id:z61.uuid(),deliveryId:z61.uuid(),attempt:z61.number().int().positive(),status:z61.enum(["delivering","succeeded","failed"]),responseStatus:z61.number().int().nullable(),durationMs:z61.number().int().nonnegative(),responseExcerpt:z61.string().nullable(),errorCode:z61.string().nullable(),errorMessage:z61.string().nullable(),createdAt:z61.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z61.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z61.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z62}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z62.object({key:z62.literal("fimo-2"),enabled:z62.boolean(),dismissed:z62.boolean().default(!1),interacted:z62.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z63}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z63.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z63.object({total:z63.number(),base:z63.number(),purchases:z63.number(),awards:z63.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z63.object({id:z63.string(),name:z63.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z63.object({type:z63.string(),brand:z63.string().nullable(),last4:z63.string().nullable(),expirationDate:z63.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z63.object({currency:z63.string(),nextPaymentAmount:z63.number().nullable(),nextPaymentAt:z63.string().nullable(),billingInterval:z63.string().nullable(),totalAmount:z63.number().nullable(),discountAmount:z63.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z63.object({id:z63.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z63.string().nullable(),currentPeriodEndsAt:z63.string().nullable(),renewsAt:z63.string().nullable(),cancelAt:z63.string().nullable(),renewAutomatically:z63.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z63.object({type:z63.enum(["low_balance","critical_balance","approaching_limit"]),message:z63.string(),estimatedPromptsRemaining:z63.number().nullable(),avgCostPerPrompt:z63.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z63.object({monthlyCredits:z63.number().nullable(),usedThisPeriod:z63.number(),remainingThisPeriod:z63.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z63.object({organizationId:z63.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z63.string().nullable(),tenureDays:z63.number().int().nonnegative(),capturedAt:z63.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z63.object({hasSubscription:z63.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z63.number().nullable(),alerts:z63.array(CreditAlertDTOSchema),portalUrl:z63.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z63.object({creditCount:z63.number().int().positive(),expiresAt:z63.string().datetime().nullable().optional(),message:z63.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z63.literal("free"),amountCents:z63.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z63.literal("purchase"),amountCents:z63.number().int().positive()}),CreditTopupRequestDTOSchema=z63.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z63.object({success:z63.boolean(),transactionId:z63.string().nullable(),newBalance:z63.number(),creditCount:z63.number(),type:z63.enum(["free","purchase"]),invoiceId:z63.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z64}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z64.object({totalCredits:z64.number(),totalCostUsd:z64.number(),totalMessages:z64.number(),avgCostPerMessage:z64.number(),periodStart:z64.string().nullable(),periodEnd:z64.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z64.object({projectId:z64.string(),projectName:z64.string(),projectDisplayName:z64.string().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z64.object({userId:z64.string(),userName:z64.string().nullable(),userEmail:z64.string().email().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z64.object({date:z64.string(),credits:z64.number(),costUsd:z64.number(),messages:z64.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z64.object({userId:z64.string(),userName:z64.string().nullable(),userEmail:z64.string().email().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z64.object({projectId:z64.string(),projectName:z64.string(),projectDisplayName:z64.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z64.array(UsageByUserForProjectDTOSchema),timeline:z64.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z64.object({summary:UsageSummaryDTOSchema,byProject:z64.array(UsageByProjectDTOSchema),byUser:z64.array(UsageByUserDTOSchema),timeline:z64.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z65}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z65.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z65.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z65.object({startDate:z65.string().optional(),endDate:z65.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z65.coerce.number().int().positive().default(1),limit:z65.coerce.number().int().positive().max(100).default(20),sortBy:z65.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z65.string().optional(),activeOnly:z65.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z65.object({totalCredits:z65.number(),totalCostUsd:z65.number(),totalMessages:z65.number(),avgCostPerMessage:z65.number(),avgCreditsPerMessage:z65.number(),periodStart:z65.string(),periodEnd:z65.string(),creditsChange:z65.number().nullable(),costChange:z65.number().nullable(),messagesChange:z65.number().nullable(),unattributedCredits:z65.number(),unattributedCostUsd:z65.number(),unattributedMessages:z65.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z65.object({date:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z65.object({organizationId:z65.string(),organizationName:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),userCount:z65.number(),projectCount:z65.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z65.object({userId:z65.string(),userName:z65.string().nullable(),userEmail:z65.string().nullable(),userImage:z65.string().nullable(),organizationId:z65.string().nullable(),organizationName:z65.string().nullable(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),projectCount:z65.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z65.object({projectId:z65.string(),projectName:z65.string(),projectDisplayName:z65.string().nullable(),organizationId:z65.string(),organizationName:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),userCount:z65.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z65.object({id:z65.string(),name:z65.string(),value:z65.number(),percentage:z65.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z65.object({day:z65.number(),hour:z65.number(),value:z65.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z65.object({summary:UsageOverviewSummaryDTOSchema,timeline:z65.array(UsageTimelinePointDTOSchema),topOrganizations:z65.array(OrganizationUsageRowDTOSchema),topUsers:z65.array(UserUsageRowDTOSchema),topProjects:z65.array(ProjectUsageRowDTOSchema),creditDistribution:z65.array(UsageDistributionItemDTOSchema),userDistribution:z65.array(UsageDistributionItemDTOSchema),heatmap:z65.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z65.object({page:z65.number(),limit:z65.number(),totalItems:z65.number(),totalPages:z65.number(),hasMore:z65.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z65.object({organizations:z65.array(OrganizationUsageRowDTOSchema),top:z65.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z65.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z65.object({users:z65.array(ExtendedUserUsageRowDTOSchema),top:z65.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z65.string(),ownerName:z65.string().nullable(),ownerEmail:z65.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z65.object({projects:z65.array(ExtendedProjectUsageRowDTOSchema),top:z65.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z65.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z65.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z65.object({credits:z65.number(),costUsd:z65.number(),messages:z65.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z65.object({id:z65.string(),name:z65.string(),createdAt:z65.string(),memberCount:z65.number(),projectCount:z65.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z65.object({id:z65.string(),name:z65.string().nullable(),email:z65.string(),image:z65.string().nullable(),createdAt:z65.string(),organizationCount:z65.number(),projectCount:z65.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z65.object({id:z65.string(),name:z65.string(),displayName:z65.string().nullable(),createdAt:z65.string(),organizationId:z65.string(),organizationName:z65.string(),ownerId:z65.string(),ownerName:z65.string().nullable(),ownerEmail:z65.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z66}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z66.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z66.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z66.object({command:z66.string().min(1).max(1e4),cwd:z66.string().optional(),projectEnv:EnvSchema.optional(),env:z66.record(z66.string(),z66.string()).optional(),name:z66.string().optional(),waitForCompletion:z66.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z66.object({identifier:z66.string(),status:SandboxProcessStatusSchema,command:z66.string().optional(),startedAt:z66.string().optional(),exitCode:z66.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z66.object({processes:z66.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z66.object({processId:z66.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z66.object({success:z66.boolean(),message:z66.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z67}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_fimo_config();init_page_sources();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&¶ms.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path50,message}=issue;return`${Array.isArray(path50)&&path50.length>0?`${path50.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,env){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(env)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,env,base)===normalized?base:void 0}catch{return}}var SandboxReadinessError,ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");SandboxReadinessError=class extends Error{static{__name(this,"SandboxReadinessError")}constructor(message){super(message),this.name="SandboxReadinessError"}},ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path50,status,detail,code2,body){super(`API ${method} ${path50} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path50,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}cfg;static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path50,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path50}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path50,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path50,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env),fimoFetch(`${this.cfg.apiUrl}${path50}`,{...init,headers})}async rawRequest(path50,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path50}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path50} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId){await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST"})}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&¶ms.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts){let query=new URLSearchParams({environment:opts.environment});return opts.kind&&query.set("kind",opts.kind),(await this.request(`/api/management/projects/${projectId}/secrets?${query.toString()}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value,environment:input.environment})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value,environment:input.environment})})).data}async deleteProjectSecretEntry(projectId,key,kind,environment){let qs=new URLSearchParams({kind,environment});await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}?${qs.toString()}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.cursor&¶ms.set("cursor",query.cursor),query.status&¶ms.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&¶ms.set("includeDeleted","true"),opts.includeAgentEnvs&¶ms.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listEnvs(projectId,{includeAgentEnvs:!0}),current=branches.find(candidate=>candidate.env===branch),visited=new Set;for(;current&&!visited.has(current.env);){if(visited.add(current.env),current.resolvedEnvironment)return current.resolvedEnvironment.id;current=current.parentEnv?branches.find(candidate=>candidate.env===current?.parentEnv):void 0}return PREVIEW_ENVIRONMENT_KEY}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path50,opts={}){let qs=lazyFetchQs(opts.against,{path:path50});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path50=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path50}?${qs}`:path50)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path50=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path50}?${qs}`:path50)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path50=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path50}?${qs}`:path50)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path50=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path50}?${qs}`:path50)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path50=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path50}?${qs}`:path50)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&¶ms.set("agent_name",opts.agentName),opts.env&¶ms.set("env",opts.env),opts.status&¶ms.set("status",opts.status),opts.limit!==void 0&¶ms.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){let remote=(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,env);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectEnvManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox`)).data}async getSandboxLogs(projectId,env,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.before&¶ms.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,env,options={}){let params=new URLSearchParams;options.noRestart&¶ms.set("noRestart","true"),options.wait!==void 0&¶ms.set("wait",String(options.wait));let search=params.toString(),query=search?`?${search}`:"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage4=null,errorCode,readiness=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
42
|
+
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue2=data2[key];result[key]=filterUnknownProperties(fieldValue2,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","datetime","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ARCHIVE_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:20971520},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:20971520},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:20971520},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:20971520},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:5242880},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:5242880},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:5242880},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:5242880},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:5242880},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880},{mime:"application/zip",extensions:[".zip"],category:"archive",maxSizeBytes:20971520},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:10485760},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:10485760},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:10485760},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:10485760},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:20971520},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:20971520},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:20971520},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:20971520},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:20971520},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:20971520},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:20971520}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ARCHIVE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="archive").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z5}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(env);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z5.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv");__name(fnv1a8,"fnv1a8");__name(envResourceKey,"envResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl")}});import{z as z6}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z6.union([z6.literal(PRODUCTION_ENVIRONMENT_KEY),z6.literal(PREVIEW_ENVIRONMENT_KEY),z6.uuid()]),CustomEnvironmentSchema=z6.object({id:z6.uuid(),projectId:z6.uuid(),name:z6.string().trim().min(1).max(64),branchPatterns:z6.array(z6.string().min(1).max(255)).min(1),description:z6.string().max(255).nullable()}),ResolvedEnvironmentSchema=z6.object({branch:EnvSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});import{z as z7}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z7.preprocess(referenceValuePreprocess,z7.object({documentId:z7.uuid()})),ReferenceInputValueSchema=z7.preprocess(referenceValuePreprocess,z7.union([z7.object({documentId:z7.uuid()}),z7.object({slug:z7.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z7.preprocess(polymorphicReferenceValuePreprocess,z7.object({contentType:z7.string().min(1),documentId:z7.uuid()})),PolymorphicReferenceInputValueSchema=z7.preprocess(polymorphicReferenceValuePreprocess,z7.union([z7.object({contentType:z7.string().min(1),documentId:z7.uuid()}),z7.object({contentType:z7.string().min(1),slug:z7.string().min(1)})]))}});import{z as z8}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path50){let conditionPath=[...path50,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path50)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path50));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path50,fieldName,variant.uid]);else walk(field.schema.fields,[...path50,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path50,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path50,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z8.union([z8.object({field:z8.string().min(1),equals:z8.union([z8.string(),z8.number(),z8.boolean()])}).strict(),z8.object({field:z8.string().min(1),in:z8.array(z8.union([z8.string(),z8.number(),z8.boolean()])).min(1)}).strict()]),commonFieldShape={label:z8.string().min(1).optional(),description:z8.string().optional(),editable:z8.boolean().optional(),required:z8.boolean().optional(),default:z8.unknown().optional(),showIf:z8.union([showIfClauseSchema,z8.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z8.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z8.object({...commonFieldShape,type:z8.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z8.number().optional(),max:z8.number().optional(),minLength:z8.number().int().nonnegative().optional(),maxLength:z8.number().int().nonnegative().optional(),regex:z8.string().optional(),multiple:z8.boolean().optional(),allowedMimeTypes:z8.array(z8.string()).optional(),options:z8.array(z8.string().min(1)).min(1).optional(),unique:z8.boolean().optional(),i18n:z8.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z8.object({...commonFieldShape,type:z8.literal("reference"),target:z8.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z8.array(z8.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z8.boolean().optional(),i18n:z8.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z8.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z8.record(z8.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z8.object({uid:z8.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z8.string().min(1),description:z8.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z8.object({fields:blockFieldsSchema}).strict(),blocksSchema=z8.object({oneOf:z8.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z8.object({...commonFieldShape,type:z8.literal("blocks"),min:z8.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z8.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z8.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z8.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z9}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","cutover_step","agent_delegate","version_restore","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_agent_provider_errors_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","admin_resource_read","merge_force"],AuditActionSchema=z9.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z9.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z9.enum(AUDIT_ACTOR_KINDS)}});import{z as z10}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z10.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z10.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z10.object({permissions:z10.array(OpsPermissionSchema).min(1),backendProfiles:z10.array(OpsBackendProfileSchema).min(1),enabled:z10.boolean().default(!0)}),OpsServiceTokenInputSchema=z10.object({name:z10.string().trim().min(1).max(120),permissions:z10.array(OpsPermissionSchema).min(1),backendProfiles:z10.array(OpsBackendProfileSchema).min(1),expiresAt:z10.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z10.object({importanceReason:z10.string().trim().min(1).max(1e3),ownerUserId:z10.string().trim().min(1).nullable().optional(),framework:z10.string().trim().max(120).nullable().optional(),packageManager:z10.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z10.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z10.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z10.object({projectId:z10.uuid(),title:z10.string().trim().min(1).max(240),userReport:z10.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z10.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z10.string().trim().max(1e4).nullable().optional(),outcome:z10.string().trim().max(1e4).nullable().optional(),evidence:z10.array(z10.record(z10.string(),z10.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z10.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z10.object({fingerprint:z10.string().trim().min(1).max(240),title:z10.string().trim().min(1).max(240),description:z10.string().trim().min(1).max(1e4),affectedVersions:z10.array(z10.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z10.array(z10.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z10.string().trim().min(1).max(64).nullable().optional(),workaround:z10.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z10.array(z10.string().trim().min(1).max(120)).max(100),detectionQueries:z10.array(z10.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z10.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z10.object({changeReference:z10.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z10.string().trim().min(1).max(1e4),evidence:z10.array(z10.record(z10.string(),z10.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z10.object({recipientEmail:z10.email().optional(),subject:z10.string().trim().min(1).max(200).default("An update from Fimo"),message:z10.string().trim().min(1).max(5e3),locale:z10.string().trim().min(2).max(20),reason:z10.string().trim().min(1).max(1e3),acknowledgePolicy:z10.literal(!0)}),OpsSentryIssueIdSchema=z10.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z10.object({reason:z10.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z10.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z10.object({projectId:z10.uuid(),from:z10.coerce.date(),to:z10.coerce.date(),reason:z10.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBraintrustSpanIdSchema=z10.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z10.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z10.object({projectId:z10.uuid().optional(),organizationId:z10.string().trim().min(1).max(255).optional(),agentKey:z10.string().trim().min(1).max(120).optional(),threadId:z10.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z10.coerce.date().optional(),minCostUsd:z10.coerce.number().min(0).optional(),tracedOnly:z10.coerce.boolean().default(!1),limit:z10.coerce.number().int().min(1).max(100).default(25),reason:z10.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z10.object({limit:z10.coerce.number().int().min(1).max(500).default(200),reason:z10.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z10.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z10.object({maxChars:z10.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z10.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z10.object({messageIndex:z10.coerce.number().int().min(0).optional(),maxChars:z10.coerce.number().int().min(500).max(2e5).default(2e4),reason:z10.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z10.enum(["agent","status","env","project","day"]),OpsAgentHealthInputSchema=z10.object({projectId:z10.uuid().optional(),organizationId:z10.string().trim().min(1).max(255).optional(),env:z10.string().trim().min(1).max(64).optional(),agentKey:z10.string().trim().min(1).max(120).optional(),since:z10.coerce.date(),until:z10.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z10.coerce.boolean().default(!1),limit:z10.coerce.number().int().min(1).max(200).default(50),reason:z10.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentTraceStatsGroupBySchema=z10.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z10.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z10.object({since:z10.coerce.date(),until:z10.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z10.coerce.number().min(0).optional(),limit:z10.coerce.number().int().min(1).max(200).default(50),reason:z10.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentProviderErrorsInputSchema=z10.object({since:z10.coerce.date(),until:z10.coerce.date().optional(),model:z10.string().trim().min(1).max(120).optional(),provider:z10.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z10.coerce.date().optional(),limit:z10.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z10.coerce.number().int().min(200).max(2e4).default(1200),reason:z10.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsBillingCacheInvalidateInputSchema=z10.object({reason:z10.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z10.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z10.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z10.discriminatedUnion("kind",[z10.object({kind:z10.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z10.object({kind:z10.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z10.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z10.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z10.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z10.object({migrationId:OpsMigrationIdSchema,projectEnv:z10.string().trim().min(1).max(255).default("main"),reason:z10.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z10.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z10.string().trim().min(1).max(1e3),OpsProjectFileReadInputSchema=z10.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z10.object({pattern:z10.string().min(1).max(300).optional(),limit:z10.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z10.object({pattern:z10.string().min(1).max(200),include:z10.string().min(1).max(300).optional(),caseInsensitive:z10.boolean().default(!1),maxMatches:z10.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z10.object({path:OpsProjectFilePathSchema,content:z10.string().max(256*1024),overwrite:z10.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z10.string().trim().length(64),consentReference:z10.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z10.intersection(OpsProjectOperationPlanInputSchema,z10.object({planHash:z10.string().trim().length(64),reason:z10.string().trim().min(1).max(1e3),consentReference:z10.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z10.object({planHash:z10.string().trim().length(64),reason:z10.string().trim().min(1).max(1e3),consentReference:z10.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)})}});import{z as z11}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt)}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z11.object({kind:z11.literal("say"),label:z11.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z11.string().min(1).max(240).optional(),message:z11.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z11.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z11.object({kind:z11.literal("app"),command:z11.literal("publish")}).strict(),BlockBaseSchema=z11.object({fallback:z11.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z11.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z11.literal("choices"),text:z11.string().max(500).optional(),actions:z11.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z11.discriminatedUnion("kind",[z11.object({kind:z11.literal("entry"),collection:z11.string().min(1).max(80),entryId:z11.string().min(1).max(120)}),z11.object({kind:z11.literal("asset"),assetId:z11.string().min(1).max(120)}),z11.object({kind:z11.literal("url"),url:z11.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z11.literal("table"),columns:z11.array(z11.object({label:z11.string().min(1).max(24)})).min(2).max(4),rows:z11.array(z11.object({cells:z11.array(z11.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z11.literal("cards"),layout:z11.enum(["rail","stack"]).optional(),items:z11.array(z11.object({title:z11.string().min(1).max(60),subtitle:z11.string().min(1).max(120).optional(),imageUrl:z11.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z11.literal("entry"),label:z11.string().min(1).max(80),collection:z11.string().min(1).max(80),entryId:z11.string().min(1).max(120),path:z11.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z11.literal("assets"),items:z11.array(z11.object({url:z11.url({protocol:/^https$/}).max(2e3),alt:z11.string().min(1).max(120),label:z11.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z11.literal("callout"),title:z11.string().min(1).max(80),text:z11.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z11.literal("stat"),items:z11.array(z11.object({label:z11.string().min(1).max(24),value:z11.string().min(1).max(16),delta:z11.string().min(1).max(12).optional(),tone:z11.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z11.literal("chart"),unit:z11.string().min(1).max(12).optional(),points:z11.array(z11.object({label:z11.string().min(1).max(12),value:z11.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),ChatFormBodySchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z11.object({question:z11.string().min(1).max(500),header:z11.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z11.boolean(),recommended:z11.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."})}),FormBlockSchema=BlockBaseSchema.extend({type:z11.literal("form"),steps:z11.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z11.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z11.object({header:z11.string().min(1).max(25),question:z11.string().min(1).max(500),answer:z11.string().min(1).max(3e3),selectedLabels:z11.array(z11.string().min(1).max(120)).max(8),freeText:z11.string().max(2e3),skipped:z11.boolean()}),ChatFormAnswerMetadataSchema=z11.object({toolCallId:z11.string().max(255).optional(),shortTitle:z11.string().max(80).optional(),questions:z11.array(ChatFormAnswerItemSchema).max(4)}),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z11.string().min(1).max(255)})}});import{z as z12}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z12.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z12.object({dev:z12.string().trim().min(1).optional(),build:z12.string().trim().min(1).optional(),install:z12.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z12.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z12.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z12.object({type:z12.enum(["header","cookie","query","host"]),key:z12.string().min(1).optional(),value:z12.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z12.array(FimoHostingConditionSchema).min(1).optional(),missing:z12.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z12.object({source:z12.string().min(1),destination:z12.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z12.object({source:z12.string().min(1),destination:z12.string().min(1),permanent:z12.boolean().optional(),statusCode:z12.union([z12.literal(301),z12.literal(302),z12.literal(307),z12.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z12.object({source:z12.string().min(1),headers:z12.array(z12.object({key:z12.string().min(1),value:z12.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z12.object({rewrites:z12.array(FimoHostingRewriteSchema).optional(),redirects:z12.array(FimoHostingRedirectSchema).optional(),headers:z12.array(FimoHostingHeaderSchema).optional(),cleanUrls:z12.boolean().optional(),trailingSlash:z12.boolean().optional()}).strict(),FimoAppConfigSchema=z12.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path50){return[...path50.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path50){return pageRouteParamNames(path50).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record2=value;return typeof record2.id=="string"?record2.id:Object.fromEntries(Object.entries(record2).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});import{z as z13}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z13.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z13.string(),displayName:z13.string().nullable(),subdomain:z13.string().nullable().optional(),subdomainUpdatedAt:z13.date().nullable().optional(),organizationId:z13.string().nullable(),createdBy:z13.string().nullable(),previewEnabled:z13.boolean().default(!0),enabledChatModels:z13.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z13.string(),thumbnailUrl:z13.string().nullable(),publishedThumbnailUrl:z13.string().nullable(),category:z13.string().nullable(),appUrl:z13.string().nullable(),lastPublishedAt:z13.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z13.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z13.object({id:z13.uuid(),name:z13.string(),displayName:z13.string().nullable(),thumbnailUrl:z13.string().nullable(),category:z13.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z13.object({id:z13.string(),name:z13.string(),avatar:z13.string().nullable(),color:z13.object({bg:z13.string(),text:z13.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z13.object({path:z13.string(),content:z13.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z13.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z13.object({id:z13.string(),messageId:z13.string(),versionId:z13.string().nullable(),role:ProjectChatMessageRole,parts:z13.array(z13.any()),createdAt:z13.coerce.date()}),MessageUserMetadataSchema=z13.object({id:z13.string(),name:z13.string().nullable().optional(),image:z13.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z13.number(),metadata:z13.object({user:MessageUserMetadataSchema,changeManifest:z13.array(z13.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z13.object({versionId:z13.uuid(),commitHash:z13.string(),name:z13.string(),description:z13.string().nullable(),kind:z13.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z13.object({versionCount:z13.number().int().nonnegative(),snapshotBytes:z13.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z13.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z13.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z13.object({content:z13.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z13.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z13.object({success:z13.boolean(),message:z13.string().optional(),warning:z13.string().optional(),durationMs:z13.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z13.object({isPublished:z13.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z13.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z13.object({success:z13.boolean(),message:z13.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z13.boolean(),publicationId:z13.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z14}from"zod";var ProjectEnvStatusSchema,ProjectEnvKindSchema,ProjectEnvDTOSchema,ProjectEnvDTO,ResolvedBranchEnvironmentDTOSchema,ProjectEnvListItemDTOSchema,ProjectEnvListItemDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectEnvStatusSchema=z14.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z14.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z14.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,parentEnv:EnvSchema.nullable(),createdBy:z14.string().nullable(),deletedAt:z14.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),ResolvedBranchEnvironmentDTOSchema=z14.object({id:z14.union([z14.literal(PREVIEW_ENVIRONMENT_KEY),z14.uuid()]),name:z14.string()}),ProjectEnvListItemDTOSchema=ProjectEnvDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectEnvListItemDTO=createDTO(ProjectEnvListItemDTOSchema),CreateProjectEnvRequestSchema=z14.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z14.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z14.array(ProjectEnvListItemDTOSchema)),EnvSurfaceDiffSchema=z14.object({surface:z14.enum(["code","schemas","content","translations","assets","forms"]),status:z14.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z14.number().int().nonnegative(),conflictCount:z14.number().int().nonnegative()}),EnvDiffResultSchema=z14.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z14.coerce.date(),surfaces:z14.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z15}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z15.object({projectId:z15.uuid(),name:z15.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z15.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z15.literal("production"),sourceBranch:EnvSchema,isPublished:z15.boolean(),url:z15.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z15.literal(PREVIEW_ENVIRONMENT_KEY),kind:z15.literal("preview"),matchedBranchCount:z15.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z15.literal("custom"),matchedBranchCount:z15.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z15.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z15.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z15.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z15.object({deletedId:z15.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z16}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z16.object({kind:z16.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z16.object({kind:z16.enum(["variable","secret"]),value:z16.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z16.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z16.object({kind:z16.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z16.object({id:z16.uuid(),projectId:z16.uuid(),key:z16.string(),kind:z16.literal("secret"),exposure:z16.literal("private"),environment:EnvironmentKeySchema,maskedValue:z16.string().optional(),createdAt:z16.date().transform(value=>value.toISOString()),updatedAt:z16.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z16.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z17}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z17.object({success:z17.literal(!0),downloadUrl:z17.string(),expiresAt:z17.string(),fileSize:z17.number(),duration:z17.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z17.object({success:z17.literal(!0),projectId:z17.string(),projectName:z17.string(),displayName:z17.string(),projectUrl:z17.string(),duration:z17.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z17.object({contentTypes:z17.number(),entries:z17.number(),assets:z17.number(),translations:z17.number(),forms:z17.number(),codeFiles:z17.number(),assetFiles:z17.number()}),ImportPreviewSurfaceDTOSchema=z17.object({name:z17.string(),included:z17.boolean(),count:z17.number().optional(),note:z17.string().optional()}),ImportPreviewDTOSchema=z17.object({projectName:z17.string(),displayName:z17.string().nullable(),category:z17.string().nullable(),exportedAt:z17.string(),version:z17.string(),envScope:z17.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z17.array(ImportPreviewSurfaceDTOSchema),fileSize:z17.number(),fileName:z17.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z17.object({success:z17.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z18}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z18.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z18.object({type:z18.literal("manual")}),ScheduleTriggerSchema=z18.object({type:z18.literal("schedule"),cron:z18.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z18.string().optional()}),WebhookTriggerSchema=z18.object({type:z18.literal("webhook"),path:z18.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z18.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z19}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z19.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z19.object({token:z19.string().min(1),risk:CapabilityRiskTierSchema,description:z19.string()}),AgentSubAgentSummarySchema=z19.object({name:z19.string().min(1),grant:z19.enum(["inherit","explicit"]),effectiveCaps:z19.array(z19.string().min(1))}),AgentInstallSummaryDTOSchema=z19.object({agentName:z19.string().min(1),env:z19.string().min(1),declaredCapabilities:z19.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z19.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z19.array(CapabilitySummaryEntrySchema),criticalCapabilities:z19.array(CapabilitySummaryEntrySchema),subAgents:z19.array(AgentSubAgentSummarySchema),declaresDelegate:z19.boolean(),cycle:z19.array(z19.string()).nullable(),missingSubAgents:z19.array(z19.string()),warnings:z19.array(z19.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z20}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z20.object({kind:TriggerKindSchema,summary:z20.string()}),AgentListItemTriggerStateSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z20.boolean(),wired:z20.boolean(),syncError:z20.string().nullable()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),triggerStates:z20.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z21.object({args:z21.unknown().optional(),requestId:z21.string().min(1).max(128).optional()}),DispatchSkippedSchema=z21.object({skipped:z21.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z21.object({sessionId:z21.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z21.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({env:EnvSchema,vs:EnvSchema,syncState:z22.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),agents:z22.array(z22.object({id:z22.string(),name:z22.string(),status:z22.enum(["active","paused","failed"]),lastRunAt:z22.coerce.date().nullable()})).optional(),crossSurface:z22.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z22.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z22.array(z22.object({surface:SurfaceNameSchema,count:z22.number().int().nonnegative()})),conflicts:z22.array(ConflictSchema).optional(),summary:z22.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z22.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z22.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z22.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z22.boolean().optional()}),ResolvedStrategySchema=z22.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z22.boolean()}),MergeRequestSchema=z22.object({from:EnvSchema,allowDirectMerge:z22.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z22.object({mergeId:z22.string().uuid(),streamUrl:z22.string(),strategy:ResolvedStrategySchema,acceptedAt:z22.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z22.object({mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z23.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z23.object({cpuMs:z23.number().nonnegative().default(0),netBytes:z23.number().nonnegative().default(0),walltimeMs:z23.number().nonnegative().default(0),llmTokensIn:z23.number().nonnegative().optional(),llmTokensOut:z23.number().nonnegative().optional(),stepCount:z23.number().int().nonnegative().optional(),toolCallCounts:z23.record(z23.string().min(1).max(120),z23.number().int().nonnegative()).optional()}),AgentSessionReviewPublicationSchema=z23.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z23.object({capturedAt:z23.coerce.date(),fingerprint:z23.string().min(1).max(256),counts:z23.object({code:z23.number().int().nonnegative(),content:z23.number().int().nonnegative(),schemas:z23.number().int().nonnegative(),labels:z23.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z23.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z23.object({diff:DiffReportSchema,code:z23.array(CodeFileDiffSchema.extend({raw:z23.string().max(24576)})).max(200),schemas:z23.array(SchemaTypeDiffSchema).max(200),content:z23.array(z23.object({key:z23.string().min(1).max(512),collection:z23.string().min(1).max(256),slug:z23.string().max(512).optional(),verb:z23.enum(["added","modified","deleted"]),fields:z23.array(z23.object({name:z23.string().min(1).max(256),before:z23.unknown().optional(),after:z23.unknown().optional()})).max(20)})).max(200),labels:z23.array(z23.object({key:z23.string().min(1).max(512),locale:z23.string().min(1).max(64).optional(),before:z23.unknown().nullable(),after:z23.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),env:EnvSchema,agentName:z23.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z23.unknown().optional(),capabilities:z23.array(z23.string()).optional(),dataSources:z23.array(z23.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z23.string().nullable(),startedAt:z23.coerce.date().nullable(),finishedAt:z23.coerce.date().nullable(),cancelledAt:z23.coerce.date().nullable(),costUsd:z23.number().nonnegative(),costCeilingUsd:z23.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z23.boolean(),lastCheckpointId:z23.uuid().nullable(),branchEnvId:z23.uuid().nullable(),parentSessionId:z23.uuid().nullable(),terminalReason:z23.string().nullable(),errorMessage:z23.string().nullable(),report:z23.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z23.string().nullable(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z23.object({id:z23.uuid(),sessionId:z23.uuid(),checkpointIdx:z23.number().int().nonnegative(),payloadRef:z23.string(),payloadSizeBytes:z23.number().int().nonnegative(),checksum:z23.string().length(64),createdAt:z23.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z23.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z23.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z23.object({session:AgentSessionDTOSchema,checkpoints:z23.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress"]),CancelSessionRequestSchema=z23.object({reason:z23.string().min(1).max(120).optional()})}});import{z as z24}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z25.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z25.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z25.enum(["secret_text"]),IntegrationCredentialUsageSchema=z25.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z25.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z25.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z25.object({mode:IntegrationAuthModeSchema,label:z25.string().min(1),description:z25.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z25.object({id:z25.string().min(1),label:z25.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z25.boolean()}),IntegrationToolDefinitionDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),description:z25.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z25.object({title:z25.string().min(1),description:z25.string().min(1),command:z25.string().min(1).optional()}),IntegrationInfoDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z25.array(IntegrationAuthModeDTOSchema),credentials:z25.array(IntegrationCredentialDefinitionDTOSchema),tools:z25.array(IntegrationToolDefinitionDTOSchema),recipes:z25.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),installed:z25.boolean(),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z25.string().nullable(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),connectionStatus:z25.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),installedAt:z25.coerce.date().nullable(),updatedAt:z25.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z25.string(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z25.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z25.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z25.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z25.object({value:z25.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z25.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z25.object({id:z25.uuid(),organizationId:z25.string().min(1),integrationKey:z25.string().min(1),alias:z25.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z25.string().min(1),externalAccountName:z25.string().nullable(),externalBotUserId:z25.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z25.array(z25.string()),connectedAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z25.object({alias:z25.string().min(1).max(120).optional(),token:z25.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z25.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z25.discriminatedUnion("mode",[z25.object({mode:z25.literal("personal"),alias:z25.string().min(1).max(120),token:z25.string().min(1)}),z25.object({mode:z25.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z25.object({integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z25.discriminatedUnion("mode",[z25.object({mode:z25.literal("personal"),integrationKey:z25.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z25.object({mode:z25.literal("oauth"),integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()})]),BindProjectChannelRequestSchema=z25.object({ref:z25.string().min(1),connectionAlias:z25.string().min(1).optional(),agentName:z25.string().min(1).max(160).nullable().optional(),force:z25.boolean().optional()}),ListProjectChannelsQuerySchema=z25.object({integrationKey:z25.string().min(1)}),SearchProjectChannelsQuerySchema=z25.object({integrationKey:z25.string().min(1),connectionAlias:z25.string().min(1),query:z25.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),connectionId:z25.uuid(),externalWorkspaceId:z25.string().min(1),externalChannelId:z25.string().min(1),externalChannelName:z25.string().nullable(),agentName:z25.string().nullable(),enabled:z25.boolean(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z25.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z25.object({id:z25.string().min(1),name:z25.string().min(1),visibility:z25.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z25.string().min(1).nullable(),canMove:z25.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z25.object({markdown:z25.boolean().optional(),summary:z25.boolean().optional(),links:z25.boolean().optional(),images:z25.boolean().optional(),html:z25.union([z25.literal("cleaned"),z25.literal("raw"),z25.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z25.object({url:z25.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z25.object({query:z25.string().min(1),maxResults:z25.number().int().positive().max(20).optional(),sources:z25.array(z25.enum(["web","news","images"])).min(1).max(3).optional(),categories:z25.array(z25.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z25.enum(["hour","day","week","month","year"]).optional(),location:z25.string().min(1).max(160).optional(),country:z25.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z25.object({url:z25.string().url(),search:z25.string().min(1).optional(),limit:z25.number().int().positive().max(200).optional(),includeSubdomains:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z25.object({url:z25.string().url(),limit:z25.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z25.object({text:z25.string().min(1).max(200).optional(),cron:z25.string().min(1).max(120).optional(),timezone:z25.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z25.object({type:z25.enum(["scrape","crawl"]).default("scrape"),urls:z25.array(z25.string().url()).min(1).max(50),scrapeOptions:z25.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z25.object({name:z25.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z25.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z25.string().min(1).max(2e3).optional(),judgeEnabled:z25.boolean().optional(),retentionDays:z25.number().int().min(1).max(365).optional(),notification:z25.object({email:z25.object({enabled:z25.boolean().default(!0),recipients:z25.array(z25.string().email()).min(1).max(20),includeDiffs:z25.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z25.object({monitorId:z25.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z25.string().uuid()}),RunProjectIntegrationToolRequestSchema=z25.object({tool:z25.string().min(1),input:z25.record(z25.string(),z25.unknown()),connectionAlias:z25.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z25.object({provider:z25.string().min(1),providerCredits:z25.number().nonnegative().optional(),providerCostUsd:z25.number().nonnegative().optional(),requests:z25.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z25.object({credits:z25.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()}),FirecrawlSearchToolOutputSchema=z25.object({query:z25.string(),provider:z25.literal("firecrawl"),warning:z25.string().optional(),results:z25.array(z25.object({title:z25.string(),url:z25.string(),snippet:z25.string().optional(),content:z25.string().optional(),score:z25.number().optional(),publishedAt:z25.string().optional()}))}),FirecrawlMapToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),count:z25.number(),links:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),description:z25.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),total:z25.number(),pages:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()})),warning:z25.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z25.object({cron:z25.string().optional(),text:z25.string().optional(),timezone:z25.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z25.object({id:z25.string().optional(),urls:z25.array(z25.string()).optional(),scrapeOptions:z25.record(z25.string(),z25.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z25.object({id:z25.string(),name:z25.string(),status:z25.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z25.string().nullable().optional(),lastRunAt:z25.string().nullable().optional(),currentCheckId:z25.string().nullable().optional(),targets:z25.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z25.string().nullable().optional(),judgeEnabled:z25.boolean().optional(),estimatedCreditsPerMonth:z25.number().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z25.object({id:z25.string(),monitorId:z25.string(),scheduledFor:z25.string().nullable().optional(),startedAt:z25.string().nullable().optional(),finishedAt:z25.string().nullable().optional(),estimatedCredits:z25.number().optional(),reservedCredits:z25.number().optional(),actualCredits:z25.number().optional(),billingStatus:z25.string().nullable().optional(),summary:z25.object({totalPages:z25.number().optional(),same:z25.number().optional(),changed:z25.number().optional(),new:z25.number().optional(),removed:z25.number().optional(),error:z25.number().optional()}).passthrough().optional(),error:z25.string().nullable().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitors:z25.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),deleted:z25.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),checks:z25.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),check:FirecrawlMonitorCheckOutputSchema,next:z25.string().optional()}),FirecrawlToolKeySchema=z25.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z25.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),tool:z25.string().min(1),connectionAlias:z25.string().min(1).nullable().optional(),output:z25.record(z25.string(),z25.unknown()),executedAt:z25.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z25.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z25.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z25.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z25.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z25.array(ProjectChannelCandidateDTOSchema))}});import{z as z26}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z26.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z26.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z26.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z26.object({userId:z26.string().min(1),name:z26.string(),email:z26.string().min(1),subscribed:z26.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z26.object({maxSubscribers:z26.number().int().positive(),subscriberCount:z26.number().int().nonnegative(),effectiveRecipientCount:z26.number().int().nonnegative(),currentUserSubscribed:z26.boolean(),candidates:z26.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z26.object({userIds:z26.array(z26.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z26.object({topic:UserManagedNotificationTopicSchema,enabled:z26.boolean(),source:z26.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z26.object({topics:z26.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z26.object({enabled:z26.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z26.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z26.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z26.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z26.string().nullable(),maskedEmail:z26.string().min(1),applied:z26.boolean(),expiresAt:z26.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z26.object({scheduleId:z26.string().min(1),scheduleName:z26.string(),projectId:z26.string().min(1),projectName:z26.string(),env:z26.string().min(1)}),FollowedSchedulesSchema=z26.object({schedules:z26.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z27}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z27.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z27.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z27.uuid(),env:z27.string().min(1),name:z27.string().min(1),cron:z27.string().min(1),command:z27.string().min(1),secretKeys:z27.array(z27.string().min(1)),enabled:z27.boolean(),lastRunAt:z27.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z27.string().nullable(),overPolicyReasons:z27.array(z27.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z27.object({name:z27.string().min(1).max(120),cron:z27.string().min(1).max(120),command:z27.string().min(1).max(500),secretKeys:z27.array(ProjectSecretKeySchema).default([]),enabled:z27.boolean().optional()}),UpdateProjectScheduleRequestSchema=z27.object({name:z27.string().min(1).max(120).optional(),cron:z27.string().min(1).max(120).optional(),command:z27.string().min(1).max(500).optional(),secretKeys:z27.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z27.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z27.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z27.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z27.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z27.object({maxRuns:z27.number().int().positive(),retentionDays:z27.number().int().positive().nullable(),outputRetentionDays:z27.number().int().positive(),maxOutputBytes:z27.number().int().positive()}),SchedulePolicyStateSchema=z27.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z27.object({code:z27.enum(["Free","Premium"]),source:z27.enum(["cached_subscription","free_fallback"]),activeSchedules:z27.object({used:z27.number().int().nonnegative(),limit:z27.number().int().positive()}),minCadenceMinutes:z27.number().int().positive(),maxRunMs:z27.number().int().positive(),concurrency:z27.object({used:z27.number().int().nonnegative(),limit:z27.number().int().positive()}),compute:z27.object({settledMs:z27.number().int().nonnegative(),reservedMs:z27.number().int().nonnegative(),includedMs:z27.number().int().positive(),remainingMs:z27.number().int().nonnegative(),resetsAt:z27.coerce.date()}),upgrade:z27.object({code:z27.literal("Premium"),activeSchedulesLimit:z27.number().int().positive(),minCadenceMinutes:z27.number().int().positive(),maxRunMs:z27.number().int().positive(),maxConcurrentRuns:z27.number().int().positive(),computeIncludedMs:z27.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z27.array(z27.string())}),ProjectScheduleUsageSchema=z27.object({runCount:z27.number().int().nonnegative(),runsWithOutput:z27.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z27.object({id:z27.uuid(),scheduleId:z27.uuid(),projectId:z27.uuid(),env:z27.string().min(1),scheduleName:z27.string().min(1),command:z27.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z27.object({id:z27.string().min(1),name:z27.string().min(1)}).nullable(),queuedAt:z27.coerce.date(),startedAt:z27.coerce.date().nullable(),finishedAt:z27.coerce.date().nullable(),exitCode:z27.number().int().nullable(),errorCode:z27.string().nullable(),error:z27.string().nullable(),outputBytes:z27.number().int().nonnegative(),outputTruncated:z27.boolean(),outputExpiresAt:z27.coerce.date().nullable(),metadataExpiresAt:z27.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z27.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z27.coerce.date().nullable(),items:z27.array(z27.object({key:z27.string().min(1),updatedAt:z27.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z27.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z27.object({trigger:z27.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z27.object({limit:z27.coerce.number().int().min(1).max(100).default(25),cursor:z27.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z27.object({items:z27.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z27.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z27.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z27.object({items:z27.array(ProjectScheduleRunDTOSchema),nextCursor:z27.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z28}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z28.object({id:z28.uuid(),occurredAt:z28.coerce.date(),projectId:z28.uuid().nullable(),env:z28.string().nullable(),actor:z28.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z28.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z28.unknown().optional(),ipAddress:z28.string().nullable().optional(),userAgent:z28.string().nullable().optional(),error:z28.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z28.object({rows:z28.array(AuditLogRowDTOSchema),nextCursor:z28.string().nullable()})),AuditLogQuerySchema=z28.object({env:z28.string().optional(),action:AuditActionSchema.optional(),actor:z28.string().optional(),from:z28.coerce.date().optional(),to:z28.coerce.date().optional(),limit:z28.coerce.number().int().min(1).max(200).optional(),cursor:z28.string().optional()})}});import{z as z29}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z29.object({surface:SurfaceNameSchema,key:z29.string(),label:z29.string()}),InlineSchema=z29.object({text:z29.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z29.discriminatedUnion("type",[z29.object({type:z29.literal("paragraph"),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("preview"),ref:DiffRefSchema,caption:z29.string().optional()}),z29.object({type:z29.literal("code"),code:z29.string(),lang:z29.string().optional(),caption:z29.string().optional()}),z29.object({type:z29.literal("risk"),level:z29.enum(["warning","error"]),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("list"),items:z29.array(z29.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z29.object({headline:z29.string(),blocks:z29.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z29.object({summary:EnvDiffSummarySchema,fingerprint:z29.string(),generatedAt:z29.coerce.date(),cached:z29.boolean().optional(),credits:z29.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z30}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z30.object({date:z30.string(),visitors:z30.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z30.object({key:z30.string(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z30.object({path:z30.string(),pageName:z30.string().nullable().optional(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z30.object({preset:z30.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z30.string(),requestedTo:z30.string(),effectiveFrom:z30.string(),effectiveTo:z30.string(),isRetentionLimited:z30.boolean(),groupBy:z30.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z30.object({date:z30.string(),content:z30.string(),updatedAt:z30.string(),updatedByUserId:z30.string()}),ProjectPageviewAnalyticsDTOSchema=z30.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative(),bounceRate:z30.number().min(0).max(100),viewsPerVisit:z30.number().nonnegative(),averageVisitDurationSeconds:z30.number().nonnegative(),visitorsSeries:z30.array(ProjectDailyVisitorsDTOSchema),topPages:z30.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z30.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z31}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z31.object({id:z31.string(),email:z31.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z31.coerce.date(),createdAt:z31.coerce.date(),inviterUserId:z31.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z31.object({id:z31.string(),token:z31.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z31.object({success:z31.boolean(),projectId:z31.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z32}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z32.object({id:z32.string(),name:z32.string(),image:z32.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z32.object({count:z32.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z32.object({counts:z32.object({signed_up:z32.int(),activated:z32.int()}),credits:z32.object({total:z32.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z32.email(),emailVerified:z32.boolean(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z33}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z33.object({id:z33.string(),principalType:ProjectPrincipalTypeSchema,principalId:z33.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z33.coerce.date(),expiresAt:z33.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z33.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z33.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z33.record(z33.string(),z33.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z33.object({access:z33.array(ProjectAccessItemDTOSchema),invites:z33.array(ProjectInviteDTOSchema),organization:z33.object({name:z33.string().nullable(),logo:z33.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z33.object({success:z33.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z33.object({success:z33.boolean(),projectId:z33.uuid()}))}});import{z as z34}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z34.object({publicationStatus:PublicationStatusSchema,appUrl:z34.string().nullable(),lastPublishedAt:z34.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z35}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z35.object({url:z35.url(),expiresAt:z35.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z36}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z36.string(),slug:z36.string().nullable(),logo:z36.string().nullable(),metadata:z36.record(z36.string(),z36.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z36.object({id:z36.string(),name:z36.string(),email:z36.email(),image:z36.string().nullable()}),OrganizationMemberDTOSchema=z36.object({id:z36.string(),userId:z36.string(),organizationId:z36.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z36.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z37}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z37.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z37.object({reason:CancellationReasonCodeSchema,details:z37.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z37.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z37.object({included:z37.number().optional(),unitPrice:z37.number().optional(),dailyCap:z37.number().nullable().optional()}),EntitlementsDTOSchema=z37.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z37.object({retentionDays:z37.number().int().positive(),canUseExtendedDateRanges:z37.boolean()}).optional(),history:z37.object({retentionDays:z37.number().int().positive()}).optional(),members:z37.object({canInvite:z37.boolean(),maxMembers:z37.number().int().positive().nullable()}).optional(),domains:z37.object({canUseCustomDomains:z37.boolean(),maxDomains:z37.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z37.object({id:z37.string(),external_id:z37.string(),customerId:z37.string(),planId:z37.string(),planCode:TemplateCodeSchema,currentPeriod:z37.object({start:z37.string(),end:z37.string().nullable()}),cancelAt:z37.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z37.string(),nextPaymentAt:z37.string().nullable(),baseAmount:z37.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z37.object({totalCap:z37.number(),dailyCap:z37.number(),usedTotal:z37.number()}),CreditBalanceDTOSchema=z37.object({total:z37.number(),base:z37.number(),dailyBase:z37.number(),purchases:z37.number(),awards:z37.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z37.object({total:z37.number(),nearLimit:z37.boolean(),canChat:z37.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z37.object({dailyFreeAvailable:z37.number(),monthlyAvailable:z37.number(),purchasedAvailable:z37.number(),awardedAvailable:z37.number()}),ProjectDailyCreditAllowanceDTOSchema=z37.object({periodCap:z37.number(),dailyGrant:z37.number(),usedThisPeriod:z37.number(),remainingThisPeriod:z37.number()}),ProjectCreditBalanceDTOSchema=z37.object({projectId:z37.uuid(),organizationId:z37.string(),balance:z37.object({totalAvailable:z37.number(),nearLimit:z37.boolean(),canUseAi:z37.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z37.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z37.discriminatedUnion("enabled",[z37.object({enabled:z37.literal(!0),thresholdUsd:z37.number().nonnegative(),refillAmountUsd:z37.number().nonnegative()}),z37.object({enabled:z37.literal(!1),thresholdUsd:z37.number().nonnegative().nullable(),refillAmountUsd:z37.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z37.discriminatedUnion("enabled",[z37.object({enabled:z37.literal(!0),thresholdUsd:z37.number().min(.01).multipleOf(.01),refillAmountUsd:z37.number().min(.01).multipleOf(.01)}).strict(),z37.object({enabled:z37.literal(!1),thresholdUsd:z37.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z37.object({invoiceId:z37.string(),newBalance:z37.int(),creditCount:z37.int(),amountUsd:z37.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z37.object({url:z37.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z38}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z38.object({brand:z38.string(),last4:z38.string(),exp:z38.string(),isDefault:z38.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z39}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z39.string().superRefine((path50,ctx)=>{let segments=path50.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z39.object({type:z39.literal("renameField"),contentType:z39.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z39.object({enabled:z39.boolean()}).strict(),ContentTypeDTOSchema=z39.object({id:z39.string(),name:z39.string(),label:z39.string(),isSingleton:z39.boolean(),i18n:ContentTypeI18nSchema,fields:z39.record(z39.string(),FieldDefinitionSchema),createdAt:z39.string(),updatedAt:z39.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z39.object({contentTypes:z39.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z39.object({id:z39.string(),entryId:z39.string(),documentId:z39.string(),slug:z39.string(),locale:z39.string().optional(),createdAt:z39.string(),updatedAt:z39.string(),__fimo:z39.object({contentType:z39.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({limit:z39.number(),offset:z39.number(),total:z39.number(),hasMore:z39.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z39.object({contentType:z39.string(),count:z39.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z39.object({counts:z39.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z39.object({count:z39.number().int().nonnegative(),sourceLocale:z39.string(),targetLocale:z39.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z39.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z39.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z39.union([z39.string(),z39.number(),z39.boolean(),z39.null()]),entryWhereOperatorSchema=z39.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z39.array(entryWhereScalarSchema).optional(),$nin:z39.array(entryWhereScalarSchema).optional(),$contains:z39.string().optional(),$startsWith:z39.string().optional(),$null:z39.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z39.object({data:z39.record(z39.string(),z39.unknown()),locale:z39.string().min(1).optional(),documentId:z39.uuid().optional()}),entryIdsSchema=z39.array(z39.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z39.object({sql:z39.string().min(1)}),BulkCreateEntriesRequestSchema=z39.object({entries:z39.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z39.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z39.object({updates:z39.array(z39.object({id:z39.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,locale:z39.string().min(1).optional()}),z39.object({where:EntryWhereSchema,locale:z39.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z39.object({data:z39.array(z39.record(z39.string(),z39.unknown())),meta:z39.object({rowCount:z39.number().int().nonnegative(),truncated:z39.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({created:z39.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({updated:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({deleted:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z40}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z40.object({index:z40.number().int().nonnegative(),contentType:z40.string(),field:z40.string(),value:z40.string(),against:z40.enum(["stored","batch"]),ownerDocumentId:z40.uuid().optional(),ownerIndex:z40.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z40.object({code:z40.literal("unique_conflict"),message:z40.string(),conflicts:z40.array(UniqueConflictSchema),truncated:z40.boolean().optional()})}});import{z as z41}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z41.object({kind:z41.literal("unique_conflict"),contentType:z41.string(),field:z41.string(),value:z41.string(),documentCount:z41.number().int().positive(),documentIds:z41.array(z41.uuid()),documentIdsTruncated:z41.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z41.object({code:z41.literal("schema_transition_rejected"),message:z41.string(),issues:z41.array(SchemaTransitionIssueSchema),truncated:z41.boolean().optional()})}});import{z as z42}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z42.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z42.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z42.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z42.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z42.object({field:CmsFieldNameSchema,direction:z42.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z42.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z42.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z42.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z42.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z42.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z43}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z43.object({id:z43.string(),name:z43.string()}),AssetDTOSchema=z43.object({id:z43.string(),name:z43.string(),type:AssetTypeSchema,originalFileName:z43.string().nullable(),parentId:z43.string().nullable(),mimeType:z43.string().nullable(),fileSize:z43.number().nullable(),url:z43.string().nullable(),storageKey:z43.string().nullable(),createdAt:z43.string(),updatedAt:z43.string(),altText:z43.string().nullable().optional(),caption:z43.string().nullable().optional(),aiCaption:z43.string().nullable().optional(),aiAltText:z43.string().nullable().optional(),aiTags:z43.array(z43.string()).nullable().optional(),aiPrimaryColor:z43.string().nullable().optional(),aiProcessingStatus:z43.string().nullable().optional(),width:z43.number().nullable().optional(),height:z43.number().nullable().optional(),path:z43.array(AssetPathItemSchema).optional(),hasChildren:z43.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z43.lazy(()=>z43.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z43.array(AssetDTOSchema))}});import{z as z44}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z44.object({key:z44.string(),value:z44.string().optional(),defaultValue:z44.string(),locale:z44.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z45}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z45.object({id:z45.string(),name:z45.string(),type:z45.enum(["file","folder"]),path:z45.string(),children:z45.lazy(()=>z45.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z45.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z45.object({path:z45.string(),exists:z45.boolean(),type:z45.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z46}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z46.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z46.object({items:z46.array(ProjectMessagePublicDTOSchema),nextCursor:z46.string().nullable()}),ChatLiveTurnDTOSchema=z46.object({invocationId:z46.string(),step:z46.enum(["preparing","working","compacting","merging"]),startedAt:z46.string()}),ChatLiveTurnStateDTOSchema=z46.object({threadId:z46.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z46.object({id:z46.string(),role:z46.enum(["user","assistant"]),parts:z46.array(z46.unknown()),metadata:z46.record(z46.string(),z46.unknown()).nullable(),versionId:z46.string().nullable().optional(),createdAt:z46.date().transform(value=>value.toISOString()),providerMessageId:z46.string().nullable().optional(),invocationId:z46.string().nullable().optional(),invocationStatus:z46.string().nullable().optional(),invocationTerminalReason:z46.string().nullable().optional()}),ChatAttentionDTOSchema=z46.object({type:z46.literal("merge_conflict"),merge:z46.object({mergeId:z46.string().uuid(),projectId:z46.string(),fromEnv:z46.string(),toEnv:z46.string()}),publishAfterMerge:z46.boolean()}),ChatThreadMessagesPageDTOSchema=z46.object({threadId:z46.string().nullable(),title:z46.string().nullable(),messages:z46.array(ChatThreadMessageDTOSchema),nextCursor:z46.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z46.object({kind:z46.literal("replay"),threadId:z46.string(),userMessageId:z46.string()}),ChatQueuedOutcomeDTOSchema=z46.object({kind:z46.literal("queued"),threadId:z46.string(),userMessageId:z46.string(),blockingRootId:z46.string()}),ChatBusyOutcomeDTOSchema=z46.object({kind:z46.literal("busy"),threadId:z46.string(),userMessageId:z46.string(),blockingRootId:z46.string().optional()}),ChatRefusedOutcomeDTOSchema=z46.object({kind:z46.literal("refused"),threadId:z46.string(),userMessageId:z46.string(),refusedInvocationId:z46.string(),terminalReason:z46.string()}),ChatNonStreamingOutcomeDTOSchema=z46.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z46.object({success:z46.boolean(),deletedCount:z46.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z46.object({code:z46.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z46.string()})}});import{z as z47}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z47.object({url:z47.string().url(),key:z47.string(),size:z47.number(),contentType:z47.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z48}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z48.object({canAccess:z48.boolean(),permissions:z48.record(z48.string(),z48.boolean()),role:z48.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z49}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z49.string().trim().default(""),sort:z49.enum(["recent","name","relevance"]).default("recent"),category:z49.string().optional()})}});import{z as z50}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z50.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z50.enum(["fimo","external"]),PaymentStatusSchema=z50.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z50.object({id:z50.string().uuid(),domain:z50.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z50.boolean(),price:z50.number().int().nullable(),renewalPrice:z50.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z50.string().nullable(),failureReason:z50.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z50.object({domain:z50.string(),available:z50.boolean(),premium:z50.boolean(),price:z50.number().nullable(),renewalPrice:z50.number().nullable(),purchaseType:z50.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z50.object({domain:z50.string(),price:z50.number().nullable(),renewalPrice:z50.number().nullable(),premium:z50.boolean(),allowedYears:z50.array(z50.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z50.object({firstName:z50.string().max(100),lastName:z50.string().max(100),companyName:z50.string().max(100).optional(),address1:z50.string().max(255),address2:z50.string().max(255).optional(),city:z50.string().max(100),state:z50.string().max(100),zip:z50.string().max(20),country:z50.string().max(2),phone:z50.string().max(30),email:z50.union([z50.string().email().max(255),z50.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z50.object({firstName:z50.string().min(1).max(100),lastName:z50.string().min(1).max(100),companyName:z50.string().max(100).optional(),address1:z50.string().min(1).max(255),address2:z50.string().max(255).optional(),city:z50.string().min(1).max(100),state:z50.string().min(1).max(100),zip:z50.string().min(1).max(20),country:z50.string().min(1).max(2),phone:z50.string().min(1).max(30),email:z50.string().email().max(255)}),SearchDomainsRequestSchema=z50.object({keyword:z50.string().min(1).max(100),tldFilter:z50.array(z50.string()).optional()}),CheckAvailabilityRequestSchema=z50.object({domains:z50.array(z50.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z50.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z50.object({domain:DomainNameSchema,years:z50.number().int().min(1).max(10).optional().default(3),autoRenew:z50.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z50.object({autoRenew:z50.boolean().optional()}),RenewDomainRequestSchema=z50.object({years:z50.number().int().min(1).max(10).optional().default(1),autoRenew:z50.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z50.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z50.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z50.object({verified:z50.boolean(),email:z50.string().nullable(),verifyBy:z50.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z51}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z51.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z51.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z51.object({txtName:z51.string().nullable().optional(),txtValue:z51.string().nullable().optional(),httpUrl:z51.string().nullable().optional(),httpBody:z51.string().nullable().optional(),cname:z51.string().nullable().optional(),cnameTarget:z51.string().nullable().optional()}),SSLValidationErrorSchema=z51.object({message:z51.string()}),OwnershipVerificationSchema=z51.object({type:z51.string(),name:z51.string(),value:z51.string()}),ProjectDomainSSLDTOSchema=z51.object({status:z51.string(),method:z51.string().nullable(),type:z51.string().nullable(),validationRecords:z51.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z51.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z51.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z51.enum(["subdomain","apex"]),RedirectConfigSchema=z51.object({type:z51.literal("apex_to_www"),linkedDomainId:z51.string()}).nullable().optional(),ProjectDomainDTOSchema=z51.object({id:z51.string(),hostname:z51.string(),status:z51.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z51.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z51.string(),scdCnameTarget:z51.string().optional(),apexTargets:z51.array(z51.string()),dnsAutoConfigured:z51.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z51.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z51.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z51.object({hostname:z51.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z51.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z51.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z51.object({available:z51.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z51.object({success:z51.boolean(),hostname:z51.string()}))}});import{z as z52}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z52.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z52.object({available:z52.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z52.object({slug:z52.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z52.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z52.object({subdomain:z52.string(),subdomainUpdatedAt:z52.coerce.date()})),SubdomainSuggestionsQuerySchema=z52.object({base:z52.string().max(100).optional(),max:z52.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z52.object({suggestions:z52.array(z52.string())}))}});import{z as z53}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z53.object({translated:z53.number().int().nonnegative(),total:z53.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z53.object({locale:z53.string(),isDefault:z53.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z53.object({defaultLocale:z53.string(),locales:z53.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z53.object({locale:z53.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z53.object({locale:z53.string().min(1).max(40)}),ProjectLocaleMutationSchema=z53.object({locale:z53.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z53.object({locale:z53.string(),entriesDeleted:z53.number().int().nonnegative(),labelsDeleted:z53.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z54}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z54.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z54.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z54.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z54.number(),credits:z54.number().optional(),billingMode:z54.enum(["fimo-credits","provider-account"]).optional(),confidence:z54.enum(["exact","estimated","metered"]),basis:z54.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z55}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z55.object({options:z55.record(z55.string(),z55.unknown()),name:z55.string().optional(),parentId:z55.string().nullable().optional(),altText:z55.string().optional(),caption:z55.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z55.string().min(1).optional(),model:z55.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z55.object({jobId:z55.string(),status:z55.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z55.string().nullable().optional(),credits:z55.number().optional(),costUsd:z55.number().optional(),billingMode:z55.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z55.object({error:z55.string(),code:z55.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z55.array(GenerationTaskIdSchema).optional(),availableModels:z55.array(z55.string()).optional(),issues:z55.array(z55.unknown()).optional()})}});import{z as z56}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z56.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z56.object({name:z56.string(),key:z56.string(),description:z56.string(),type:FlagTypeSchema,required:z56.boolean(),defaultValue:z56.unknown().optional(),enumValues:z56.array(z56.string()).optional(),isArray:z56.boolean()}),AssetModelPriceSchema=z56.object({unitPrice:z56.number(),unit:z56.string(),confidence:z56.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z56.object({id:z56.string(),shortName:z56.string(),provider:z56.string(),source:z56.string(),modality:z56.enum(["image","video","audio"]),tags:z56.array(z56.string()),displayName:z56.string(),description:z56.string(),flags:z56.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z56.object({model:z56.string(),costUsd:z56.number(),credits:z56.number(),billingMode:z56.enum(["fimo-credits","provider-account"]),confidence:z56.enum(["exact","estimated","metered"]),basis:z56.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z57}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z57.object({tourId:z57.string(),version:z57.string(),status:z57.string(),completedAt:z57.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z57.array(UserTourDTOSchema))}});import{z as z58}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z58.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z58.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z58.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z58.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z58.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z58.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z58.enum(["user","agent","system"]),SupportReportTagSchema=z58.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z58.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z58.object({organization:z58.object({id:z58.string().trim().min(1).max(255),name:z58.string().trim().max(240).optional()}),project:z58.object({id:z58.uuid(),name:z58.string().trim().max(240).optional(),createdAt:z58.coerce.date().optional()}).optional(),environment:z58.string().trim().max(255).optional(),clientVersion:z58.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z58.object({message:z58.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z58.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z58.string().trim().max(200).optional(),limit:z58.coerce.number().int().min(1).max(100).default(50),offset:z58.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z58.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z58.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z58.uuid().nullable().optional(),note:z58.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z58.object({message:z58.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z58.object({kind:SupportReportLinkKindSchema,label:z58.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z58.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z58.object({kind:SupportReportActorKindSchema,id:z58.string().nullable(),name:z58.string().nullable()}),SupportReportLinkDTOSchema=z58.object({id:z58.uuid(),kind:SupportReportLinkKindSchema,label:z58.string(),url:SupportReportHttpUrlSchema,externalId:z58.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z58.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z58.object({id:z58.uuid(),kind:SupportReportEventKindSchema,body:z58.string().nullable(),metadata:z58.record(z58.string(),z58.unknown()),actor:SupportReportActorDTOSchema,createdAt:z58.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z58.object({id:z58.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z58.array(z58.string()),source:SupportReportSourceSchema,message:z58.string(),reporter:z58.object({id:z58.string().nullable(),name:z58.string().nullable(),email:z58.string().nullable()}),organization:z58.object({id:z58.string().nullable(),name:z58.string()}),project:z58.object({id:z58.uuid().nullable(),name:z58.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z58.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z58.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}).nullable(),duplicateOfReportId:z58.uuid().nullable(),resolvedAt:z58.coerce.date().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z58.string().nullable(),clientVersion:z58.string().nullable(),links:z58.array(SupportReportLinkDTOSchema),events:z58.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z58.object({reports:z58.array(SupportReportSummaryDTOSchema),total:z58.number().int().nonnegative(),statusCounts:z58.object({new:z58.number().int().nonnegative(),in_progress:z58.number().int().nonnegative(),waiting:z58.number().int().nonnegative(),resolved:z58.number().int().nonnegative(),duplicate:z58.number().int().nonnegative(),irrelevant:z58.number().int().nonnegative(),ignored:z58.number().int().nonnegative()}),limit:z58.number().int().positive(),offset:z58.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z58.object({id:z58.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z58.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z59}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z59.iso.datetime({offset:!0}).pipe(z59.coerce.date()),OpsRecentChatInputSchema=z59.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z59.string().trim().min(1).max(255).optional(),limit:z59.coerce.number().int().min(1).max(200).default(100),cursor:z59.string().trim().min(1).max(2e3).optional(),slim:z59.boolean().default(!0),reason:z59.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z59.object({id:z59.string(),threadId:z59.string(),providerMessageId:z59.string().nullable(),invocationId:z59.string().nullable(),env:z59.string().nullable(),role:z59.string(),parts:z59.array(z59.record(z59.string(),z59.unknown())),metadata:z59.object({status:z59.string().optional(),traceUrl:z59.string().optional(),externalFileChanges:z59.array(z59.unknown()).optional()}),stats:z59.object({toolCount:z59.number().int().nonnegative(),failedToolCount:z59.number().int().nonnegative()}),createdAt:z59.iso.datetime({offset:!0}),project:z59.object({id:z59.string(),name:z59.string(),displayName:z59.string().nullable(),organizationId:z59.string().nullable()})}),OpsRecentChatResponseSchema=z59.object({target:z59.object({backendProfile:OpsBackendProfileSchema,projectEnv:z59.string().nullable()}),window:z59.object({from:z59.iso.datetime({offset:!0}),to:z59.iso.datetime({offset:!0})}),messages:z59.object({items:z59.array(OpsRecentChatMessageSchema),nextCursor:z59.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z60}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z60.object({backendProfile:OpsBackendProfileSchema,provider:z60.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z60.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z60.object({backendProfile:OpsBackendProfileSchema,provider:z60.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z60.literal(!1),reason:z60.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z61}from"zod";function createAgentRunWebhookEventDataSchema(status){return z61.object({run:z61.object({id:z61.string(),agentName:z61.string(),trigger:z61.string(),status:z61.literal(status),startedAt:z61.string().nullable(),finishedAt:z61.string().nullable(),reason:z61.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z61.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z61.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z61.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z61.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z61.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z61.union([z61.literal(0),z61.literal(5),z61.literal(30),z61.literal(60)]),EntryChangedWebhookEventDataSchema=z61.object({reason:WebhookEntryChangeReasonSchema,operationId:z61.string().optional(),batch:z61.object({index:z61.number().int().positive(),total:z61.number().int().positive()}).optional(),changes:z61.array(z61.object({action:WebhookEntryChangeActionSchema,contentType:z61.string(),id:z61.string(),documentId:z61.string(),locale:z61.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z61.object({form:z61.object({id:z61.string(),label:z61.string()}),submission:z61.object({id:z61.string(),data:z61.record(z61.string(),z61.unknown()),submittedAt:z61.string()})}),PublishStartedWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("publishing"),startedAt:z61.string()})}),PublishSucceededWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("published"),url:z61.string(),publishedAt:z61.string(),firstPublish:z61.boolean()})}),PublishFailedWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("failed"),reason:z61.string()})}),PublishUnpublishedWebhookEventDataSchema=z61.object({publication:z61.object({previousUrl:z61.string(),unpublishedAt:z61.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z61.object({review:z61.object({id:z61.string(),runId:z61.string(),agentName:z61.string(),classification:z61.string(),summary:z61.string(),reasons:z61.array(z61.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z61.object({review:z61.object({id:z61.string(),runId:z61.string(),agentName:z61.string(),resolution:z61.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z61.object({report:z61.object({weekStart:z61.string(),weekEnd:z61.string(),pageviews:z61.number(),visitors:z61.number(),previousPageviews:z61.number(),previousVisitors:z61.number()})}),MediaAssetWebhookEventDataSchema=z61.object({id:z61.string().nullable(),name:z61.string().nullable(),type:z61.string(),mimeType:z61.string().nullable(),fileSize:z61.number().nullable()}),MediaUploadedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.enum(["updated","moved","analysis"]),analysis:z61.object({category:z61.string(),status:z61.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("generated"),generation:z61.object({model:z61.string(),mode:z61.string()})}),MediaProcessingFailedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.enum(["analysis","generation"]),failure:z61.object({code:z61.string()})}),DomainCreatedWebhookEventDataSchema=z61.object({domain:z61.object({id:z61.string(),hostname:z61.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z61.object({domain:z61.object({id:z61.string(),hostname:z61.string()})}),LabelChangedWebhookEventDataSchema=z61.object({changes:z61.array(z61.object({action:z61.enum(["created","updated","deleted"]),key:z61.string(),locale:z61.string(),value:z61.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),isDefault:z61.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),previousCode:z61.string()})}),LocaleDeletedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),entriesDeleted:z61.number().int().nonnegative(),labelsDeleted:z61.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z61.object({merge:z61.object({id:z61.string(),from:EnvSchema,to:EnvSchema,applied:z61.array(z61.object({surface:SurfaceNameSchema,count:z61.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema}),version:z61.object({versionId:z61.uuid(),name:z61.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z61.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z61.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z61.discriminatedUnion("source",[z61.object({source:z61.literal("literal"),value:z61.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z61.object({source:z61.literal("secret"),key:z61.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z61.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z61.object({name:z61.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z61.object({name:z61.string(),source:z61.enum(["literal","secret"]),secretKey:z61.string().nullable(),secretPrefix:z61.string().nullable(),configured:z61.literal(!0)}),WebhookFilterSchema=z61.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z61.string().min(1).max(255).optional(),agentName:z61.string().min(1).max(120).optional(),mediaType:z61.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z61.string().min(1).max(255).optional(),locale:z61.string().min(1).max(120).optional()}),JsonValueSchema=z61.lazy(()=>z61.union([z61.string(),z61.number(),z61.boolean(),z61.null(),z61.array(JsonValueSchema),z61.record(z61.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z61.object({name:z61.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z61.url(),enabled:z61.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z61.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z61.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z61.object({name:z61.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z61.url().optional(),enabled:z61.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z61.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z61.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z61.object({eventType:WebhookEventTypeSchema.optional(),data:z61.record(z61.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z61.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z61.uuid(),name:z61.string(),eventType:WebhookEventTypeSchema,enabled:z61.boolean(),destination:z61.object({host:z61.string(),maskedUrl:z61.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z61.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z61.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z61.coerce.date().nullable(),deliveryStats24h:z61.object({succeeded:z61.number().int().nonnegative(),failed:z61.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z61.uuid(),projectId:z61.uuid(),env:EnvSchema,environment:EnvironmentKeySchema,branch:EnvSchema,eventId:z61.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z61.number().int().positive(),test:z61.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z61.number().int().nonnegative(),responseStatus:z61.number().int().nullable(),lastErrorCode:z61.string().nullable(),lastErrorMessage:z61.string().nullable(),payloadAvailable:z61.boolean(),destination:z61.object({host:z61.string(),maskedUrl:z61.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z61.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z61.string().nullable(),qstashMessageId:z61.string().nullable(),deliveredAt:z61.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z61.object({items:z61.array(WebhookDeliveryDTOSchema),pagination:z61.object({page:z61.number().int().positive(),limit:z61.number().int().positive(),total:z61.number().int().nonnegative(),totalPages:z61.number().int().positive(),hasMore:z61.boolean()}),stats:z61.object({total:z61.number().int().nonnegative(),succeeded:z61.number().int().nonnegative(),failed:z61.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z61.object({id:z61.uuid(),deliveryId:z61.uuid(),attempt:z61.number().int().positive(),status:z61.enum(["delivering","succeeded","failed"]),responseStatus:z61.number().int().nullable(),durationMs:z61.number().int().nonnegative(),responseExcerpt:z61.string().nullable(),errorCode:z61.string().nullable(),errorMessage:z61.string().nullable(),createdAt:z61.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z61.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z61.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z62}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z62.object({key:z62.literal("fimo-2"),enabled:z62.boolean(),dismissed:z62.boolean().default(!1),interacted:z62.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z63}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z63.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z63.object({total:z63.number(),base:z63.number(),purchases:z63.number(),awards:z63.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z63.object({id:z63.string(),name:z63.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z63.object({type:z63.string(),brand:z63.string().nullable(),last4:z63.string().nullable(),expirationDate:z63.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z63.object({currency:z63.string(),nextPaymentAmount:z63.number().nullable(),nextPaymentAt:z63.string().nullable(),billingInterval:z63.string().nullable(),totalAmount:z63.number().nullable(),discountAmount:z63.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z63.object({id:z63.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z63.string().nullable(),currentPeriodEndsAt:z63.string().nullable(),renewsAt:z63.string().nullable(),cancelAt:z63.string().nullable(),renewAutomatically:z63.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z63.object({type:z63.enum(["low_balance","critical_balance","approaching_limit"]),message:z63.string(),estimatedPromptsRemaining:z63.number().nullable(),avgCostPerPrompt:z63.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z63.object({monthlyCredits:z63.number().nullable(),usedThisPeriod:z63.number(),remainingThisPeriod:z63.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z63.object({organizationId:z63.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z63.string().nullable(),tenureDays:z63.number().int().nonnegative(),capturedAt:z63.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z63.object({hasSubscription:z63.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z63.number().nullable(),alerts:z63.array(CreditAlertDTOSchema),portalUrl:z63.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z63.object({creditCount:z63.number().int().positive(),expiresAt:z63.string().datetime().nullable().optional(),message:z63.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z63.literal("free"),amountCents:z63.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z63.literal("purchase"),amountCents:z63.number().int().positive()}),CreditTopupRequestDTOSchema=z63.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z63.object({success:z63.boolean(),transactionId:z63.string().nullable(),newBalance:z63.number(),creditCount:z63.number(),type:z63.enum(["free","purchase"]),invoiceId:z63.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z64}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z64.object({totalCredits:z64.number(),totalCostUsd:z64.number(),totalMessages:z64.number(),avgCostPerMessage:z64.number(),periodStart:z64.string().nullable(),periodEnd:z64.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z64.object({projectId:z64.string(),projectName:z64.string(),projectDisplayName:z64.string().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z64.object({userId:z64.string(),userName:z64.string().nullable(),userEmail:z64.string().email().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z64.object({date:z64.string(),credits:z64.number(),costUsd:z64.number(),messages:z64.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z64.object({userId:z64.string(),userName:z64.string().nullable(),userEmail:z64.string().email().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z64.object({projectId:z64.string(),projectName:z64.string(),projectDisplayName:z64.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z64.array(UsageByUserForProjectDTOSchema),timeline:z64.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z64.object({summary:UsageSummaryDTOSchema,byProject:z64.array(UsageByProjectDTOSchema),byUser:z64.array(UsageByUserDTOSchema),timeline:z64.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z65}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z65.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z65.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z65.object({startDate:z65.string().optional(),endDate:z65.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z65.coerce.number().int().positive().default(1),limit:z65.coerce.number().int().positive().max(100).default(20),sortBy:z65.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z65.string().optional(),activeOnly:z65.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z65.object({totalCredits:z65.number(),totalCostUsd:z65.number(),totalMessages:z65.number(),avgCostPerMessage:z65.number(),avgCreditsPerMessage:z65.number(),periodStart:z65.string(),periodEnd:z65.string(),creditsChange:z65.number().nullable(),costChange:z65.number().nullable(),messagesChange:z65.number().nullable(),unattributedCredits:z65.number(),unattributedCostUsd:z65.number(),unattributedMessages:z65.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z65.object({date:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z65.object({organizationId:z65.string(),organizationName:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),userCount:z65.number(),projectCount:z65.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z65.object({userId:z65.string(),userName:z65.string().nullable(),userEmail:z65.string().nullable(),userImage:z65.string().nullable(),organizationId:z65.string().nullable(),organizationName:z65.string().nullable(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),projectCount:z65.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z65.object({projectId:z65.string(),projectName:z65.string(),projectDisplayName:z65.string().nullable(),organizationId:z65.string(),organizationName:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),userCount:z65.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z65.object({id:z65.string(),name:z65.string(),value:z65.number(),percentage:z65.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z65.object({day:z65.number(),hour:z65.number(),value:z65.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z65.object({summary:UsageOverviewSummaryDTOSchema,timeline:z65.array(UsageTimelinePointDTOSchema),topOrganizations:z65.array(OrganizationUsageRowDTOSchema),topUsers:z65.array(UserUsageRowDTOSchema),topProjects:z65.array(ProjectUsageRowDTOSchema),creditDistribution:z65.array(UsageDistributionItemDTOSchema),userDistribution:z65.array(UsageDistributionItemDTOSchema),heatmap:z65.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z65.object({page:z65.number(),limit:z65.number(),totalItems:z65.number(),totalPages:z65.number(),hasMore:z65.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z65.object({organizations:z65.array(OrganizationUsageRowDTOSchema),top:z65.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z65.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z65.object({users:z65.array(ExtendedUserUsageRowDTOSchema),top:z65.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z65.string(),ownerName:z65.string().nullable(),ownerEmail:z65.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z65.object({projects:z65.array(ExtendedProjectUsageRowDTOSchema),top:z65.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z65.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z65.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z65.object({credits:z65.number(),costUsd:z65.number(),messages:z65.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z65.object({id:z65.string(),name:z65.string(),createdAt:z65.string(),memberCount:z65.number(),projectCount:z65.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z65.object({id:z65.string(),name:z65.string().nullable(),email:z65.string(),image:z65.string().nullable(),createdAt:z65.string(),organizationCount:z65.number(),projectCount:z65.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z65.object({id:z65.string(),name:z65.string(),displayName:z65.string().nullable(),createdAt:z65.string(),organizationId:z65.string(),organizationName:z65.string(),ownerId:z65.string(),ownerName:z65.string().nullable(),ownerEmail:z65.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z66}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z66.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z66.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z66.object({command:z66.string().min(1).max(1e4),cwd:z66.string().optional(),projectEnv:EnvSchema.optional(),env:z66.record(z66.string(),z66.string()).optional(),name:z66.string().optional(),waitForCompletion:z66.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z66.object({identifier:z66.string(),status:SandboxProcessStatusSchema,command:z66.string().optional(),startedAt:z66.string().optional(),exitCode:z66.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z66.object({processes:z66.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z66.object({processId:z66.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z66.object({success:z66.boolean(),message:z66.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z67}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_fimo_config();init_page_sources();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&¶ms.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path50,message}=issue;return`${Array.isArray(path50)&&path50.length>0?`${path50.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,env){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(env)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,env,base)===normalized?base:void 0}catch{return}}var SandboxReadinessError,ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");SandboxReadinessError=class extends Error{static{__name(this,"SandboxReadinessError")}constructor(message){super(message),this.name="SandboxReadinessError"}},ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path50,status,detail,code2,body){super(`API ${method} ${path50} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path50,this.status=status,this.detail=detail,this.code=code2,this.body=body}};__name(publicationIdFromError,"publicationIdFromError");UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}cfg;static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path50,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path50}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path50,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path50,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env),fimoFetch(`${this.cfg.apiUrl}${path50}`,{...init,headers})}async rawRequest(path50,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path50}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path50} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId){return(await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST"}))?.data?.publicationId??null}async listPublications(projectId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.before&¶ms.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications${search?`?${search}`:""}`)).data}async getPublication(projectId,publicationId){return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}`)).data}async getPublicationLogs(projectId,publicationId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit));let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}/logs${search?`?${search}`:""}`)).data}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&¶ms.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts){let query=new URLSearchParams({environment:opts.environment});return opts.kind&&query.set("kind",opts.kind),(await this.request(`/api/management/projects/${projectId}/secrets?${query.toString()}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value,environment:input.environment})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value,environment:input.environment})})).data}async deleteProjectSecretEntry(projectId,key,kind,environment){let qs=new URLSearchParams({kind,environment});await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}?${qs.toString()}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.cursor&¶ms.set("cursor",query.cursor),query.status&¶ms.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&¶ms.set("includeDeleted","true"),opts.includeAgentEnvs&¶ms.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listEnvs(projectId,{includeAgentEnvs:!0}),current=branches.find(candidate=>candidate.env===branch),visited=new Set;for(;current&&!visited.has(current.env);){if(visited.add(current.env),current.resolvedEnvironment)return current.resolvedEnvironment.id;current=current.parentEnv?branches.find(candidate=>candidate.env===current?.parentEnv):void 0}return PREVIEW_ENVIRONMENT_KEY}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path50,opts={}){let qs=lazyFetchQs(opts.against,{path:path50});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path50=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path50}?${qs}`:path50)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path50=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path50}?${qs}`:path50)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path50=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path50}?${qs}`:path50)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path50=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path50}?${qs}`:path50)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path50=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path50}?${qs}`:path50)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&¶ms.set("agent_name",opts.agentName),opts.env&¶ms.set("env",opts.env),opts.status&¶ms.set("status",opts.status),opts.limit!==void 0&¶ms.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){let remote=(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,env);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectEnvManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox`)).data}async getSandboxLogs(projectId,env,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.before&¶ms.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,env,options={}){let params=new URLSearchParams;options.noRestart&¶ms.set("noRestart","true"),options.wait!==void 0&¶ms.set("wait",String(options.wait));let search=params.toString(),query=search?`?${search}`:"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage5=null,errorCode,readiness=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
43
43
|
|
|
44
44
|
`);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
|
|
45
45
|
|
|
46
46
|
`);let eventName="message",dataLines=[];for(let line of rawEvent.split(`
|
|
47
47
|
`))line.startsWith("event:")?eventName=line.slice(6).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).trim());if(dataLines.length===0)continue;let payload=dataLines.join(`
|
|
48
|
-
`);if(eventName==="progress")try{let parsed=JSON.parse(payload);onProgress?.(parsed)}catch{}else if(eventName==="complete"){completed=!0;try{readiness=JSON.parse(payload).readiness??null}catch{}}else if(eventName==="error")try{let parsed=JSON.parse(payload);errorMessage4=parsed.message??"Sandbox pull failed",errorCode=parsed.code}catch{errorMessage4="Sandbox pull failed"}}}}finally{reader.releaseLock()}if(errorMessage4)throw errorCode==="readiness_failed"?new SandboxReadinessError(errorMessage4):new Error(errorMessage4);if(!completed)throw new Error("Sandbox pull stream ended before completion");return{readiness:readiness??{status:"skipped",reason:"not_reported",durationMs:0}}}async checkSubdomain(projectId,slug){return(await this.request(`/api/management/projects/${projectId}/subdomain/check?slug=${encodeURIComponent(slug)}`)).data}async renameSubdomain(projectId,slug){return(await this.request(`/api/management/projects/${projectId}/subdomain`,{method:"PATCH",body:JSON.stringify({slug})})).data}async suggestSubdomains(projectId,opts){let params=new URLSearchParams;opts?.base&¶ms.set("base",opts.base),opts?.max!==void 0&¶ms.set("max",String(opts.max));let query=params.toString();return(await this.request(`/api/management/projects/${projectId}/subdomain/suggestions${query?`?${query}`:""}`)).data.suggestions}async listProjectDomains(projectId){return(await this.request(`/api/management/projects/${projectId}/domains`,{},{allow403:!0})).data}async addProjectDomain(projectId,input){return(await this.request(`/api/management/projects/${projectId}/domains`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async refreshProjectDomain(projectId,domainId){return(await this.request(`/api/management/projects/${projectId}/domains/${domainId}/refresh`,{method:"POST"},{allow403:!0})).data}async removeProjectDomain(projectId,domainId){await this.request(`/api/management/projects/${projectId}/domains/${domainId}`,{method:"DELETE"},{allow403:!0})}async searchRegisteredDomains(input){return(await this.request("/api/domains/search",{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async getRegisteredDomainPricing(domain){return(await this.request(`/api/domains/pricing/${encodeURIComponent(domain)}`,{},{allow403:!0})).data}async listOwnedRegisteredDomains(organizationId){return(await this.request(`/api/domains/${encodeURIComponent(organizationId)}`,{},{allow403:!0})).data}async purchaseRegisteredDomain(organizationId,input){return(await this.request(`/api/domains/${encodeURIComponent(organizationId)}/purchase`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async refreshRegisteredDomainPayment(organizationId,domainId){return(await this.request(`/api/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,{method:"POST"},{allow403:!0})).data}async listSchemas(projectId){return this.request(this.tenantPath(projectId,"/schema"))}async getSchema(projectId,typeName){return(await this.request(this.tenantPath(projectId,`/schema/types/${typeName}`))).data}async createSchema(projectId,contentType){return(await this.request(this.tenantPath(projectId,"/schema/types"),{method:"POST",body:JSON.stringify({contentType})})).data}async updateSchema(projectId,typeName,contentType,operations=[]){return(await this.request(this.tenantPath(projectId,`/schema/types/${typeName}`),{method:"PUT",body:JSON.stringify({contentType,...operations.length>0?{operations}:{}})})).data}async upsertSchemas(projectId,contentTypes,operations=[]){return(await this.request(this.tenantPath(projectId,"/schema/batch"),{method:"POST",body:JSON.stringify({contentTypes,...operations.length>0?{operations}:{}})})).data}async deleteSchema(projectId,typeName){return(await this.request(this.tenantPath(projectId,`/schema/types/${typeName}`),{method:"DELETE"})).data}async listEntries(projectId,typeName,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return this.request(this.tenantPath(projectId,`/entries/${typeName}${query}`))}async getEntry(projectId,typeName,id,locale){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/entries/${typeName}/${id}${query}`))).data}async createEntry(projectId,typeName,data2){return(await this.request(this.tenantPath(projectId,`/entries/${typeName}`),{method:"POST",body:JSON.stringify(data2)})).data}async updateEntry(projectId,typeName,id,locale,data2){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/entries/${typeName}/${id}${query}`),{method:"PUT",body:JSON.stringify(data2)})).data}async deleteEntry(projectId,typeName,id,locale){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/entries/${typeName}/${id}${query}`),{method:"DELETE"})).data}async queryEntries(projectId,sql){return this.request(this.tenantPath(projectId,"/entries/query"),{method:"POST",body:JSON.stringify({sql})})}async bulkCreateEntries(projectId,typeName,entries2){return this.request(this.tenantPath(projectId,`/entries/${typeName}/bulk-create`),{method:"POST",body:JSON.stringify({entries:entries2})})}async bulkUpdateEntries(projectId,typeName,payload){return this.request(this.tenantPath(projectId,`/entries/${typeName}/bulk-update`),{method:"POST",body:JSON.stringify(payload)})}async bulkDeleteEntries(projectId,typeName,payload){return this.request(this.tenantPath(projectId,`/entries/${typeName}/bulk-delete`),{method:"POST",body:JSON.stringify(payload)})}async getSingle(projectId,typeName,params){let searchParams=new URLSearchParams;params?.locale&&searchParams.set("locale",params.locale),params?.populate&&searchParams.set("populate",params.populate);let query=searchParams.size>0?`?${searchParams.toString()}`:"";return(await this.request(this.tenantPath(projectId,`/documents/${typeName}${query}`))).data}async updateSingle(projectId,typeName,locale,data2){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/documents/${typeName}${query}`),{method:"PUT",body:JSON.stringify(data2)})).data}async listAssets(projectId,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return this.request(this.tenantPath(projectId,`/assets${query}`))}async getAsset(projectId,id){return this.request(this.tenantPath(projectId,`/assets/${id}`))}async uploadAsset(projectId,formData){return(await(await this.rawRequest(this.tenantPath(projectId,"/assets/upload"),{method:"POST",body:formData})).json()).data}async generate(projectId,payload){return(await this.request(this.tenantPath(projectId,"/assets/generate"),{method:"POST",body:JSON.stringify(payload)})).data}async createFolder(projectId,name,parentId){return(await this.request(this.tenantPath(projectId,"/assets/folders"),{method:"POST",body:JSON.stringify({name,parentId:parentId??null})})).data}async moveAsset(projectId,id,parentId){return(await this.request(this.tenantPath(projectId,`/assets/${id}/move`),{method:"POST",body:JSON.stringify({parentId})})).data}async deleteAsset(projectId,id){return(await this.request(this.tenantPath(projectId,`/assets/${id}`),{method:"DELETE"})).data}async listForms(projectId){return(await this.request(this.tenantPath(projectId,"/forms"))).data}async getForm(projectId,id){return(await this.request(this.tenantPath(projectId,`/forms/${id}`))).data}async createForm(projectId,data2){return(await this.request(this.tenantPath(projectId,"/forms"),{method:"POST",body:JSON.stringify(data2)})).data}async updateForm(projectId,id,data2){return(await this.request(this.tenantPath(projectId,`/forms/${id}`),{method:"PUT",body:JSON.stringify(data2)})).data}async deleteForm(projectId,id){return(await this.request(this.tenantPath(projectId,`/forms/${id}`),{method:"DELETE"})).data}async listLabels(projectId,locale){let query=locale?`?locale=${encodeURIComponent(locale)}`:"";return(await this.request(this.tenantPath(projectId,`/labels${query}`))).data}async setLabel(projectId,data2){return(await this.request(this.tenantPath(projectId,"/labels"),{method:"POST",body:JSON.stringify(data2)})).data}async setLabels(projectId,records){return(await this.request(this.tenantPath(projectId,"/labels/sync"),{method:"POST",body:JSON.stringify({created:records,updated:[],deleted:[]})})).data}async deleteLabel(projectId,locale,key){return(await this.request(this.tenantPath(projectId,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{method:"DELETE"})).data}async getProjectAnalytics(projectId,params){let search=new URLSearchParams;params?.preset&&search.set("preset",params.preset),params?.groupBy&&search.set("groupBy",params.groupBy),params?.from&&search.set("from",params.from),params?.to&&search.set("to",params.to),params?.days!==void 0&&search.set("days",String(params.days));let query=search.toString();return(await this.request(this.projectEnvManagementPath(projectId,`/analytics${query?`?${query}`:""}`))).data}async setAnalyticsAnnotation(projectId,date,content2){return(await this.request(this.projectEnvManagementPath(projectId,`/analytics/annotations/${date}`),{method:"PUT",body:JSON.stringify({content:content2})}))?.data??null}async deleteAnalyticsAnnotation(projectId,date){return await this.setAnalyticsAnnotation(projectId,date,""),null}async listFormSubmissions(projectId,formId,params){let search=new URLSearchParams;params?.limit!==void 0&&search.set("limit",String(params.limit)),params?.offset!==void 0&&search.set("offset",String(params.offset)),params?.searchQuery&&search.set("searchQuery",params.searchQuery),params?.sortDirection&&search.set("sortDirection",params.sortDirection);let query=search.toString();return await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions${query?`?${query}`:""}`))}async getFormSubmission(projectId,formId,submissionId){return(await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions/${submissionId}`))).data}async getFormSubmissionStats(projectId,formId){return(await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions/stats`))).data}}}});var require_identity=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js"(exports2){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,"isAlias"),isDocument2=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,"isDocument"),isMap=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,"isMap"),isPair=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,"isPair"),isScalar=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,"isScalar"),isSeq=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ,"isSeq");function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}__name(isCollection,"isCollection");function isNode2(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}__name(isNode2,"isNode");var hasAnchor=__name(node=>(isScalar(node)||isCollection(node))&&!!node.anchor,"hasAnchor");exports2.ALIAS=ALIAS;exports2.DOC=DOC;exports2.MAP=MAP;exports2.NODE_TYPE=NODE_TYPE;exports2.PAIR=PAIR;exports2.SCALAR=SCALAR;exports2.SEQ=SEQ;exports2.hasAnchor=hasAnchor;exports2.isAlias=isAlias;exports2.isCollection=isCollection;exports2.isDocument=isDocument2;exports2.isMap=isMap;exports2.isNode=isNode2;exports2.isPair=isPair;exports2.isScalar=isScalar;exports2.isSeq=isSeq}});var require_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/visit.js"(exports2){"use strict";var identity2=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit2(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}__name(visit2,"visit");visit2.BREAK=BREAK;visit2.SKIP=SKIP;visit2.REMOVE=REMOVE;function visit_(key,node,visitor,path50){let ctrl=callVisitor(key,node,visitor,path50);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path50,ctrl),visit_(key,ctrl,visitor,path50);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path50=Object.freeze(path50.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path50);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path50=Object.freeze(path50.concat(node));let ck=visit_("key",node.key,visitor,path50);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path50);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visit_,"visit_");async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}__name(visitAsync,"visitAsync");visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path50){let ctrl=await callVisitor(key,node,visitor,path50);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path50,ctrl),visitAsync_(key,ctrl,visitor,path50);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path50=Object.freeze(path50.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path50);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path50=Object.freeze(path50.concat(node));let ck=await visitAsync_("key",node.key,visitor,path50);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path50);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visitAsync_,"visitAsync_");function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}__name(initVisitor,"initVisitor");function callVisitor(key,node,visitor,path50){if(typeof visitor=="function")return visitor(key,node,path50);if(identity2.isMap(node))return visitor.Map?.(key,node,path50);if(identity2.isSeq(node))return visitor.Seq?.(key,node,path50);if(identity2.isPair(node))return visitor.Pair?.(key,node,path50);if(identity2.isScalar(node))return visitor.Scalar?.(key,node,path50);if(identity2.isAlias(node))return visitor.Alias?.(key,node,path50)}__name(callVisitor,"callVisitor");function replaceNode(key,path50,node){let parent2=path50[path50.length-1];if(identity2.isCollection(parent2))parent2.items[key]=node;else if(identity2.isPair(parent2))key==="key"?parent2.key=node:parent2.value=node;else if(identity2.isDocument(parent2))parent2.contents=node;else{let pt2=identity2.isAlias(parent2)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt2} parent`)}}__name(replaceNode,"replaceNode");exports2.visit=visit2;exports2.visitAsync=visitAsync}});var require_directives=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/directives.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=__name(tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),"escapeTagName"),Directives=class _Directives{static{__name(this,"Directives")}constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version]=parts;if(version==="1.1"||version==="1.2")return this.yaml.version=version,!0;{let isValid=/^\d+\.\d+$/.test(version);return onError(6,`Unsupported YAML version ${version}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity2.isNode(doc.contents)){let tags={};visit2.visit(doc.contents,(_key,node)=>{identity2.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
48
|
+
`);if(eventName==="progress")try{let parsed=JSON.parse(payload);onProgress?.(parsed)}catch{}else if(eventName==="complete"){completed=!0;try{readiness=JSON.parse(payload).readiness??null}catch{}}else if(eventName==="error")try{let parsed=JSON.parse(payload);errorMessage5=parsed.message??"Sandbox pull failed",errorCode=parsed.code}catch{errorMessage5="Sandbox pull failed"}}}}finally{reader.releaseLock()}if(errorMessage5)throw errorCode==="readiness_failed"?new SandboxReadinessError(errorMessage5):new Error(errorMessage5);if(!completed)throw new Error("Sandbox pull stream ended before completion");return{readiness:readiness??{status:"skipped",reason:"not_reported",durationMs:0}}}async checkSubdomain(projectId,slug){return(await this.request(`/api/management/projects/${projectId}/subdomain/check?slug=${encodeURIComponent(slug)}`)).data}async renameSubdomain(projectId,slug){return(await this.request(`/api/management/projects/${projectId}/subdomain`,{method:"PATCH",body:JSON.stringify({slug})})).data}async suggestSubdomains(projectId,opts){let params=new URLSearchParams;opts?.base&¶ms.set("base",opts.base),opts?.max!==void 0&¶ms.set("max",String(opts.max));let query=params.toString();return(await this.request(`/api/management/projects/${projectId}/subdomain/suggestions${query?`?${query}`:""}`)).data.suggestions}async listProjectDomains(projectId){return(await this.request(`/api/management/projects/${projectId}/domains`,{},{allow403:!0})).data}async addProjectDomain(projectId,input){return(await this.request(`/api/management/projects/${projectId}/domains`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async refreshProjectDomain(projectId,domainId){return(await this.request(`/api/management/projects/${projectId}/domains/${domainId}/refresh`,{method:"POST"},{allow403:!0})).data}async removeProjectDomain(projectId,domainId){await this.request(`/api/management/projects/${projectId}/domains/${domainId}`,{method:"DELETE"},{allow403:!0})}async searchRegisteredDomains(input){return(await this.request("/api/domains/search",{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async getRegisteredDomainPricing(domain){return(await this.request(`/api/domains/pricing/${encodeURIComponent(domain)}`,{},{allow403:!0})).data}async listOwnedRegisteredDomains(organizationId){return(await this.request(`/api/domains/${encodeURIComponent(organizationId)}`,{},{allow403:!0})).data}async purchaseRegisteredDomain(organizationId,input){return(await this.request(`/api/domains/${encodeURIComponent(organizationId)}/purchase`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async refreshRegisteredDomainPayment(organizationId,domainId){return(await this.request(`/api/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,{method:"POST"},{allow403:!0})).data}async listSchemas(projectId){return this.request(this.tenantPath(projectId,"/schema"))}async getSchema(projectId,typeName){return(await this.request(this.tenantPath(projectId,`/schema/types/${typeName}`))).data}async createSchema(projectId,contentType){return(await this.request(this.tenantPath(projectId,"/schema/types"),{method:"POST",body:JSON.stringify({contentType})})).data}async updateSchema(projectId,typeName,contentType,operations=[]){return(await this.request(this.tenantPath(projectId,`/schema/types/${typeName}`),{method:"PUT",body:JSON.stringify({contentType,...operations.length>0?{operations}:{}})})).data}async upsertSchemas(projectId,contentTypes,operations=[]){return(await this.request(this.tenantPath(projectId,"/schema/batch"),{method:"POST",body:JSON.stringify({contentTypes,...operations.length>0?{operations}:{}})})).data}async deleteSchema(projectId,typeName){return(await this.request(this.tenantPath(projectId,`/schema/types/${typeName}`),{method:"DELETE"})).data}async listEntries(projectId,typeName,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return this.request(this.tenantPath(projectId,`/entries/${typeName}${query}`))}async getEntry(projectId,typeName,id,locale){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/entries/${typeName}/${id}${query}`))).data}async createEntry(projectId,typeName,data2){return(await this.request(this.tenantPath(projectId,`/entries/${typeName}`),{method:"POST",body:JSON.stringify(data2)})).data}async updateEntry(projectId,typeName,id,locale,data2){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/entries/${typeName}/${id}${query}`),{method:"PUT",body:JSON.stringify(data2)})).data}async deleteEntry(projectId,typeName,id,locale){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/entries/${typeName}/${id}${query}`),{method:"DELETE"})).data}async queryEntries(projectId,sql){return this.request(this.tenantPath(projectId,"/entries/query"),{method:"POST",body:JSON.stringify({sql})})}async bulkCreateEntries(projectId,typeName,entries2){return this.request(this.tenantPath(projectId,`/entries/${typeName}/bulk-create`),{method:"POST",body:JSON.stringify({entries:entries2})})}async bulkUpdateEntries(projectId,typeName,payload){return this.request(this.tenantPath(projectId,`/entries/${typeName}/bulk-update`),{method:"POST",body:JSON.stringify(payload)})}async bulkDeleteEntries(projectId,typeName,payload){return this.request(this.tenantPath(projectId,`/entries/${typeName}/bulk-delete`),{method:"POST",body:JSON.stringify(payload)})}async getSingle(projectId,typeName,params){let searchParams=new URLSearchParams;params?.locale&&searchParams.set("locale",params.locale),params?.populate&&searchParams.set("populate",params.populate);let query=searchParams.size>0?`?${searchParams.toString()}`:"";return(await this.request(this.tenantPath(projectId,`/documents/${typeName}${query}`))).data}async updateSingle(projectId,typeName,locale,data2){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/documents/${typeName}${query}`),{method:"PUT",body:JSON.stringify(data2)})).data}async listAssets(projectId,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return this.request(this.tenantPath(projectId,`/assets${query}`))}async getAsset(projectId,id){return this.request(this.tenantPath(projectId,`/assets/${id}`))}async uploadAsset(projectId,formData){return(await(await this.rawRequest(this.tenantPath(projectId,"/assets/upload"),{method:"POST",body:formData})).json()).data}async generate(projectId,payload){return(await this.request(this.tenantPath(projectId,"/assets/generate"),{method:"POST",body:JSON.stringify(payload)})).data}async createFolder(projectId,name,parentId){return(await this.request(this.tenantPath(projectId,"/assets/folders"),{method:"POST",body:JSON.stringify({name,parentId:parentId??null})})).data}async moveAsset(projectId,id,parentId){return(await this.request(this.tenantPath(projectId,`/assets/${id}/move`),{method:"POST",body:JSON.stringify({parentId})})).data}async deleteAsset(projectId,id){return(await this.request(this.tenantPath(projectId,`/assets/${id}`),{method:"DELETE"})).data}async listForms(projectId){return(await this.request(this.tenantPath(projectId,"/forms"))).data}async getForm(projectId,id){return(await this.request(this.tenantPath(projectId,`/forms/${id}`))).data}async createForm(projectId,data2){return(await this.request(this.tenantPath(projectId,"/forms"),{method:"POST",body:JSON.stringify(data2)})).data}async updateForm(projectId,id,data2){return(await this.request(this.tenantPath(projectId,`/forms/${id}`),{method:"PUT",body:JSON.stringify(data2)})).data}async deleteForm(projectId,id){return(await this.request(this.tenantPath(projectId,`/forms/${id}`),{method:"DELETE"})).data}async listLabels(projectId,locale){let query=locale?`?locale=${encodeURIComponent(locale)}`:"";return(await this.request(this.tenantPath(projectId,`/labels${query}`))).data}async setLabel(projectId,data2){return(await this.request(this.tenantPath(projectId,"/labels"),{method:"POST",body:JSON.stringify(data2)})).data}async setLabels(projectId,records){return(await this.request(this.tenantPath(projectId,"/labels/sync"),{method:"POST",body:JSON.stringify({created:records,updated:[],deleted:[]})})).data}async deleteLabel(projectId,locale,key){return(await this.request(this.tenantPath(projectId,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{method:"DELETE"})).data}async getProjectAnalytics(projectId,params){let search=new URLSearchParams;params?.preset&&search.set("preset",params.preset),params?.groupBy&&search.set("groupBy",params.groupBy),params?.from&&search.set("from",params.from),params?.to&&search.set("to",params.to),params?.days!==void 0&&search.set("days",String(params.days));let query=search.toString();return(await this.request(this.projectEnvManagementPath(projectId,`/analytics${query?`?${query}`:""}`))).data}async setAnalyticsAnnotation(projectId,date,content2){return(await this.request(this.projectEnvManagementPath(projectId,`/analytics/annotations/${date}`),{method:"PUT",body:JSON.stringify({content:content2})}))?.data??null}async deleteAnalyticsAnnotation(projectId,date){return await this.setAnalyticsAnnotation(projectId,date,""),null}async listFormSubmissions(projectId,formId,params){let search=new URLSearchParams;params?.limit!==void 0&&search.set("limit",String(params.limit)),params?.offset!==void 0&&search.set("offset",String(params.offset)),params?.searchQuery&&search.set("searchQuery",params.searchQuery),params?.sortDirection&&search.set("sortDirection",params.sortDirection);let query=search.toString();return await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions${query?`?${query}`:""}`))}async getFormSubmission(projectId,formId,submissionId){return(await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions/${submissionId}`))).data}async getFormSubmissionStats(projectId,formId){return(await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions/stats`))).data}}}});var require_identity=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js"(exports2){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,"isAlias"),isDocument2=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,"isDocument"),isMap=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,"isMap"),isPair=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,"isPair"),isScalar=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,"isScalar"),isSeq=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ,"isSeq");function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}__name(isCollection,"isCollection");function isNode2(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}__name(isNode2,"isNode");var hasAnchor=__name(node=>(isScalar(node)||isCollection(node))&&!!node.anchor,"hasAnchor");exports2.ALIAS=ALIAS;exports2.DOC=DOC;exports2.MAP=MAP;exports2.NODE_TYPE=NODE_TYPE;exports2.PAIR=PAIR;exports2.SCALAR=SCALAR;exports2.SEQ=SEQ;exports2.hasAnchor=hasAnchor;exports2.isAlias=isAlias;exports2.isCollection=isCollection;exports2.isDocument=isDocument2;exports2.isMap=isMap;exports2.isNode=isNode2;exports2.isPair=isPair;exports2.isScalar=isScalar;exports2.isSeq=isSeq}});var require_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/visit.js"(exports2){"use strict";var identity2=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit2(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}__name(visit2,"visit");visit2.BREAK=BREAK;visit2.SKIP=SKIP;visit2.REMOVE=REMOVE;function visit_(key,node,visitor,path50){let ctrl=callVisitor(key,node,visitor,path50);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path50,ctrl),visit_(key,ctrl,visitor,path50);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path50=Object.freeze(path50.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path50);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path50=Object.freeze(path50.concat(node));let ck=visit_("key",node.key,visitor,path50);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path50);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visit_,"visit_");async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}__name(visitAsync,"visitAsync");visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path50){let ctrl=await callVisitor(key,node,visitor,path50);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path50,ctrl),visitAsync_(key,ctrl,visitor,path50);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path50=Object.freeze(path50.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path50);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path50=Object.freeze(path50.concat(node));let ck=await visitAsync_("key",node.key,visitor,path50);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path50);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visitAsync_,"visitAsync_");function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}__name(initVisitor,"initVisitor");function callVisitor(key,node,visitor,path50){if(typeof visitor=="function")return visitor(key,node,path50);if(identity2.isMap(node))return visitor.Map?.(key,node,path50);if(identity2.isSeq(node))return visitor.Seq?.(key,node,path50);if(identity2.isPair(node))return visitor.Pair?.(key,node,path50);if(identity2.isScalar(node))return visitor.Scalar?.(key,node,path50);if(identity2.isAlias(node))return visitor.Alias?.(key,node,path50)}__name(callVisitor,"callVisitor");function replaceNode(key,path50,node){let parent2=path50[path50.length-1];if(identity2.isCollection(parent2))parent2.items[key]=node;else if(identity2.isPair(parent2))key==="key"?parent2.key=node:parent2.value=node;else if(identity2.isDocument(parent2))parent2.contents=node;else{let pt2=identity2.isAlias(parent2)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt2} parent`)}}__name(replaceNode,"replaceNode");exports2.visit=visit2;exports2.visitAsync=visitAsync}});var require_directives=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/directives.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=__name(tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),"escapeTagName"),Directives=class _Directives{static{__name(this,"Directives")}constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version]=parts;if(version==="1.1"||version==="1.2")return this.yaml.version=version,!0;{let isValid=/^\d+\.\d+$/.test(version);return onError(6,`Unsupported YAML version ${version}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity2.isNode(doc.contents)){let tags={};visit2.visit(doc.contents,(_key,node)=>{identity2.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
49
49
|
`)}};Directives.defaultYaml={explicit:!1,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};exports2.Directives=Directives}});var require_anchors=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/anchors.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit();function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){let msg=`Anchor must not contain whitespace or control characters: ${JSON.stringify(anchor)}`;throw new Error(msg)}return!0}__name(anchorIsValid,"anchorIsValid");function anchorNames(root2){let anchors=new Set;return visit2.visit(root2,{Value(_key,node){node.anchor&&anchors.add(node.anchor)}}),anchors}__name(anchorNames,"anchorNames");function findNewAnchor(prefix,exclude){for(let i=1;;++i){let name=`${prefix}${i}`;if(!exclude.has(name))return name}}__name(findNewAnchor,"findNewAnchor");function createNodeAnchors(doc,prefix){let aliasObjects=[],sourceObjects=new Map,prevAnchors=null;return{onAnchor:__name(source=>{aliasObjects.push(source),prevAnchors??(prevAnchors=anchorNames(doc));let anchor=findNewAnchor(prefix,prevAnchors);return prevAnchors.add(anchor),anchor},"onAnchor"),setAnchors:__name(()=>{for(let source of aliasObjects){let ref=sourceObjects.get(source);if(typeof ref=="object"&&ref.anchor&&(identity2.isScalar(ref.node)||identity2.isCollection(ref.node)))ref.node.anchor=ref.anchor;else{let error=new Error("Failed to resolve repeated object (this should not happen)");throw error.source=source,error}}},"setAnchors"),sourceObjects}}__name(createNodeAnchors,"createNodeAnchors");exports2.anchorIsValid=anchorIsValid;exports2.anchorNames=anchorNames;exports2.createNodeAnchors=createNodeAnchors;exports2.findNewAnchor=findNewAnchor}});var require_applyReviver=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/applyReviver.js"(exports2){"use strict";function applyReviver(reviver,obj,key,val2){if(val2&&typeof val2=="object")if(Array.isArray(val2))for(let i=0,len=val2.length;i<len;++i){let v0=val2[i],v1=applyReviver(reviver,val2,String(i),v0);v1===void 0?delete val2[i]:v1!==v0&&(val2[i]=v1)}else if(val2 instanceof Map)for(let k of Array.from(val2.keys())){let v0=val2.get(k),v1=applyReviver(reviver,val2,k,v0);v1===void 0?val2.delete(k):v1!==v0&&val2.set(k,v1)}else if(val2 instanceof Set)for(let v0 of Array.from(val2)){let v1=applyReviver(reviver,val2,v0,v0);v1===void 0?val2.delete(v0):v1!==v0&&(val2.delete(v0),val2.add(v1))}else for(let[k,v0]of Object.entries(val2)){let v1=applyReviver(reviver,val2,k,v0);v1===void 0?delete val2[k]:v1!==v0&&(val2[k]=v1)}return reviver.call(obj,key,val2)}__name(applyReviver,"applyReviver");exports2.applyReviver=applyReviver}});var require_toJS=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/toJS.js"(exports2){"use strict";var identity2=require_identity();function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v,i)=>toJS(v,String(i),ctx));if(value&&typeof value.toJSON=="function"){if(!ctx||!identity2.hasAnchor(value))return value.toJSON(arg,ctx);let data2={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data2),ctx.onCreate=res2=>{data2.res=res2,delete ctx.onCreate};let res=value.toJSON(arg,ctx);return ctx.onCreate&&ctx.onCreate(res),res}return typeof value=="bigint"&&!ctx?.keep?Number(value):value}__name(toJS,"toJS");exports2.toJS=toJS}});var require_Node=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Node.js"(exports2){"use strict";var applyReviver=require_applyReviver(),identity2=require_identity(),toJS=require_toJS(),NodeBase=class{static{__name(this,"NodeBase")}constructor(type){Object.defineProperty(this,identity2.NODE_TYPE,{value:type})}clone(){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(copy.range=this.range.slice()),copy}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!identity2.isDocument(doc))throw new TypeError("A document argument is required");let ctx={anchors:new Map,doc,keep:!0,mapAsMap:mapAsMap===!0,mapKeyWarned:!1,maxAliasCount:typeof maxAliasCount=="number"?maxAliasCount:100},res=toJS.toJS(this,"",ctx);if(typeof onAnchor=="function")for(let{count,res:res2}of ctx.anchors.values())onAnchor(res2,count);return typeof reviver=="function"?applyReviver.applyReviver(reviver,{"":res},"",res):res}};exports2.NodeBase=NodeBase}});var require_Alias=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Alias.js"(exports2){"use strict";var anchors=require_anchors(),visit2=require_visit(),identity2=require_identity(),Node2=require_Node(),toJS=require_toJS(),Alias=class extends Node2.NodeBase{static{__name(this,"Alias")}constructor(source){super(identity2.ALIAS),this.source=source,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(doc,ctx){let nodes;ctx?.aliasResolveCache?nodes=ctx.aliasResolveCache:(nodes=[],visit2.visit(doc,{Node:__name((_key,node)=>{(identity2.isAlias(node)||identity2.hasAnchor(node))&&nodes.push(node)},"Node")}),ctx&&(ctx.aliasResolveCache=nodes));let found;for(let node of nodes){if(node===this)break;node.anchor===this.source&&(found=node)}return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};let{anchors:anchors2,doc,maxAliasCount}=ctx,source=this.resolve(doc,ctx);if(!source){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(msg)}let data2=anchors2.get(source);if(data2||(toJS.toJS(source,null,ctx),data2=anchors2.get(source)),data2?.res===void 0){let msg="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(msg)}if(maxAliasCount>=0&&(data2.count+=1,data2.aliasCount===0&&(data2.aliasCount=getAliasCount(doc,source,anchors2)),data2.count*data2.aliasCount>maxAliasCount)){let msg="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(msg)}return data2.res}toString(ctx,_onComment,_onChompKeep){let src=`*${this.source}`;if(ctx){if(anchors.anchorIsValid(this.source),ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors2){if(identity2.isAlias(node)){let source=node.resolve(doc),anchor=anchors2&&source&&anchors2.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(identity2.isCollection(node)){let count=0;for(let item of node.items){let c2=getAliasCount(doc,item,anchors2);c2>count&&(count=c2)}return count}else if(identity2.isPair(node)){let kc=getAliasCount(doc,node.key,anchors2),vc=getAliasCount(doc,node.value,anchors2);return Math.max(kc,vc)}return 1}__name(getAliasCount,"getAliasCount");exports2.Alias=Alias}});var require_Scalar=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Scalar.js"(exports2){"use strict";var identity2=require_identity(),Node2=require_Node(),toJS=require_toJS(),isScalarValue=__name(value=>!value||typeof value!="function"&&typeof value!="object","isScalarValue"),Scalar=class extends Node2.NodeBase{static{__name(this,"Scalar")}constructor(value){super(identity2.SCALAR),this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS.toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";exports2.Scalar=Scalar;exports2.isScalarValue=isScalarValue}});var require_createNode=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/createNode.js"(exports2){"use strict";var Alias=require_Alias(),identity2=require_identity(),Scalar=require_Scalar(),defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(value,tagName,tags){if(tagName){let match=tags.filter(t2=>t2.tag===tagName),tagObj=match.find(t2=>!t2.format)??match[0];if(!tagObj)throw new Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t2=>t2.identify?.(value)&&!t2.format)}__name(findTagObject,"findTagObject");function createNode(value,tagName,ctx){if(identity2.isDocument(value)&&(value=value.contents),identity2.isNode(value))return value;if(identity2.isPair(value)){let map2=ctx.schema[identity2.MAP].createNode?.(ctx.schema,null,ctx);return map2.items.push(value),map2}(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt<"u"&&value instanceof BigInt)&&(value=value.valueOf());let{aliasDuplicateObjects,onAnchor,onTagObj,schema,sourceObjects}=ctx,ref;if(aliasDuplicateObjects&&value&&typeof value=="object"){if(ref=sourceObjects.get(value),ref)return ref.anchor??(ref.anchor=onAnchor(value)),new Alias.Alias(ref.anchor);ref={anchor:null,node:null},sourceObjects.set(value,ref)}tagName?.startsWith("!!")&&(tagName=defaultTagPrefix+tagName.slice(2));let tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(value&&typeof value.toJSON=="function"&&(value=value.toJSON()),!value||typeof value!="object"){let node2=new Scalar.Scalar(value);return ref&&(ref.node=node2),node2}tagObj=value instanceof Map?schema[identity2.MAP]:Symbol.iterator in Object(value)?schema[identity2.SEQ]:schema[identity2.MAP]}onTagObj&&(onTagObj(tagObj),delete ctx.onTagObj);let node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from=="function"?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar.Scalar(value);return tagName?node.tag=tagName:tagObj.default||(node.tag=tagObj.tag),ref&&(ref.node=node),node}__name(createNode,"createNode");exports2.createNode=createNode}});var require_Collection=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Collection.js"(exports2){"use strict";var createNode=require_createNode(),identity2=require_identity(),Node2=require_Node();function collectionFromPath(schema,path50,value){let v=value;for(let i=path50.length-1;i>=0;--i){let k=path50[i];if(typeof k=="number"&&Number.isInteger(k)&&k>=0){let a=[];a[k]=v,v=a}else v=new Map([[k,v]])}return createNode.createNode(v,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:__name(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema,sourceObjects:new Map})}__name(collectionFromPath,"collectionFromPath");var isEmptyPath=__name(path50=>path50==null||typeof path50=="object"&&!!path50[Symbol.iterator]().next().done,"isEmptyPath"),Collection=class extends Node2.NodeBase{static{__name(this,"Collection")}constructor(type,schema){super(type),Object.defineProperty(this,"schema",{value:schema,configurable:!0,enumerable:!1,writable:!0})}clone(schema){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return schema&&(copy.schema=schema),copy.items=copy.items.map(it2=>identity2.isNode(it2)||identity2.isPair(it2)?it2.clone(schema):it2),this.range&&(copy.range=this.range.slice()),copy}addIn(path50,value){if(isEmptyPath(path50))this.add(value);else{let[key,...rest]=path50,node=this.get(key,!0);if(identity2.isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path50){let[key,...rest]=path50;if(rest.length===0)return this.delete(key);let node=this.get(key,!0);if(identity2.isCollection(node))return node.deleteIn(rest);throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path50,keepScalar){let[key,...rest]=path50,node=this.get(key,!0);return rest.length===0?!keepScalar&&identity2.isScalar(node)?node.value:node:identity2.isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!identity2.isPair(node))return!1;let n=node.value;return n==null||allowScalar&&identity2.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(path50){let[key,...rest]=path50;if(rest.length===0)return this.has(key);let node=this.get(key,!0);return identity2.isCollection(node)?node.hasIn(rest):!1}setIn(path50,value){let[key,...rest]=path50;if(rest.length===0)this.set(key,value);else{let node=this.get(key,!0);if(identity2.isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}};exports2.Collection=Collection;exports2.collectionFromPath=collectionFromPath;exports2.isEmptyPath=isEmptyPath}});var require_stringifyComment=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyComment.js"(exports2){"use strict";var stringifyComment=__name(str=>str.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function indentComment(comment,indent){return/^\n+$/.test(comment)?comment.substring(1):indent?comment.replace(/^(?! *$)/gm,indent):comment}__name(indentComment,"indentComment");var lineComment=__name((str,indent,comment)=>str.endsWith(`
|
|
50
50
|
`)?indentComment(comment,indent):comment.includes(`
|
|
51
51
|
`)?`
|
|
@@ -315,7 +315,7 @@ ${codeblock}`,options),this.line=line,this.column=column,this.codeblock=codebloc
|
|
|
315
315
|
${preamble}`:`[${tableKey}]`),preamble&&tables?`${preamble}
|
|
316
316
|
${tables}`:preamble||tables}function stringify2(obj,{maxDepth=1e3,numbersAsFloat=!1}={}){if(extendedTypeOf(obj)!=="object")throw new TypeError("stringify can only be called with an object");let str=stringifyTable(0,obj,"",maxDepth,numbersAsFloat);return str[str.length-1]!==`
|
|
317
317
|
`?str+`
|
|
318
|
-
`:str}var BARE_KEY,init_stringify=__esm({"../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/stringify.js"(){BARE_KEY=/^[a-z0-9-_]+$/i;__name(extendedTypeOf,"extendedTypeOf");__name(isArrayOfTables,"isArrayOfTables");__name(formatString,"formatString");__name(stringifyValue,"stringifyValue");__name(stringifyInlineTable,"stringifyInlineTable");__name(stringifyArray,"stringifyArray");__name(stringifyArrayTable,"stringifyArrayTable");__name(stringifyTable,"stringifyTable");__name(stringify2,"stringify")}});var dist_exports3={};__export(dist_exports3,{TomlDate:()=>TomlDate,TomlError:()=>TomlError2,default:()=>dist_default3,parse:()=>parse4,stringify:()=>stringify2});var dist_default3,init_dist6=__esm({"../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/index.js"(){init_parse();init_stringify();init_date();init_error();dist_default3={parse:parse4,stringify:stringify2,TomlDate,TomlError:TomlError2}}});var require_dist2=__commonJS({"../../node_modules/.pnpm/@vercel+error-utils@2.2.1/node_modules/@vercel/error-utils/dist/index.js"(exports2,module2){"use strict";var __create2=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf2=Object.getPrototypeOf,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toESM2=__name((mod,isNodeMode,target)=>(target=mod!=null?__create2(__getProtoOf2(mod)):{},__copyProps2(isNodeMode||!mod||!mod.__esModule?__defProp2(target,"default",{value:mod,enumerable:!0}):target,mod)),"__toESM"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),src_exports={};__export2(src_exports,{errorToString:__name(()=>errorToString,"errorToString"),errorToStringFriendly:__name(()=>errorToStringFriendly,"errorToStringFriendly"),getSystemErrorMessage:__name(()=>getSystemErrorMessage,"getSystemErrorMessage"),isErrnoException:__name(()=>isErrnoException,"isErrnoException"),isError:__name(()=>isError,"isError"),isErrorLike:__name(()=>isErrorLike,"isErrorLike"),isObject:__name(()=>isObject2,"isObject"),isSpawnError:__name(()=>isSpawnError,"isSpawnError"),normalizeError:__name(()=>normalizeError,"normalizeError")});module2.exports=__toCommonJS2(src_exports);var import_node_util12=__toESM2(__require("node:util")),isObject2=__name(obj=>typeof obj=="object"&&obj!==null,"isObject"),isError=__name(error=>import_node_util12.default.types.isNativeError(error),"isError"),isErrnoException=__name(error=>isError(error)&&"code"in error,"isErrnoException"),nativeGetSystemErrorMessage=import_node_util12.default.getSystemErrorMessage,getSystemErrorMessageFallback=__name(errno=>import_node_util12.default.getSystemErrorMap().get(errno)?.[1]??`Unknown system error ${errno}`,"getSystemErrorMessageFallback"),isErrorLike=__name(error=>isObject2(error)&&"message"in error,"isErrorLike"),errorToString=__name((error,fallback)=>isError(error)||isErrorLike(error)?error.message:typeof error=="string"?error:fallback??"An unknown error has ocurred.","errorToString"),getSystemErrorMessage=nativeGetSystemErrorMessage??getSystemErrorMessageFallback,errorToStringFriendly=__name((error,fallback)=>isErrnoException(error)&&typeof error.errno=="number"?getSystemErrorMessage(error.errno):errorToString(error,fallback),"errorToStringFriendly"),normalizeError=__name(error=>{if(isError(error))return error;let errorMessage4=errorToString(error);return isErrorLike(error)?Object.assign(new Error(errorMessage4),error):new Error(errorMessage4)},"normalizeError");function isSpawnError(v){return isErrnoException(v)&&"spawnargs"in v}__name(isSpawnError,"isSpawnError")}});var require_read_config_file=__commonJS({"../../node_modules/.pnpm/@vercel+frameworks@3.30.9/node_modules/@vercel/frameworks/dist/read-config-file.js"(exports2,module2){"use strict";var __create2=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf2=Object.getPrototypeOf,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toESM2=__name((mod,isNodeMode,target)=>(target=mod!=null?__create2(__getProtoOf2(mod)):{},__copyProps2(isNodeMode||!mod||!mod.__esModule?__defProp2(target,"default",{value:mod,enumerable:!0}):target,mod)),"__toESM"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),read_config_file_exports={};__export2(read_config_file_exports,{readConfigFile:__name(()=>readConfigFile,"readConfigFile")});module2.exports=__toCommonJS2(read_config_file_exports);var import_js_yaml=__toESM2(require_js_yaml2()),import_smol_toml=(init_dist6(),__toCommonJS(dist_exports3)),import_fs3=__require("fs"),import_error_utils=require_dist2(),{readFile:readFile6}=import_fs3.promises;async function readFileOrNull2(file){try{return await readFile6(file)}catch(error){if(!(0,import_error_utils.isErrnoException)(error)||error.code!=="ENOENT")throw error}return null}__name(readFileOrNull2,"readFileOrNull");async function readConfigFile(files){files=Array.isArray(files)?files:[files];for(let name of files){let data2=await readFileOrNull2(name);if(data2){let str=data2.toString("utf8");if(name.endsWith(".json"))return JSON.parse(str);if(name.endsWith(".toml"))return(0,import_smol_toml.parse)(str);if(name.endsWith(".yaml")||name.endsWith(".yml"))return import_js_yaml.default.safeLoad(str,{filename:name})}}return null}__name(readConfigFile,"readConfigFile")}});var require_types=__commonJS({"../../node_modules/.pnpm/@vercel+frameworks@3.30.9/node_modules/@vercel/frameworks/dist/types.js"(exports2,module2){"use strict";var __defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__hasOwnProp2=Object.prototype.hasOwnProperty,__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),types_exports={};module2.exports=__toCommonJS2(types_exports)}});var require_frameworks=__commonJS({"../../node_modules/.pnpm/@vercel+frameworks@3.30.9/node_modules/@vercel/frameworks/dist/frameworks.js"(exports2,module2){"use strict";var __defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__reExport=__name((target,mod,secondTarget)=>(__copyProps2(target,mod,"default"),secondTarget&&__copyProps2(secondTarget,mod,"default")),"__reExport"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),frameworks_exports={};__export2(frameworks_exports,{default:__name(()=>frameworks_default,"default"),frameworkList:__name(()=>frameworkList,"frameworkList"),frameworks:__name(()=>frameworks2,"frameworks")});module2.exports=__toCommonJS2(frameworks_exports);var import_path3=__require("path"),import_fs3=__require("fs"),import_read_config_file=require_read_config_file();__reExport(frameworks_exports,require_types(),module2.exports);var{readdir:readdir2,readFile:readFile6,unlink}=import_fs3.promises,frameworks2=[{name:"Container",slug:"container",runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/container.svg",tagline:"Deploy any project as a container image built from a Dockerfile.",description:"A project deployed as a container image, built from a Dockerfile.vercel or Containerfile.vercel.",website:"https://docs.docker.com/reference/dockerfile/",useRuntime:{src:"<detect>",use:"@vercel/container"},detectors:{some:[{path:"Dockerfile.vercel"},{path:"Containerfile.vercel"}]},settings:{installCommand:{placeholder:"None",value:null},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{placeholder:"None"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Blitz.js (Legacy)",slug:"blitzjs",demo:"https://blitz-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/blitz.svg",tagline:"Blitz.js: The Fullstack React Framework",description:"A brand new Blitz.js app - the result of running `npx blitz@0.45.4 new`.",website:"https://blitzjs.com",envPrefix:"NEXT_PUBLIC_",useRuntime:{src:"package.json",use:"@vercel/next"},detectors:{some:[{path:"blitz.config.js"},{path:"blitz.config.ts"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `blitz build`",value:"blitz build"},devCommand:{value:"blitz start"},outputDirectory:{placeholder:"Next.js default"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Next.js",slug:"nextjs",demo:"https://nextjs-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/next.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/next-dark.svg",screenshot:"https://py8fhxnkzwtsqdo9.public.blob.vercel-storage.com/front/import/nextjs.png",tagline:"Next.js makes you productive with React instantly \u2014 whether you want to build static or dynamic sites.",description:"A Next.js app and a Serverless Function API.",website:"https://nextjs.org",sort:1,envPrefix:"NEXT_PUBLIC_",useRuntime:{src:"package.json",use:"@vercel/next"},detectors:{every:[{matchPackage:"next"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `next build`",value:"next build"},devCommand:{value:"next dev --port $PORT",placeholder:"next"},outputDirectory:{placeholder:"Next.js default"}},recommendedIntegrations:[{id:"oac_5lUsiANun1DEzgLg0NZx5Es3",dependencies:["next-plugin-sentry","next-sentry-source-maps"]}],getOutputDirName:__name(async()=>"public","getOutputDirName"),cachePattern:".next/cache/**"},{name:"Gatsby.js",slug:"gatsby",demo:"https://gatsby.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/gatsby.svg",tagline:"Gatsby helps developers build blazing fast websites and apps with React.",description:"A Gatsby starter app with an API Route.",website:"https://gatsbyjs.org",sort:5,envPrefix:"GATSBY_",detectors:{every:[{matchPackage:"gatsby"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `gatsby build`",value:"gatsby build"},devCommand:{value:"gatsby develop --port $PORT",placeholder:"gatsby develop"},outputDirectory:{value:"public"}},dependency:"gatsby",getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:__name(async dirPrefix=>{try{let nowRoutesPath=(0,import_path3.join)(dirPrefix,"public","__now_routes_g4t5bY.json"),content2=await readFile6(nowRoutesPath,"utf8"),nowRoutes=JSON.parse(content2);try{await unlink(nowRoutesPath)}catch{}return nowRoutes}catch{return[{src:"^/static/(.*)$",headers:{"cache-control":"public,max-age=31536000,immutable"},continue:!0},{src:"^/.*\\.(js|css)$",headers:{"cache-control":"public,max-age=31536000,immutable"},continue:!0},{src:"^/(sw\\.js|app-data\\.json|.*\\.html|page-data/.*)$",headers:{"cache-control":"public,max-age=0,must-revalidate"},continue:!0},{handle:"filesystem"},{src:".*",status:404,dest:"404.html"}]}},"defaultRoutes"),cachePattern:"{.cache,public}/**"},{name:"Remix",slug:"remix",demo:"https://remix-run-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/remix-no-shadow.svg",tagline:"Build Better Websites",description:"A new Remix app \u2014 the result of running `npx create-remix`.",website:"https://remix.run",sort:6,supersedes:["hydrogen","vite","node"],useRuntime:{src:"package.json",use:"@vercel/remix-builder"},ignoreRuntimes:["@vercel/node"],detectors:{some:[{matchPackage:"@remix-run/dev"},{path:"remix.config.js"},{path:"remix.config.mjs"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"remix build",placeholder:"`npm run build` or `remix build`"},devCommand:{value:"remix dev",placeholder:"remix dev"},outputDirectory:{value:"public"}},dependency:"remix",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"React Router",slug:"react-router",demo:"https://react-router-v7-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/react-router.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/react-router-dark.svg",tagline:"Declarative routing for React",description:"A user-obsessed, standards-focused, multi-strategy router you can deploy anywhere.",website:"https://reactrouter.com",sort:7,supersedes:["hydrogen","vite","node"],useRuntime:{src:"package.json",use:"@vercel/remix-builder"},ignoreRuntimes:["@vercel/node"],detectors:{some:[{path:"vite.config.js",matchContent:"@react-router/dev/vite"},{path:"vite.config.ts",matchContent:"@react-router/dev/vite"},{path:"react-router.config.js"},{path:"react-router.config.ts"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"react-router build",placeholder:"`npm run build` or `react-router build`"},devCommand:{value:"react-router dev",placeholder:"react-router dev"},outputDirectory:{value:"build"}},dependency:"react-router",getOutputDirName:__name(async()=>"build","getOutputDirName")},{name:"Astro",slug:"astro",demo:"https://astro-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/astro.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/astro-dark.svg",tagline:"Astro is a new kind of static site builder for the modern web. Powerful developer experience meets lightweight output.",description:"An Astro site, using the basics starter kit.",website:"https://astro.build",envPrefix:"PUBLIC_",detectors:{every:[{matchPackage:"astro"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"astro build",placeholder:"`npm run build` or `astro build`"},devCommand:{value:"astro dev --port $PORT",placeholder:"astro dev"},outputDirectory:{value:"dist"}},dependency:"astro",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{src:"^/assets/(.*)$",headers:{"cache-control":"public, max-age=31536000, immutable"},continue:!0},{src:"^/_astro/(.*)$",headers:{"cache-control":"public, max-age=31536000, immutable"},continue:!0}]},{name:"Hexo",slug:"hexo",demo:"https://hexo-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/hexo.svg",tagline:"Hexo is a fast, simple & powerful blog framework powered by Node.js.",description:"A Hexo site, created with the Hexo CLI.",website:"https://hexo.io",detectors:{every:[{matchPackage:"hexo"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `hexo generate`",value:"hexo generate"},devCommand:{value:"hexo server --port $PORT",placeholder:"hexo server"},outputDirectory:{value:"public"}},dependency:"hexo",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Eleventy",slug:"eleventy",demo:"https://eleventy-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/eleventy.svg",tagline:"11ty is a simpler static site generator written in JavaScript, created to be an alternative to Jekyll.",description:"An Eleventy site, created with npm init.",website:"https://www.11ty.dev",detectors:{every:[{matchPackage:"@11ty/eleventy"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `npx @11ty/eleventy`",value:"npx @11ty/eleventy"},devCommand:{value:"npx @11ty/eleventy --serve --watch --port $PORT",placeholder:"npx @11ty/eleventy --serve"},outputDirectory:{value:"_site"}},dependency:"@11ty/eleventy",getOutputDirName:__name(async()=>"_site","getOutputDirName"),cachePattern:".cache/**"},{name:"Docusaurus (v2+)",slug:"docusaurus-2",demo:"https://docusaurus-2-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/docusaurus.svg",tagline:"Docusaurus makes it easy to maintain Open Source documentation websites.",description:"A static Docusaurus site that makes it easy to maintain OSS documentation.",website:"https://v2.docusaurus.io",detectors:{some:[{matchPackage:"@docusaurus/core"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `docusaurus build`",value:"docusaurus build"},devCommand:{value:"docusaurus start --port $PORT",placeholder:"docusaurus start"},outputDirectory:{value:"build"}},dependency:"@docusaurus/core",getOutputDirName:__name(async dirPrefix=>{let base="build";try{let location=(0,import_path3.join)(dirPrefix,base),content2=await readdir2(location,{withFileTypes:!0});if(content2.length===1&&content2[0].isDirectory())return(0,import_path3.join)(base,content2[0].name)}catch(error){console.error("Error detecting output directory: ",error)}return base},"getOutputDirName"),defaultRoutes:[{src:"^/[^./]+\\.[0-9a-f]{8}\\.(css|js)$",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{src:"^/assets/images/[^/]+-[0-9a-f]{32}\\.(ico|svg|jpg|jpeg|png|gif|webp)$",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{src:"^/assets/medias/[^/]+-[0-9a-f]{32}\\.(ogv|wav|mp3|m4a|aac|oga|flac)$",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{src:"^/assets/files/[^/]+-[0-9a-f]{32}\\.(pdf|doc|docx|xls|xlsx|zip|rar)$",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{src:"^/ideal-img/[^/]+\\.[0-9a-f]{7}\\.\\d+\\.(png|jpe?g|gif)$",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{handle:"filesystem"},{src:".*",status:404,dest:"404.html"}]},{name:"Docusaurus (v1)",slug:"docusaurus",demo:"https://docusaurus-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/docusaurus.svg",tagline:"Docusaurus makes it easy to maintain Open Source documentation websites.",description:"A static Docusaurus site that makes it easy to maintain OSS documentation.",website:"https://docusaurus.io/",detectors:{some:[{matchPackage:"docusaurus"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `docusaurus-build`",value:"docusaurus-build"},devCommand:{value:"docusaurus-start --port $PORT",placeholder:"docusaurus-start"},outputDirectory:{value:"build"}},dependency:"docusaurus",getOutputDirName:__name(async dirPrefix=>{let base="build";try{let location=(0,import_path3.join)(dirPrefix,base),content2=await readdir2(location,{withFileTypes:!0});if(content2.length===1&&content2[0].isDirectory())return(0,import_path3.join)(base,content2[0].name)}catch(error){console.error("Error detecting output directory: ",error)}return base},"getOutputDirName")},{name:"Preact",slug:"preact",demo:"https://preact-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/preact.svg",tagline:"Preact is a fast 3kB alternative to React with the same modern API.",description:"A Preact app, created with the Preact CLI.",website:"https://preactjs.com",detectors:{every:[{matchPackage:"preact-cli"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `preact build`",value:"preact build"},devCommand:{value:"preact watch --port $PORT",placeholder:"preact watch"},outputDirectory:{value:"build"}},dependency:"preact-cli",getOutputDirName:__name(async()=>"build","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"SolidStart (v1)",slug:"solidstart-1",demo:"https://solid-start-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/solid.svg",tagline:"Simple and performant reactivity for building user interfaces.",description:"A Solid app, created with SolidStart.",website:"https://start.solidjs.com",envPrefix:"VITE_",detectors:{every:[{matchPackage:"solid-js"},{matchPackage:"@solidjs/start"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vinxi build`",value:"vinxi build"},devCommand:{value:"vinxi dev"},outputDirectory:{value:".output"}},getOutputDirName:__name(async()=>".output","getOutputDirName")},{name:"SolidStart (v0)",slug:"solidstart",demo:"https://solid-start-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/solid.svg",tagline:"Simple and performant reactivity for building user interfaces.",description:"A Solid app, created with SolidStart.",website:"https://solidjs.com",envPrefix:"VITE_",sort:98,detectors:{every:[{matchPackage:"solid-js"},{matchPackage:"solid-start"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `solid-start build`",value:"solid-start build"},devCommand:{value:"solid-start dev"},outputDirectory:{value:".output"}},getOutputDirName:__name(async()=>".output","getOutputDirName")},{name:"Dojo",slug:"dojo",demo:"https://dojo-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/dojo.svg",tagline:"Dojo is a modern progressive, TypeScript first framework.",description:"A Dojo app, created with the Dojo CLI's cli-create-app command.",website:"https://dojo.io",detectors:{some:[{matchPackage:"@dojo/framework"},{path:".dojorc"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `dojo build`",value:"dojo build"},devCommand:{value:"dojo build -m dev -w -s -p $PORT",placeholder:"dojo build -m dev -w -s"},outputDirectory:{value:"output/dist"}},dependency:"@dojo/cli",getOutputDirName:__name(async()=>(0,import_path3.join)("output","dist"),"getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/service-worker.js",headers:{"cache-control":"s-maxage=0"},continue:!0},{src:"/(.*)",dest:"/index.html"}],defaulHeaders:[{source:"/service-worker.js",regex:"/service-worker.js",headers:{"cache-control":"s-maxage=0"},continue:!0}]},{name:"Ember.js",slug:"ember",demo:"https://ember-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/ember.svg",tagline:"Ember.js helps webapp developers be more productive out of the box.",description:"An Ember app, created with the Ember CLI.",website:"https://emberjs.com/",detectors:{some:[{matchPackage:"ember-source"},{matchPackage:"ember-cli"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `ember build`",value:"ember build"},devCommand:{value:"ember serve --port $PORT",placeholder:"ember serve"},outputDirectory:{value:"dist"}},dependency:"ember-cli",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Vue.js",slug:"vue",demo:"https://vue-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/vue.svg",tagline:"Vue.js is a versatile JavaScript framework that is as approachable as it is performant.",description:"A Vue.js app, created with the Vue CLI.",website:"https://vuejs.org",envPrefix:"VUE_APP_",detectors:{every:[{matchPackage:"@vue/cli-service"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vue-cli-service build`",value:"vue-cli-service build"},devCommand:{value:"vue-cli-service serve --port $PORT",placeholder:"vue-cli-service serve"},outputDirectory:{value:"dist"}},dependency:"@vue/cli-service",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{src:"^/[^/]*\\.(js|txt|ico|json)",headers:{"cache-control":"max-age=300"},continue:!0},{src:"^/(img|js|css|fonts|media)/[^/]+\\.[0-9a-f]{8}\\.*",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{handle:"filesystem"},{src:"^.*",dest:"/index.html"}]},{name:"Scully",slug:"scully",demo:"https://scully-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/scullyio-logo.svg",tagline:"Scully is a static site generator for Angular.",description:"The Static Site Generator for Angular apps.",website:"https://github.com/scullyio/scully",detectors:{every:[{matchPackage:"@scullyio/init"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `ng build && scully`",value:"ng build && scully"},devCommand:{value:"ng serve --port $PORT",placeholder:"ng serve"},outputDirectory:{value:"dist"}},dependency:"@scullyio/init",getOutputDirName:__name(async()=>"dist/static","getOutputDirName")},{name:"Ionic Angular",slug:"ionic-angular",demo:"https://ionic-angular-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/ionic.svg",tagline:"Ionic Angular allows you to build mobile PWAs with Angular and the Ionic Framework.",description:"An Ionic Angular site, created with the Ionic CLI.",website:"https://ionicframework.com",detectors:{every:[{matchPackage:"@ionic/angular"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `ng build`",value:"ng build"},devCommand:{value:"ng serve --port $PORT"},outputDirectory:{value:"www"}},dependency:"@ionic/angular",getOutputDirName:__name(async()=>"www","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Angular",slug:"angular",demo:"https://angular-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/angular.svg",tagline:"Angular is a TypeScript-based cross-platform framework from Google.",description:"An Angular app, created with the Angular CLI.",website:"https://angular.io",detectors:{every:[{matchPackage:"@angular/cli"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `ng build`",value:"ng build"},devCommand:{value:"ng serve --port $PORT",placeholder:"ng serve"},outputDirectory:{value:"dist"}},dependency:"@angular/cli",getOutputDirName:__name(async dirPrefix=>{let base="dist";try{let location=(0,import_path3.join)(dirPrefix,base),content2=await readdir2(location,{withFileTypes:!0});if(content2.length===1&&content2[0].isDirectory()){let potentialOutDir=(0,import_path3.join)(base,content2[0].name),potentialOutDirWithBrowser=(0,import_path3.join)(potentialOutDir,"browser");return(0,import_fs3.existsSync)(potentialOutDirWithBrowser)?potentialOutDirWithBrowser:potentialOutDir}}catch(error){console.error("Error detecting output directory: ",error)}return base},"getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Polymer",slug:"polymer",demo:"https://polymer-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/polymer.svg",tagline:"Polymer is an open-source webapps library from Google, for building using Web Components.",description:"A Polymer app, created with the Polymer CLI.",website:"https://www.polymer-project.org/",detectors:{every:[{matchPackage:"polymer-cli"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `polymer build`",value:"polymer build"},devCommand:{value:"polymer serve --port $PORT",placeholder:"polymer serve"},outputDirectory:{value:"build"}},dependency:"polymer-cli",getOutputDirName:__name(async dirPrefix=>{let base="build";try{let location=(0,import_path3.join)(dirPrefix,base),paths=(await readdir2(location)).filter(item=>!item.includes("."));return(0,import_path3.join)(base,paths[0])}catch(error){console.error("Error detecting output directory: ",error)}return base},"getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Svelte",slug:"svelte",demo:"https://svelte.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/svelte.svg",tagline:"Svelte lets you write high performance reactive apps with significantly less boilerplate.",description:"A basic Svelte app using the default template.",website:"https://svelte.dev",sort:3,detectors:{every:[{matchPackage:"svelte"},{matchPackage:"sirv-cli"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `rollup -c`",value:"rollup -c"},devCommand:{value:"rollup -c -w"},outputDirectory:{value:"public"}},dependency:"sirv-cli",getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"SvelteKit (v0)",slug:"sveltekit",demo:"https://sveltekit-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/svelte.svg",screenshot:"https://py8fhxnkzwtsqdo9.public.blob.vercel-storage.com/front/import/sveltekit.png",tagline:"SvelteKit is a framework for building web applications of all sizes.",description:"A SvelteKit legacy app optimized Edge-first.",website:"https://kit.svelte.dev",supersedes:["vite"],sort:99,envPrefix:"VITE_",detectors:{every:[{path:"package.json",matchContent:'"(dev)?(d|D)ependencies":\\s*{[^}]*"@sveltejs\\/kit":\\s*"1\\.0\\.0-next\\.(\\d+)"[^}]*}'}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `svelte-kit build`",value:"svelte-kit build"},devCommand:{value:"svelte-kit dev --port $PORT",placeholder:"svelte-kit dev"},outputDirectory:{value:"public"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"SvelteKit",slug:"sveltekit-1",demo:"https://sveltekit-1-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/svelte.svg",screenshot:"https://py8fhxnkzwtsqdo9.public.blob.vercel-storage.com/front/import/sveltekit.png",tagline:"SvelteKit is a framework for building web applications of all sizes.",description:"A SvelteKit app optimized Edge-first.",website:"https://kit.svelte.dev",supersedes:["vite"],detectors:{every:[{path:"package.json",matchContent:'"(dev)?(d|D)ependencies":\\s*{[^}]*"@sveltejs\\/kit":\\s*".+?"[^}]*}'}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"vite build",value:"vite build"},devCommand:{placeholder:"vite dev",value:"vite dev --port $PORT"},outputDirectory:{value:"public"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Ionic React",slug:"ionic-react",demo:"https://ionic-react-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/ionic.svg",tagline:"Ionic React allows you to build mobile PWAs with React and the Ionic Framework.",description:"An Ionic React site, created with the Ionic CLI.",website:"https://ionicframework.com",detectors:{every:[{matchPackage:"@ionic/react"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `react-scripts build`",value:"react-scripts build"},devCommand:{value:"react-scripts start"},outputDirectory:{value:"build"}},dependency:"@ionic/react",getOutputDirName:__name(async()=>"build","getOutputDirName"),defaultRoutes:[{src:"/static/(.*)",headers:{"cache-control":"s-maxage=31536000, immutable"},continue:!0},{src:"/service-worker.js",headers:{"cache-control":"s-maxage=0"},continue:!0},{src:"/sockjs-node/(.*)",dest:"/sockjs-node/$1"},{handle:"filesystem"},{src:"/static/(.*)",status:404,dest:"/404.html"},{src:"/(.*)",headers:{"cache-control":"s-maxage=0"},dest:"/index.html"}]},{name:"Create React App",slug:"create-react-app",demo:"https://create-react-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/react.svg",tagline:"Create React App allows you to get going with React in no time.",description:"A client-side React app created with create-react-app.",website:"https://create-react-app.dev",sort:4,envPrefix:"REACT_APP_",detectors:{some:[{matchPackage:"react-scripts"},{matchPackage:"react-dev-utils"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `react-scripts build`",value:"react-scripts build"},devCommand:{value:"react-scripts start"},outputDirectory:{value:"build"}},dependency:"react-scripts",getOutputDirName:__name(async()=>"build","getOutputDirName"),defaultRoutes:[{src:"/static/(.*)",headers:{"cache-control":"s-maxage=31536000, immutable"},continue:!0},{src:"/service-worker.js",headers:{"cache-control":"s-maxage=0"},continue:!0},{src:"/sockjs-node/(.*)",dest:"/sockjs-node/$1"},{handle:"filesystem"},{src:"/static/(.*)",status:404,dest:"/404.html"},{src:"/(.*)",headers:{"cache-control":"s-maxage=0"},dest:"/index.html"}]},{name:"Gridsome",slug:"gridsome",demo:"https://gridsome-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/gridsome.svg",tagline:"Gridsome is a Vue.js-powered framework for building websites & apps that are fast by default.",description:"A Gridsome app, created with the Gridsome CLI.",website:"https://gridsome.org/",detectors:{every:[{matchPackage:"gridsome"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `gridsome build`",value:"gridsome build"},devCommand:{value:"gridsome develop -p $PORT",placeholder:"gridsome develop"},outputDirectory:{value:"dist"}},dependency:"gridsome",getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"UmiJS",slug:"umijs",demo:"https://umijs-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/umi.svg",tagline:"UmiJS is an extensible enterprise-level React application framework.",description:"An UmiJS app, created using the Umi CLI.",website:"https://umijs.org",detectors:{every:[{matchPackage:"umi"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `umi build`",value:"umi build"},devCommand:{value:"umi dev --port $PORT",placeholder:"umi dev"},outputDirectory:{value:"dist"}},dependency:"umi",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Sapper",slug:"sapper",demo:"https://sapper-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/svelte.svg",tagline:"Sapper is a framework for building high-performance universal web apps with Svelte.",description:"A Sapper app, using the Sapper template.",website:"https://sapper.svelte.dev",detectors:{every:[{matchPackage:"sapper"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `sapper export`",value:"sapper export"},devCommand:{value:"sapper dev --port $PORT",placeholder:"sapper dev"},outputDirectory:{value:"__sapper__/export"}},dependency:"sapper",getOutputDirName:__name(async()=>"__sapper__/export","getOutputDirName")},{name:"Saber",slug:"saber",logo:"https://api-frameworks.vercel.sh/framework-logos/saber.svg",tagline:"Saber is a framework for building static sites in Vue.js that supports data from any source.",description:"A Saber site, created with npm init.",website:"https://saber.egoist.dev",detectors:{every:[{matchPackage:"saber"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `saber build`",value:"saber build"},devCommand:{value:"saber --port $PORT",placeholder:"saber"},outputDirectory:{value:"public"}},dependency:"saber",getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{src:"/_saber/.*",headers:{"cache-control":"max-age=31536000, immutable"}},{handle:"filesystem"},{src:".*",status:404,dest:"404.html"}]},{name:"Stencil",slug:"stencil",demo:"https://stencil.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/stencil.svg",tagline:"Stencil is a powerful toolchain for building Progressive Web Apps and Design Systems.",description:"A Stencil site, created with the Stencil CLI.",website:"https://stenciljs.com/",detectors:{every:[{matchPackage:"@stencil/core"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `stencil build`",value:"stencil build"},devCommand:{value:"stencil build --dev --watch --serve --port $PORT",placeholder:"stencil build --dev --watch --serve"},outputDirectory:{value:"www"}},dependency:"@stencil/core",getOutputDirName:__name(async()=>"www","getOutputDirName"),defaultRoutes:[{src:"/assets/(.*)",headers:{"cache-control":"max-age=2592000"},continue:!0},{src:"/build/p-.*",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{src:"/sw.js",headers:{"cache-control":"no-cache"},continue:!0},{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Nuxt",slug:"nuxtjs",demo:"https://nuxtjs-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/nuxt.svg",screenshot:"https://py8fhxnkzwtsqdo9.public.blob.vercel-storage.com/front/import/nuxtjs.png",tagline:"Nuxt is the open source framework that makes full-stack development with Vue.js intuitive.",description:"A Nuxt app, bootstrapped with create-nuxt-app.",website:"https://nuxt.com",sort:2,envPrefix:"NUXT_ENV_",supersedes:["nitro"],detectors:{some:[{matchPackage:"nuxt"},{matchPackage:"nuxt3"},{matchPackage:"nuxt-edge"},{matchPackage:"nuxt-nightly"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `nuxt build`",value:"nuxt build"},devCommand:{value:"nuxt dev"},outputDirectory:{value:"dist"}},dependency:"nuxt",getOutputDirName:__name(async()=>"dist","getOutputDirName"),cachePattern:".nuxt/**",defaultRoutes:[{src:"/sw.js",headers:{"cache-control":"no-cache"},continue:!0},{src:"/_nuxt/(.*)",headers:{"cache-control":"public,max-age=31536000,immutable"},continue:!0},{handle:"filesystem"},{src:"/(.*)",dest:"/200.html"}]},{name:"RedwoodJS",slug:"redwoodjs",demo:"https://redwood-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/redwoodjs.svg",tagline:"RedwoodJS is a full-stack framework for the Jamstack.",description:"A RedwoodJS app, bootstraped with create-redwood-app.",website:"https://redwoodjs.com",envPrefix:"REDWOOD_ENV_",useRuntime:{src:"package.json",use:"@vercel/redwood"},ignoreRuntimes:["@vercel/node"],detectors:{every:[{matchPackage:"@redwoodjs/core"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"yarn rw deploy vercel"},devCommand:{value:'yarn rw dev --fwd="--port=$PORT --open=false"',placeholder:"yarn rw dev"},outputDirectory:{placeholder:"RedwoodJS default"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Hugo",slug:"hugo",demo:"https://hugo-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/hugo.svg",tagline:"Hugo is the world\u2019s fastest framework for building websites, written in Go.",description:"A Hugo site, created with the Hugo CLI.",website:"https://gohugo.io",detectors:{some:[{path:"config.yaml",matchContent:"baseURL"},{path:"config.toml",matchContent:"baseURL"},{path:"config.json",matchContent:"baseURL"}]},settings:{installCommand:{placeholder:"None"},buildCommand:{placeholder:"`npm run build` or `hugo --gc`",value:"hugo --gc"},devCommand:{value:"hugo server -D -w -p $PORT",placeholder:"hugo server -D"},outputDirectory:{placeholder:"`public` or `publishDir` from the `config` file"}},getOutputDirName:__name(async dirPrefix=>{let config=await(0,import_read_config_file.readConfigFile)(["config.json","config.yaml","config.toml"].map(fileName=>(0,import_path3.join)(dirPrefix,fileName)));return config&&config.publishDir||"public"},"getOutputDirName"),defaultVersion:"0.58.2"},{name:"Jekyll",slug:"jekyll",demo:"https://jekyll-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/jekyll.svg",tagline:"Jekyll makes it super easy to transform your plain text into static websites and blogs.",description:"A Jekyll site, created with the Jekyll CLI.",website:"https://jekyllrb.com/",detectors:{every:[{path:"_config.yml"}]},settings:{installCommand:{value:"bundle install"},buildCommand:{placeholder:"`npm run build` or `jekyll build`",value:"jekyll build"},devCommand:{value:"bundle exec jekyll serve --watch --port $PORT",placeholder:"bundle exec jekyll serve"},outputDirectory:{placeholder:"`_site` or `destination` from `_config.yml`"}},getOutputDirName:__name(async dirPrefix=>{let config=await(0,import_read_config_file.readConfigFile)((0,import_path3.join)(dirPrefix,"_config.yml"));return config&&config.destination||"_site"},"getOutputDirName"),cachePattern:"{vendor/bin,vendor/cache,vendor/bundle}/**"},{name:"Brunch",slug:"brunch",demo:"https://brunch-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/brunch.svg",tagline:"Brunch is a fast and simple webapp build tool with seamless incremental compilation for rapid development.",description:"A Brunch app, created with the Brunch CLI.",website:"https://brunch.io/",detectors:{some:[{matchPackage:"brunch"},{path:"brunch-config.js"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `brunch build --production`",value:"brunch build --production"},devCommand:{value:"brunch watch --server --port $PORT",placeholder:"brunch watch --server"},outputDirectory:{value:"public"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Middleman",slug:"middleman",demo:"https://middleman-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/middleman.svg",tagline:"Middleman is a static site generator that uses all the shortcuts and tools in modern web development.",description:"A Middleman app, created with the Middleman CLI.",website:"https://middlemanapp.com/",detectors:{every:[{path:"config.rb"}]},settings:{installCommand:{value:"bundle install"},buildCommand:{placeholder:"`npm run build` or `bundle exec middleman build`",value:"bundle exec middleman build"},devCommand:{placeholder:"bundle exec middleman server",value:"bundle exec middleman server -p $PORT"},outputDirectory:{value:"build"}},getOutputDirName:__name(async()=>"build","getOutputDirName"),cachePattern:"{vendor/bin,vendor/cache,vendor/bundle}/**"},{name:"Zola",slug:"zola",demo:"https://zola-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/zola.svg",tagline:"Everything you need to make a static site engine in one binary.",description:'A Zola app, created with the "Getting Started" tutorial.',website:"https://www.getzola.org",detectors:{every:[{path:"config.toml",matchContent:"base_url"}]},settings:{installCommand:{placeholder:"None"},buildCommand:{value:"zola build"},devCommand:{placeholder:"zola serve",value:"zola serve --port $PORT"},outputDirectory:{value:"public"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultVersion:"0.13.0"},{name:"Hydrogen (v1)",slug:"hydrogen",demo:"https://hydrogen-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/hydrogen.svg",tagline:"React framework for headless commerce",description:"React framework for headless commerce",website:"https://hydrogen.shopify.dev",supersedes:["vite"],useRuntime:{src:"package.json",use:"@vercel/hydrogen"},envPrefix:"PUBLIC_",detectors:{some:[{matchPackage:"@shopify/hydrogen"},{path:"hydrogen.config.js"},{path:"hydrogen.config.ts"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"shopify hydrogen build",placeholder:"`npm run build` or `shopify hydrogen build`"},devCommand:{value:"shopify hydrogen dev",placeholder:"shopify hydrogen dev"},outputDirectory:{value:"dist"}},dependency:"@shopify/hydrogen",getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"Vite",slug:"vite",demo:"https://vite-vue-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/vite.svg",tagline:"Vite is a new breed of frontend build tool that significantly improves the frontend development experience.",description:"A Vue.js app, created with Vite.",website:"https://vitejs.dev",supersedes:["ionic-react"],envPrefix:"VITE_",detectors:{every:[{matchPackage:"vite"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vite build`",value:"vite build"},devCommand:{placeholder:"vite",value:"vite --port $PORT"},outputDirectory:{value:"dist"}},dependency:"vite",getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"TanStack Start",slug:"tanstack-start",logo:"https://api-frameworks.vercel.sh/framework-logos/tanstack-start.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/tanstack-start-dark.svg",tagline:"Full-stack Framework powered by TanStack Router for React and Solid.",description:"Full-document SSR, Streaming, Server Functions, bundling and more, powered by TanStack Router and Vite - Ready to deploy to your favorite hosting provider.",website:"https://tanstack.com/start",supersedes:["ionic-react","vite"],detectors:{every:[{matchPackage:"@tanstack/router-plugin"}],some:[{matchPackage:"@tanstack/react-start"},{matchPackage:"@tanstack/solid-start"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vite build`",value:"vite build"},devCommand:{placeholder:"vite",value:"vite --port $PORT"},outputDirectory:{value:"dist"}},getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"TanStack Start",slug:"tanstack-start-lovable",logo:"https://api-frameworks.vercel.sh/framework-logos/tanstack-start.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/tanstack-start-dark.svg",platform:{name:"lovable",logo:"https://api-frameworks.vercel.sh/framework-logos/lovable.svg"},tagline:"Full-stack Framework powered by TanStack Router imported from Lovable",description:"Full-document SSR, Streaming, Server Functions, bundling and more, imported from Lovable",website:"https://lovable.dev/",supersedes:["tanstack-start","ionic-react","vite"],detectors:{every:[{matchPackage:"@lovable.dev/vite-tanstack-config"}],some:[{matchPackage:"@tanstack/react-start"},{matchPackage:"@tanstack/solid-start"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vite build`",value:"vite build"},devCommand:{placeholder:"vite",value:"vite --port $PORT"},outputDirectory:{value:"dist"}},getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"VitePress",slug:"vitepress",demo:"https://vitepress-starter-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/vite.svg",tagline:"VitePress is VuePress' little brother, built on top of Vite.",description:"VuePress on top of Vite",website:"https://vitepress.vuejs.org/",detectors:{every:[{matchPackage:"vitepress"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vitepress build docs`",value:"vitepress build docs"},devCommand:{value:"vitepress dev docs --port $PORT"},outputDirectory:{value:"docs/.vitepress/dist"}},getOutputDirName:__name(async()=>"docs/.vitepress/dist","getOutputDirName")},{name:"VuePress",slug:"vuepress",demo:"https://vuepress-starter-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/vuepress.svg",tagline:"Vue-powered Static Site Generator",description:"Vue-powered Static Site Generator",website:"https://vuepress.vuejs.org/",detectors:{every:[{matchPackage:"vuepress"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vuepress build src`",value:"vuepress build src"},devCommand:{value:"vuepress dev src --port $PORT"},outputDirectory:{value:"src/.vuepress/dist"}},getOutputDirName:__name(async()=>"src/.vuepress/dist","getOutputDirName")},{name:"Parcel",slug:"parcel",demo:"https://parcel-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/parcel.svg",tagline:"Parcel is a zero configuration build tool for the web that scales to projects of any size and complexity.",description:"A vanilla web app built with Parcel.",website:"https://parceljs.org",detectors:{every:[{matchPackage:"parcel"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `parcel build`",value:"parcel build"},devCommand:{placeholder:"parcel",value:"parcel"},outputDirectory:{value:"dist"}},dependency:"parcel",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{src:"^/[^./]+\\.[0-9a-f]{8}\\.(css|js|png|jpg|webp|avif|svg)$",headers:{"cache-control":"s-maxage=31536000, immutable"},continue:!0},{handle:"filesystem"}]},{name:"FastAPI",slug:"fastapi",demo:"https://vercel-fastapi-gamma-smoky.vercel.app/",logo:"https://api-frameworks.vercel.sh/framework-logos/fastapi.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/fastapi.svg",tagline:"FastAPI framework, high performance, easy to learn, fast to code, ready for production",description:"FastAPI framework, high performance, easy to learn, fast to code, ready for production",website:"https://fastapi.tiangolo.com",supersedes:["python"],useRuntime:{src:"<detect>",use:"@vercel/python"},ignoreRuntimes:["@vercel/python"],detectors:{some:[{path:"requirements.txt",matchContent:"fastapi"},{path:"pyproject.toml",matchContent:"fastapi"},{path:"Pipfile",matchContent:"fastapi"}]},settings:{installCommand:{placeholder:"`pip install -r requirements.txt`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Flask",slug:"flask",logo:"https://api-frameworks.vercel.sh/framework-logos/flask.svg",tagline:"The Python micro web framework",description:"A Flask app, ready for production",website:"https://flask.palletsprojects.com",supersedes:["python"],useRuntime:{src:"<detect>",use:"@vercel/python"},ignoreRuntimes:["@vercel/python"],detectors:{some:[{path:"requirements.txt",matchContent:"[Ff]lask"},{path:"pyproject.toml",matchContent:"[Ff]lask"},{path:"Pipfile",matchContent:"[Ff]lask"}]},settings:{installCommand:{placeholder:"`pip install -r requirements.txt`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"FastHTML",slug:"fasthtml",demo:"https://fasthtml-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/fasthtml.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/fasthtml-dark.svg",tagline:"The fastest way to create an HTML app",description:"A library for writing fast and scalable Starlette-powered web applications",website:"https://fastht.ml",supersedes:["python"],useRuntime:{src:"main.py",use:"@vercel/python"},detectors:{every:[{path:"requirements.txt",matchContent:"python-fasthtml"}]},settings:{installCommand:{placeholder:"`pip install`"},buildCommand:{placeholder:"None",value:null},devCommand:{value:"uvicorn main:app --reload"},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/main"}]},{name:"Django",slug:"django",logo:"https://api-frameworks.vercel.sh/framework-logos/django.svg",tagline:"Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. ",description:"A Django project served via the Python Runtime.",website:"https://www.djangoproject.com",supersedes:["python"],useRuntime:{src:"<detect>",use:"@vercel/python"},ignoreRuntimes:["@vercel/python"],detectors:{some:[{path:"requirements.txt",matchContent:"[Dd]jango"},{path:"pyproject.toml",matchContent:"[Dd]jango"},{path:"Pipfile",matchContent:"[Dd]jango"},{path:"manage.py",matchContent:"DJANGO_SETTINGS_MODULE"}]},settings:{installCommand:{placeholder:"`pip install -r requirements.txt`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Ash",slug:"ash",logo:"https://api-frameworks.vercel.sh/framework-logos/ash.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/ash-dark.svg",tagline:"A filesystem-first framework for durable backend agents on Vercel.",description:"An Ash app: agents authored as a directory of files, compiled and served on Vercel.",detectors:{every:[{path:"package.json",matchContent:'"(dev)?(d|D)ependencies":\\s*{[^}]*"experimental-ash":\\s*".+?"[^}]*}'}]},settings:{installCommand:{placeholder:"`pnpm install`, `yarn install`, or `npm install`"},buildCommand:{value:"ash build",placeholder:"`npm run build` or `ash build`"},devCommand:{value:"ash dev",placeholder:"ash dev"},outputDirectory:{value:".output"}},getOutputDirName:__name(async()=>".output","getOutputDirName"),experimental:!0},{name:"eve",slug:"eve",logo:"https://api-frameworks.vercel.sh/framework-logos/eve.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/eve-dark.svg",tagline:"A filesystem-first framework for durable backend agents on Vercel.",description:"An eve app: agents authored as a directory of files, compiled and served on Vercel.",detectors:{every:[{path:"package.json",matchContent:'"(dev)?(d|D)ependencies":\\s*{[^}]*"eve":\\s*".+?"[^}]*}'}]},settings:{installCommand:{placeholder:"`pnpm install`, `yarn install`, or `npm install`"},buildCommand:{value:"eve build",placeholder:"`npm run build` or `eve build`"},devCommand:{value:"eve dev",placeholder:"eve dev"},outputDirectory:{value:".output"}},getOutputDirName:__name(async()=>".output","getOutputDirName")},{name:"Sanity",slug:"sanity",demo:"https://template-studio-clean.sanity.dev",logo:"https://api-frameworks.vercel.sh/framework-logos/sanity.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/sanity-dark.svg",tagline:"The back-end built for AI content operations. Power web, mobile, and agentic applications at scale.",description:"A Sanity Studio",website:"https://www.sanity.io",envPrefix:"SANITY_STUDIO_",detectors:{some:[{path:"sanity.config.js"},{path:"sanity.config.jsx"},{path:"sanity.config.ts"},{path:"sanity.config.tsx"}],every:[{matchPackage:"sanity"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `sanity build`",value:"sanity build"},devCommand:{value:"sanity dev --port $PORT"},outputDirectory:{value:"dist"}},dependency:"sanity",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Sanity (v2 - legacy)",slug:"sanity-v2",demo:"https://sanity-studio-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/sanity-v2.svg",tagline:"The structured content platform.",description:"A Sanity Studio",website:"https://www.sanity.io",envPrefix:"SANITY_STUDIO_",detectors:{some:[{path:"sanity.json"}],every:[{path:"package.json",matchContent:'"(dev)?(d|D)ependencies":\\s*{[^}]*"@sanity/cli":\\s*"\\^?2\\..*"[^}]*}'}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `sanity build`",value:"sanity build"},devCommand:{value:"sanity start --port $PORT"},outputDirectory:{value:"dist"}},dependency:"@sanity/cli",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Storybook",slug:"storybook",logo:"https://api-frameworks.vercel.sh/framework-logos/storybook.svg",tagline:"Frontend workshop for UI development",description:"Storybook is a frontend workshop for building UI components and pages in isolation.",website:"https://storybook.js.org",ignoreRuntimes:["@vercel/next","@vercel/node"],disableRootMiddleware:!0,detectionConfidence:"weak",detectors:{every:[{matchPackage:"storybook"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"storybook build",ignorePackageJsonScript:!0},devCommand:{value:"storybook dev -p $PORT"},outputDirectory:{value:"storybook-static"}},getOutputDirName:__name(async()=>"storybook-static","getOutputDirName")},{name:"Nitro",slug:"nitro",logo:"https://api-frameworks.vercel.sh/framework-logos/nitro.svg",demo:"https://nitro-template.vercel.app",tagline:"Nitro is a next generation server toolkit.",description:"Nitro lets you create web servers that run on multiple platforms.",website:"https://nitro.build/",detectors:{some:[{matchPackage:"nitropack"},{matchPackage:"nitro"}]},supersedes:["vite"],settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `nitro build`",value:"nitro build"},devCommand:{value:"nitro dev"},outputDirectory:{value:"dist"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Hono",slug:"hono",logo:"https://api-frameworks.vercel.sh/framework-logos/hono.svg",demo:"https://hono.vercel.dev",tagline:"Web framework built on Web Standards",description:"Fast, lightweight, built on Web Standards. Support for any JavaScript runtime.",website:"https://hono.dev",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/hono"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"hono"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},dependency:"hono",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Express",slug:"express",logo:"https://api-frameworks.vercel.sh/framework-logos/express.svg",demo:"https://express-vercel-example-demo.vercel.app/",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/express-dark.svg",tagline:"Fast, unopinionated, minimalist web framework for Node.js",description:"Fast, unopinionated, minimalist web framework for Node.js",website:"https://expressjs.com",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/express"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"express"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},dependency:"express",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"H3",slug:"h3",logo:"https://api-frameworks.vercel.sh/framework-logos/h3.svg",tagline:"Universal, Tiny, and Fast Servers",description:"H(TTP) server framework built on top of web standards for high performance and composability.",website:"https://h3.dev/",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/h3"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"h3"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},dependency:"h3",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Koa",slug:"koa",logo:"https://api-frameworks.vercel.sh/framework-logos/koa.svg",tagline:"Expressive middleware for Node.js using ES2017 async functions",description:"Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.",website:"https://koajs.com",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/koa"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"koa"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},dependency:"koa",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"NestJS",slug:"nestjs",logo:"https://api-frameworks.vercel.sh/framework-logos/nestjs.svg",tagline:"Framework for building efficient, scalable Node.js server-side applications",description:"A progressive Node.js framework for building efficient, reliable and scalable server-side applications.",website:"https://nestjs.com/",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/nestjs"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"@nestjs/core"}],some:[{path:"src/main.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/main.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/main.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/main.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/main.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/main.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},dependency:"nestjs",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Elysia",slug:"elysia",logo:"https://api-frameworks.vercel.sh/framework-logos/elysia.svg",tagline:"Ergonomic framework for humans",description:"TypeScript with End-to-End Type Safety, type integrity, and exceptional developer experience. Supercharged by Bun.",website:"https://elysiajs.com/",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/elysia"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"elysia"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Fastify",slug:"fastify",logo:"https://api-frameworks.vercel.sh/framework-logos/fastify.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/fastify-dark.svg",tagline:"Fast and low overhead web framework, for Node.js",description:"Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture.",website:"https://fastify.dev/",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/fastify"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"fastify"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"xmcp",slug:"xmcp",logo:"https://api-frameworks.vercel.sh/framework-logos/xmcp.svg",demo:"https://xmcp-template.vercel.app/",tagline:"The MCP framework for building AI-powered tools",description:"A framework for building Model Context Protocol servers with zero configuration.",website:"https://xmcp.dev",detectors:{some:[{path:"xmcp.config.ts"},{path:"xmcp.config.js"},{matchPackage:"xmcp"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `xmcp build`",value:"xmcp build --vercel"},devCommand:{value:"xmcp dev",placeholder:"xmcp dev"},outputDirectory:{value:"dist"}},dependency:"xmcp",getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"Python",slug:"python",runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/python.svg",tagline:"Python is a programming language that lets you work quickly and integrate systems more effectively.",description:"A generic Python application deployed as a serverless function.",website:"https://python.org",useRuntime:{src:"<detect>",use:"@vercel/python"},ignoreRuntimes:["@vercel/python"],detectors:{some:[{path:"requirements.txt"},{path:"pyproject.toml"},{path:"Pipfile"}]},settings:{installCommand:{placeholder:"`pip install -r requirements.txt`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Ruby",slug:"ruby",experimental:!0,runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/ruby.svg",tagline:"A dynamic, open source programming language with a focus on simplicity and productivity.",description:"A generic Ruby application deployed as a serverless function.",website:"https://www.ruby-lang.org",useRuntime:{src:"config.ru",use:"@vercel/ruby"},ignoreRuntimes:["@vercel/ruby"],detectors:{every:[{path:"config.ru"},{path:"Gemfile"}]},settings:{installCommand:{placeholder:"`bundle install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/config"}]},{name:"Rust",slug:"rust",experimental:!0,runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/rust.svg",tagline:"A language empowering everyone to build reliable and efficient software.",description:"A generic Rust application deployed as a serverless function.",website:"https://www.rust-lang.org",useRuntime:{src:"src/main.rs",use:"@vercel/rust"},ignoreRuntimes:["@vercel/rust"],detectors:{every:[{path:"Cargo.toml"},{path:"src/main.rs"}]},settings:{installCommand:{placeholder:"None"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`cargo run`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/src/main"}]},{name:"Axum",slug:"axum",experimental:!0,supersedes:["rust"],logo:"https://api-frameworks.vercel.sh/framework-logos/axum.svg",tagline:"Ergonomic and modular web framework built with Tokio, Tower, and Hyper.",description:"An Axum application deployed as a serverless function.",website:"https://github.com/tokio-rs/axum",useRuntime:{src:"src/main.rs",use:"@vercel/rust"},ignoreRuntimes:["@vercel/rust"],detectors:{every:[{path:"Cargo.toml",matchContent:"axum\\s*="},{path:"src/main.rs"}]},settings:{installCommand:{placeholder:"None"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`cargo run`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/src/main"}]},{name:"Actix Web",slug:"actix-web",experimental:!0,runtimeFramework:!0,supersedes:["rust"],logo:"https://api-frameworks.vercel.sh/framework-logos/actix-web.svg",tagline:"A powerful, pragmatic, and extremely fast web framework for Rust.",description:"An Actix Web application deployed as a serverless function.",website:"https://actix.rs",useRuntime:{src:"src/main.rs",use:"@vercel/rust"},ignoreRuntimes:["@vercel/rust"],detectors:{every:[{path:"Cargo.toml",matchContent:"actix-web\\s*="},{path:"src/main.rs"}]},settings:{installCommand:{placeholder:"None"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`cargo run`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/src/main"}]},{name:"Bun",slug:"bun",runtimeFramework:!0,experimental:!0,supersedes:["node"],logo:"https://api-frameworks.vercel.sh/framework-logos/bun.svg",tagline:"Bun is a fast all-in-one JavaScript runtime, bundler, and package manager.",description:"A Bun application deployed as a serverless function.",website:"https://bun.com",useRuntime:{src:"package.json",use:"@vercel/backends"},ignoreRuntimes:["@vercel/node"],detectors:{every:[{path:"bun.lock"}],some:[{path:"server.cjs"},{path:"server.js"},{path:"server.mjs"},{path:"server.mts"},{path:"server.ts"},{path:"server.cts"},{path:"src/server.cjs"},{path:"src/server.js"},{path:"src/server.mjs"},{path:"src/server.mts"},{path:"src/server.ts"},{path:"src/server.cts"}]},settings:{installCommand:{value:"bun install",placeholder:"bun install"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`bun dev`, `bun run dev`, or `bun --hot server.ts`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Node",slug:"node",runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/node.svg",tagline:"Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.",description:"A generic Node.js application deployed as a serverless function.",website:"https://nodejs.org",useRuntime:{src:"package.json",use:"@vercel/backends"},ignoreRuntimes:["@vercel/node"],detectors:{some:[{path:"server.cjs"},{path:"server.js"},{path:"server.mjs"},{path:"server.mts"},{path:"server.ts"},{path:"server.cts"},{path:"src/server.cjs"},{path:"src/server.js"},{path:"src/server.mjs"},{path:"src/server.mts"},{path:"src/server.ts"},{path:"src/server.cts"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`npm run dev`, `node server.js`, or `npx ts-node server.ts`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Go",slug:"go",runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/go.svg",tagline:"An open-source programming language supported by Google.",description:"A generic Go application deployed as a serverless function.",website:"https://go.dev",useRuntime:{src:"index.go",use:"@vercel/go"},ignoreRuntimes:["@vercel/go"],detectors:{every:[{path:"go.mod"}],some:[{path:"main.go"},{path:"cmd/api/main.go"},{path:"cmd/server/main.go"}]},settings:{installCommand:{placeholder:"`go mod download`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`go run .` or `go run ./cmd/api`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Services",slug:"services",logo:"https://api-frameworks.vercel.sh/framework-logos/services.svg",tagline:"Multiple services deployed as serverless functions within your project.",description:"Multiple services deployed as serverless functions within your project.",website:"https://vercel.com",settings:{installCommand:{placeholder:"None"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Mastra",slug:"mastra",logo:"https://api-frameworks.vercel.sh/framework-logos/mastra.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/mastra-dark.svg",tagline:"Build AI agents with a modern TypeScript stack",description:"Mastra is a framework for building AI-powered apps and agents with workflows, memory, streaming, evals, tracing, and Studio, an interactive UI for dev and testing.",website:"https://mastra.ai",detectors:{every:[{matchPackage:"mastra"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `mastra build`",value:"mastra build"},devCommand:{value:"mastra dev"},outputDirectory:{value:".mastra"}},getOutputDirName:__name(async()=>".mastra","getOutputDirName")},{name:"Other",slug:null,logo:"https://api-frameworks.vercel.sh/framework-logos/other.svg",description:"No framework or an unoptimized framework.",settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run vercel-build` or `npm run build`",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{placeholder:"`public` if it exists, or `.`"}},getOutputDirName:__name(async()=>"public","getOutputDirName")}],frameworkList=frameworks2,frameworks_default=frameworkList}});var require_detect_framework=__commonJS({"../../node_modules/.pnpm/@vercel+fs-detectors@6.15.3/node_modules/@vercel/fs-detectors/dist/detect-framework.js"(exports2,module2){"use strict";var __defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),detect_framework_exports={};__export2(detect_framework_exports,{detectFramework:__name(()=>detectFramework,"detectFramework"),detectFrameworkRecord:__name(()=>detectFrameworkRecord2,"detectFrameworkRecord"),detectFrameworkVersion:__name(()=>detectFrameworkVersion,"detectFrameworkVersion"),detectFrameworks:__name(()=>detectFrameworks,"detectFrameworks"),removeSupersededFrameworks:__name(()=>removeSupersededFrameworks,"removeSupersededFrameworks")});module2.exports=__toCommonJS2(detect_framework_exports);var import_child_process=__require("child_process");function shouldIncludeExperimentalFrameworks(useExperimentalFrameworks){if(typeof useExperimentalFrameworks=="boolean")return useExperimentalFrameworks;let experimentalEnv=process.env.VERCEL_USE_EXPERIMENTAL_FRAMEWORKS;return __name(val2=>val2==="1"||typeof val2=="string"&&val2.toLowerCase()==="true","isEnabled")(experimentalEnv)}__name(shouldIncludeExperimentalFrameworks,"shouldIncludeExperimentalFrameworks");function filterFrameworkList(frameworkList,useExperimentalFrameworks){return shouldIncludeExperimentalFrameworks(useExperimentalFrameworks)?frameworkList:frameworkList.filter(f=>!f.experimental)}__name(filterFrameworkList,"filterFrameworkList");async function matches(fs49,framework){let{detectors}=framework;if(!detectors)return;let{every,some:some2}=detectors;if(every!==void 0&&!Array.isArray(every)||some2!==void 0&&!Array.isArray(some2))return;let check=__name(async({path:path50,matchContent,matchPackage})=>{if(matchPackage&&matchContent)throw new Error(`Cannot specify "matchPackage" and "matchContent" in the same detector for "${framework.slug}"`);if(matchPackage&&path50)throw new Error(`Cannot specify "matchPackage" and "path" in the same detector for "${framework.slug}" because "path" is assumed to be "package.json".`);if(!path50&&!matchPackage)throw new Error(`Must specify either "path" or "matchPackage" in detector for "${framework.slug}".`);if(path50||(path50="package.json"),matchPackage&&(matchContent=`"(dev)?(d|D)ependencies":\\s*{[^}]*"${matchPackage}":\\s*"(.+?)"[^}]*}`),await fs49.hasPath(path50)!==!1){if(matchContent){if(await fs49.isFile(path50)===!1)return;let regex=new RegExp(matchContent,"m"),match=(await fs49.readFile(path50)).toString().match(regex);if(!match)return;if(matchPackage&&match[3])return{framework,detectedVersion:match[3]}}return{framework}}},"check"),result=[];if(every){let everyResult=await Promise.all(every.map(item=>check(item)));result.push(...everyResult)}if(some2){let someResult;for(let item of some2){let itemResult=await check(item);if(itemResult){someResult=itemResult;break}}result.push(someResult)}if(!result.every(res=>!!res))return;let detectedVersion=result.find(r=>typeof r=="object"&&r.detectedVersion)?.detectedVersion;return{framework,detectedVersion}}__name(matches,"matches");function removeSupersededFramework(matches2,slug){let index2=matches2.findIndex(f=>f?.slug===slug),framework=matches2[index2];if(framework){if(framework.supersedes)for(let slug2 of framework.supersedes)removeSupersededFramework(matches2,slug2);matches2.splice(index2,1)}}__name(removeSupersededFramework,"removeSupersededFramework");function removeSupersededFrameworks(matches2){for(let match of matches2.slice())if(match?.supersedes)for(let slug of match.supersedes)removeSupersededFramework(matches2,slug)}__name(removeSupersededFrameworks,"removeSupersededFrameworks");async function detectFramework({fs:fs49,frameworkList,useExperimentalFrameworks}){let filteredList=filterFrameworkList(frameworkList,useExperimentalFrameworks),result=await Promise.all(filteredList.map(async frameworkMatch=>await matches(fs49,frameworkMatch)?frameworkMatch:null));return removeSupersededFrameworks(result),result.find(res=>res!==null)?.slug??null}__name(detectFramework,"detectFramework");async function detectFrameworks({fs:fs49,frameworkList,useExperimentalFrameworks}){let filteredList=filterFrameworkList(frameworkList,useExperimentalFrameworks),result=await Promise.all(filteredList.map(async frameworkMatch=>await matches(fs49,frameworkMatch)?frameworkMatch:null));return removeSupersededFrameworks(result),result.filter(res=>res!==null)}__name(detectFrameworks,"detectFrameworks");async function detectFrameworkRecord2({fs:fs49,frameworkList,useExperimentalFrameworks}){let filteredList=filterFrameworkList(frameworkList,useExperimentalFrameworks),result=await Promise.all(filteredList.map(async frameworkMatch=>{let matchResult=await matches(fs49,frameworkMatch);return matchResult?{...frameworkMatch,detectedVersion:matchResult?.detectedVersion}:null}));return removeSupersededFrameworks(result),result.find(res=>res!==null)??null}__name(detectFrameworkRecord2,"detectFrameworkRecord");function detectFrameworkVersion(frameworkRecord){let firstMatchPackage=[...frameworkRecord.detectors?.every||[],...frameworkRecord.detectors?.some||[]].find(d3=>d3.matchPackage);if(firstMatchPackage?.matchPackage)return lookupInstalledVersion(process.execPath,firstMatchPackage.matchPackage)}__name(detectFrameworkVersion,"detectFrameworkVersion");function lookupInstalledVersion(cwd,packageName){try{let script=`require('${packageName}/package.json').version`;return(0,import_child_process.spawnSync)(cwd,["-p",script],{encoding:"utf-8"}).stdout.trim()}catch(error){console.debug(`Error looking up version of installed package "${packageName}": ${error}`)}}__name(lookupInstalledVersion,"lookupInstalledVersion")}});var require_filesystem=__commonJS({"../../node_modules/.pnpm/@vercel+fs-detectors@6.15.3/node_modules/@vercel/fs-detectors/dist/detectors/filesystem.js"(exports2,module2){"use strict";var __defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),filesystem_exports={};__export2(filesystem_exports,{DetectorFilesystem:__name(()=>DetectorFilesystem,"DetectorFilesystem")});module2.exports=__toCommonJS2(filesystem_exports);var import_path3=__require("path"),DetectorFilesystem=class{static{__name(this,"DetectorFilesystem")}constructor(){this.hasPath=async path50=>{let p2=this.pathCache.get(path50);return p2||(p2=this._hasPath(path50),this.pathCache.set(path50,p2)),p2},this.isFile=async name=>{let p2=this.fileCache.get(name);return p2||(p2=this._isFile(name),this.fileCache.set(name,p2)),p2},this.readFile=async name=>{let p2=this.readFileCache.get(name);return p2||(p2=this._readFile(name),this.readFileCache.set(name,p2)),p2},this.readdir=async(dirPath,options)=>{let p2=this.readdirCache.get(dirPath);p2||(p2=this._readdir(dirPath),this.readdirCache.set(dirPath,p2));let directoryContent=await p2,directoryFiles=new Set;for(let file of directoryContent)file.type==="file"&&(this.fileCache.set(file.path,Promise.resolve(!0)),this.pathCache.set(file.path,Promise.resolve(!0)),directoryFiles.add(file.name));if(options?.potentialFiles){let filesThatDoNotExist=options.potentialFiles.filter(path50=>(0,import_path3.basename)(path50)===path50).filter(path50=>!directoryFiles.has(path50));for(let filePath of filesThatDoNotExist){let fullFilePath=dirPath==="/"?filePath:import_path3.posix.join(dirPath,filePath);this.fileCache.set(fullFilePath,Promise.resolve(!1)),this.pathCache.set(fullFilePath,Promise.resolve(!1))}}return p2},this.chdir=name=>this._chdir(name),this.writeFile=async(name,content2)=>{this.readFileCache.set(name,Promise.resolve(Buffer.from(content2))),this.fileCache.set(name,Promise.resolve(!0)),this.pathCache.set(name,Promise.resolve(!0))},this.pathCache=new Map,this.fileCache=new Map,this.readFileCache=new Map,this.readdirCache=new Map}}}});var require_local_file_system_detector=__commonJS({"../../node_modules/.pnpm/@vercel+fs-detectors@6.15.3/node_modules/@vercel/fs-detectors/dist/detectors/local-file-system-detector.js"(exports2,module2){"use strict";var __create2=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf2=Object.getPrototypeOf,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toESM2=__name((mod,isNodeMode,target)=>(target=mod!=null?__create2(__getProtoOf2(mod)):{},__copyProps2(isNodeMode||!mod||!mod.__esModule?__defProp2(target,"default",{value:mod,enumerable:!0}):target,mod)),"__toESM"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),local_file_system_detector_exports={};__export2(local_file_system_detector_exports,{LocalFileSystemDetector:__name(()=>LocalFileSystemDetector2,"LocalFileSystemDetector")});module2.exports=__toCommonJS2(local_file_system_detector_exports);var import_promises9=__toESM2(__require("fs/promises")),import_path3=__require("path"),import_filesystem=require_filesystem(),import_error_utils=require_dist2(),LocalFileSystemDetector2=class _LocalFileSystemDetector extends import_filesystem.DetectorFilesystem{static{__name(this,"LocalFileSystemDetector")}constructor(rootPath){super(),this.rootPath=rootPath}async _hasPath(name){try{return await import_promises9.default.stat(this.getFilePath(name)),!0}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")return!1;throw err}}_readFile(name){return import_promises9.default.readFile(this.getFilePath(name))}async _isFile(name){return(await import_promises9.default.stat(this.getFilePath(name))).isFile()}async _readdir(dir){let dirPath=this.getFilePath(dir),entries2=await import_promises9.default.readdir(dirPath,{withFileTypes:!0}),result=[];for(let entry of entries2){let type;if(entry.isFile())type="file";else if(entry.isDirectory())type="dir";else continue;result.push({name:entry.name,path:(0,import_path3.join)(this.getRelativeFilePath(dir),entry.name),type})}return result}_chdir(name){return new _LocalFileSystemDetector(this.getFilePath(name))}getRelativeFilePath(name){return name.startsWith(this.rootPath)?(0,import_path3.relative)(this.rootPath,name):name}getFilePath(name){return(0,import_path3.join)(this.rootPath,this.getRelativeFilePath(name))}}}});function split(value){let result=value.trim();result=result.replace(SPLIT_LOWER_UPPER_RE,SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE,SPLIT_REPLACE_VALUE),result=result.replace(DEFAULT_STRIP_REGEXP,"\0");let start=0,end2=result.length;for(;result.charAt(start)==="\0";)start++;if(start===end2)return[];for(;result.charAt(end2-1)==="\0";)end2--;return result.slice(start,end2).split(/\0/g)}function splitSeparateNumbers(value){let words=split(value);for(let i=0;i<words.length;i++){let word=words[i],match=SPLIT_SEPARATE_NUMBER_RE.exec(word);if(match){let offset=match.index+(match[1]??match[2]).length;words.splice(i,1,word.slice(0,offset),word.slice(offset))}}return words}function camelCase(input,options){let[prefix,words,suffix]=splitPrefixSuffix(input,options),lower=lowerFactory(options?.locale),upper=upperFactory(options?.locale),transform=options?.mergeAmbiguousCharacters?capitalCaseTransformFactory(lower,upper):pascalCaseTransformFactory(lower,upper);return prefix+words.map((word,index2)=>index2===0?lower(word):transform(word,index2)).join(options?.delimiter??"")+suffix}function pascalCase(input,options){let[prefix,words,suffix]=splitPrefixSuffix(input,options),lower=lowerFactory(options?.locale),upper=upperFactory(options?.locale),transform=options?.mergeAmbiguousCharacters?capitalCaseTransformFactory(lower,upper):pascalCaseTransformFactory(lower,upper);return prefix+words.map(transform).join(options?.delimiter??"")+suffix}function lowerFactory(locale){return locale===!1?input=>input.toLowerCase():input=>input.toLocaleLowerCase(locale)}function upperFactory(locale){return locale===!1?input=>input.toUpperCase():input=>input.toLocaleUpperCase(locale)}function capitalCaseTransformFactory(lower,upper){return word=>`${upper(word[0])}${lower(word.slice(1))}`}function pascalCaseTransformFactory(lower,upper){return(word,index2)=>{let char0=word[0];return(index2>0&&char0>="0"&&char0<="9"?"_"+char0:upper(char0))+lower(word.slice(1))}}function splitPrefixSuffix(input,options={}){let splitFn=options.split??(options.separateNumbers?splitSeparateNumbers:split),prefixCharacters=options.prefixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,suffixCharacters=options.suffixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,prefixIndex=0,suffixIndex=input.length;for(;prefixIndex<input.length;){let char=input.charAt(prefixIndex);if(!prefixCharacters.includes(char))break;prefixIndex++}for(;suffixIndex>prefixIndex;){let index2=suffixIndex-1,char=input.charAt(index2);if(!suffixCharacters.includes(char))break;suffixIndex=index2}return[input.slice(0,prefixIndex),splitFn(input.slice(prefixIndex,suffixIndex)),input.slice(suffixIndex)]}var SPLIT_LOWER_UPPER_RE,SPLIT_UPPER_UPPER_RE,SPLIT_SEPARATE_NUMBER_RE,DEFAULT_STRIP_REGEXP,SPLIT_REPLACE_VALUE,DEFAULT_PREFIX_SUFFIX_CHARACTERS,init_dist7=__esm({"../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js"(){SPLIT_LOWER_UPPER_RE=new RegExp("([\\p{Ll}\\d])(\\p{Lu})","gu"),SPLIT_UPPER_UPPER_RE=new RegExp("(\\p{Lu})([\\p{Lu}][\\p{Ll}])","gu"),SPLIT_SEPARATE_NUMBER_RE=new RegExp("(\\d)\\p{Ll}|(\\p{L})\\d","u"),DEFAULT_STRIP_REGEXP=/[^\p{L}\d]+/giu,SPLIT_REPLACE_VALUE="$1\0$2",DEFAULT_PREFIX_SUFFIX_CHARACTERS="";__name(split,"split");__name(splitSeparateNumbers,"splitSeparateNumbers");__name(camelCase,"camelCase");__name(pascalCase,"pascalCase");__name(lowerFactory,"lowerFactory");__name(upperFactory,"upperFactory");__name(capitalCaseTransformFactory,"capitalCaseTransformFactory");__name(pascalCaseTransformFactory,"pascalCaseTransformFactory");__name(splitPrefixSuffix,"splitPrefixSuffix")}});import*as path21 from"node:path";import*as fs18 from"node:fs";function ParseErr(message,str,indx){let whitespace2=str.slice(0,indx).split(/\n/),lineNo=whitespace2.length,colNo=whitespace2[lineNo-1].length+1;throw message+=" at line "+lineNo+" col "+colNo+`:
|
|
318
|
+
`:str}var BARE_KEY,init_stringify=__esm({"../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/stringify.js"(){BARE_KEY=/^[a-z0-9-_]+$/i;__name(extendedTypeOf,"extendedTypeOf");__name(isArrayOfTables,"isArrayOfTables");__name(formatString,"formatString");__name(stringifyValue,"stringifyValue");__name(stringifyInlineTable,"stringifyInlineTable");__name(stringifyArray,"stringifyArray");__name(stringifyArrayTable,"stringifyArrayTable");__name(stringifyTable,"stringifyTable");__name(stringify2,"stringify")}});var dist_exports3={};__export(dist_exports3,{TomlDate:()=>TomlDate,TomlError:()=>TomlError2,default:()=>dist_default3,parse:()=>parse4,stringify:()=>stringify2});var dist_default3,init_dist6=__esm({"../../node_modules/.pnpm/smol-toml@1.5.2/node_modules/smol-toml/dist/index.js"(){init_parse();init_stringify();init_date();init_error();dist_default3={parse:parse4,stringify:stringify2,TomlDate,TomlError:TomlError2}}});var require_dist2=__commonJS({"../../node_modules/.pnpm/@vercel+error-utils@2.2.1/node_modules/@vercel/error-utils/dist/index.js"(exports2,module2){"use strict";var __create2=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf2=Object.getPrototypeOf,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toESM2=__name((mod,isNodeMode,target)=>(target=mod!=null?__create2(__getProtoOf2(mod)):{},__copyProps2(isNodeMode||!mod||!mod.__esModule?__defProp2(target,"default",{value:mod,enumerable:!0}):target,mod)),"__toESM"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),src_exports={};__export2(src_exports,{errorToString:__name(()=>errorToString,"errorToString"),errorToStringFriendly:__name(()=>errorToStringFriendly,"errorToStringFriendly"),getSystemErrorMessage:__name(()=>getSystemErrorMessage,"getSystemErrorMessage"),isErrnoException:__name(()=>isErrnoException,"isErrnoException"),isError:__name(()=>isError,"isError"),isErrorLike:__name(()=>isErrorLike,"isErrorLike"),isObject:__name(()=>isObject2,"isObject"),isSpawnError:__name(()=>isSpawnError,"isSpawnError"),normalizeError:__name(()=>normalizeError,"normalizeError")});module2.exports=__toCommonJS2(src_exports);var import_node_util12=__toESM2(__require("node:util")),isObject2=__name(obj=>typeof obj=="object"&&obj!==null,"isObject"),isError=__name(error=>import_node_util12.default.types.isNativeError(error),"isError"),isErrnoException=__name(error=>isError(error)&&"code"in error,"isErrnoException"),nativeGetSystemErrorMessage=import_node_util12.default.getSystemErrorMessage,getSystemErrorMessageFallback=__name(errno=>import_node_util12.default.getSystemErrorMap().get(errno)?.[1]??`Unknown system error ${errno}`,"getSystemErrorMessageFallback"),isErrorLike=__name(error=>isObject2(error)&&"message"in error,"isErrorLike"),errorToString=__name((error,fallback)=>isError(error)||isErrorLike(error)?error.message:typeof error=="string"?error:fallback??"An unknown error has ocurred.","errorToString"),getSystemErrorMessage=nativeGetSystemErrorMessage??getSystemErrorMessageFallback,errorToStringFriendly=__name((error,fallback)=>isErrnoException(error)&&typeof error.errno=="number"?getSystemErrorMessage(error.errno):errorToString(error,fallback),"errorToStringFriendly"),normalizeError=__name(error=>{if(isError(error))return error;let errorMessage5=errorToString(error);return isErrorLike(error)?Object.assign(new Error(errorMessage5),error):new Error(errorMessage5)},"normalizeError");function isSpawnError(v){return isErrnoException(v)&&"spawnargs"in v}__name(isSpawnError,"isSpawnError")}});var require_read_config_file=__commonJS({"../../node_modules/.pnpm/@vercel+frameworks@3.30.9/node_modules/@vercel/frameworks/dist/read-config-file.js"(exports2,module2){"use strict";var __create2=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf2=Object.getPrototypeOf,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toESM2=__name((mod,isNodeMode,target)=>(target=mod!=null?__create2(__getProtoOf2(mod)):{},__copyProps2(isNodeMode||!mod||!mod.__esModule?__defProp2(target,"default",{value:mod,enumerable:!0}):target,mod)),"__toESM"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),read_config_file_exports={};__export2(read_config_file_exports,{readConfigFile:__name(()=>readConfigFile,"readConfigFile")});module2.exports=__toCommonJS2(read_config_file_exports);var import_js_yaml=__toESM2(require_js_yaml2()),import_smol_toml=(init_dist6(),__toCommonJS(dist_exports3)),import_fs3=__require("fs"),import_error_utils=require_dist2(),{readFile:readFile6}=import_fs3.promises;async function readFileOrNull2(file){try{return await readFile6(file)}catch(error){if(!(0,import_error_utils.isErrnoException)(error)||error.code!=="ENOENT")throw error}return null}__name(readFileOrNull2,"readFileOrNull");async function readConfigFile(files){files=Array.isArray(files)?files:[files];for(let name of files){let data2=await readFileOrNull2(name);if(data2){let str=data2.toString("utf8");if(name.endsWith(".json"))return JSON.parse(str);if(name.endsWith(".toml"))return(0,import_smol_toml.parse)(str);if(name.endsWith(".yaml")||name.endsWith(".yml"))return import_js_yaml.default.safeLoad(str,{filename:name})}}return null}__name(readConfigFile,"readConfigFile")}});var require_types=__commonJS({"../../node_modules/.pnpm/@vercel+frameworks@3.30.9/node_modules/@vercel/frameworks/dist/types.js"(exports2,module2){"use strict";var __defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__hasOwnProp2=Object.prototype.hasOwnProperty,__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),types_exports={};module2.exports=__toCommonJS2(types_exports)}});var require_frameworks=__commonJS({"../../node_modules/.pnpm/@vercel+frameworks@3.30.9/node_modules/@vercel/frameworks/dist/frameworks.js"(exports2,module2){"use strict";var __defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__reExport=__name((target,mod,secondTarget)=>(__copyProps2(target,mod,"default"),secondTarget&&__copyProps2(secondTarget,mod,"default")),"__reExport"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),frameworks_exports={};__export2(frameworks_exports,{default:__name(()=>frameworks_default,"default"),frameworkList:__name(()=>frameworkList,"frameworkList"),frameworks:__name(()=>frameworks2,"frameworks")});module2.exports=__toCommonJS2(frameworks_exports);var import_path3=__require("path"),import_fs3=__require("fs"),import_read_config_file=require_read_config_file();__reExport(frameworks_exports,require_types(),module2.exports);var{readdir:readdir2,readFile:readFile6,unlink}=import_fs3.promises,frameworks2=[{name:"Container",slug:"container",runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/container.svg",tagline:"Deploy any project as a container image built from a Dockerfile.",description:"A project deployed as a container image, built from a Dockerfile.vercel or Containerfile.vercel.",website:"https://docs.docker.com/reference/dockerfile/",useRuntime:{src:"<detect>",use:"@vercel/container"},detectors:{some:[{path:"Dockerfile.vercel"},{path:"Containerfile.vercel"}]},settings:{installCommand:{placeholder:"None",value:null},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{placeholder:"None"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Blitz.js (Legacy)",slug:"blitzjs",demo:"https://blitz-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/blitz.svg",tagline:"Blitz.js: The Fullstack React Framework",description:"A brand new Blitz.js app - the result of running `npx blitz@0.45.4 new`.",website:"https://blitzjs.com",envPrefix:"NEXT_PUBLIC_",useRuntime:{src:"package.json",use:"@vercel/next"},detectors:{some:[{path:"blitz.config.js"},{path:"blitz.config.ts"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `blitz build`",value:"blitz build"},devCommand:{value:"blitz start"},outputDirectory:{placeholder:"Next.js default"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Next.js",slug:"nextjs",demo:"https://nextjs-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/next.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/next-dark.svg",screenshot:"https://py8fhxnkzwtsqdo9.public.blob.vercel-storage.com/front/import/nextjs.png",tagline:"Next.js makes you productive with React instantly \u2014 whether you want to build static or dynamic sites.",description:"A Next.js app and a Serverless Function API.",website:"https://nextjs.org",sort:1,envPrefix:"NEXT_PUBLIC_",useRuntime:{src:"package.json",use:"@vercel/next"},detectors:{every:[{matchPackage:"next"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `next build`",value:"next build"},devCommand:{value:"next dev --port $PORT",placeholder:"next"},outputDirectory:{placeholder:"Next.js default"}},recommendedIntegrations:[{id:"oac_5lUsiANun1DEzgLg0NZx5Es3",dependencies:["next-plugin-sentry","next-sentry-source-maps"]}],getOutputDirName:__name(async()=>"public","getOutputDirName"),cachePattern:".next/cache/**"},{name:"Gatsby.js",slug:"gatsby",demo:"https://gatsby.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/gatsby.svg",tagline:"Gatsby helps developers build blazing fast websites and apps with React.",description:"A Gatsby starter app with an API Route.",website:"https://gatsbyjs.org",sort:5,envPrefix:"GATSBY_",detectors:{every:[{matchPackage:"gatsby"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `gatsby build`",value:"gatsby build"},devCommand:{value:"gatsby develop --port $PORT",placeholder:"gatsby develop"},outputDirectory:{value:"public"}},dependency:"gatsby",getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:__name(async dirPrefix=>{try{let nowRoutesPath=(0,import_path3.join)(dirPrefix,"public","__now_routes_g4t5bY.json"),content2=await readFile6(nowRoutesPath,"utf8"),nowRoutes=JSON.parse(content2);try{await unlink(nowRoutesPath)}catch{}return nowRoutes}catch{return[{src:"^/static/(.*)$",headers:{"cache-control":"public,max-age=31536000,immutable"},continue:!0},{src:"^/.*\\.(js|css)$",headers:{"cache-control":"public,max-age=31536000,immutable"},continue:!0},{src:"^/(sw\\.js|app-data\\.json|.*\\.html|page-data/.*)$",headers:{"cache-control":"public,max-age=0,must-revalidate"},continue:!0},{handle:"filesystem"},{src:".*",status:404,dest:"404.html"}]}},"defaultRoutes"),cachePattern:"{.cache,public}/**"},{name:"Remix",slug:"remix",demo:"https://remix-run-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/remix-no-shadow.svg",tagline:"Build Better Websites",description:"A new Remix app \u2014 the result of running `npx create-remix`.",website:"https://remix.run",sort:6,supersedes:["hydrogen","vite","node"],useRuntime:{src:"package.json",use:"@vercel/remix-builder"},ignoreRuntimes:["@vercel/node"],detectors:{some:[{matchPackage:"@remix-run/dev"},{path:"remix.config.js"},{path:"remix.config.mjs"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"remix build",placeholder:"`npm run build` or `remix build`"},devCommand:{value:"remix dev",placeholder:"remix dev"},outputDirectory:{value:"public"}},dependency:"remix",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"React Router",slug:"react-router",demo:"https://react-router-v7-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/react-router.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/react-router-dark.svg",tagline:"Declarative routing for React",description:"A user-obsessed, standards-focused, multi-strategy router you can deploy anywhere.",website:"https://reactrouter.com",sort:7,supersedes:["hydrogen","vite","node"],useRuntime:{src:"package.json",use:"@vercel/remix-builder"},ignoreRuntimes:["@vercel/node"],detectors:{some:[{path:"vite.config.js",matchContent:"@react-router/dev/vite"},{path:"vite.config.ts",matchContent:"@react-router/dev/vite"},{path:"react-router.config.js"},{path:"react-router.config.ts"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"react-router build",placeholder:"`npm run build` or `react-router build`"},devCommand:{value:"react-router dev",placeholder:"react-router dev"},outputDirectory:{value:"build"}},dependency:"react-router",getOutputDirName:__name(async()=>"build","getOutputDirName")},{name:"Astro",slug:"astro",demo:"https://astro-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/astro.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/astro-dark.svg",tagline:"Astro is a new kind of static site builder for the modern web. Powerful developer experience meets lightweight output.",description:"An Astro site, using the basics starter kit.",website:"https://astro.build",envPrefix:"PUBLIC_",detectors:{every:[{matchPackage:"astro"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"astro build",placeholder:"`npm run build` or `astro build`"},devCommand:{value:"astro dev --port $PORT",placeholder:"astro dev"},outputDirectory:{value:"dist"}},dependency:"astro",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{src:"^/assets/(.*)$",headers:{"cache-control":"public, max-age=31536000, immutable"},continue:!0},{src:"^/_astro/(.*)$",headers:{"cache-control":"public, max-age=31536000, immutable"},continue:!0}]},{name:"Hexo",slug:"hexo",demo:"https://hexo-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/hexo.svg",tagline:"Hexo is a fast, simple & powerful blog framework powered by Node.js.",description:"A Hexo site, created with the Hexo CLI.",website:"https://hexo.io",detectors:{every:[{matchPackage:"hexo"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `hexo generate`",value:"hexo generate"},devCommand:{value:"hexo server --port $PORT",placeholder:"hexo server"},outputDirectory:{value:"public"}},dependency:"hexo",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Eleventy",slug:"eleventy",demo:"https://eleventy-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/eleventy.svg",tagline:"11ty is a simpler static site generator written in JavaScript, created to be an alternative to Jekyll.",description:"An Eleventy site, created with npm init.",website:"https://www.11ty.dev",detectors:{every:[{matchPackage:"@11ty/eleventy"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `npx @11ty/eleventy`",value:"npx @11ty/eleventy"},devCommand:{value:"npx @11ty/eleventy --serve --watch --port $PORT",placeholder:"npx @11ty/eleventy --serve"},outputDirectory:{value:"_site"}},dependency:"@11ty/eleventy",getOutputDirName:__name(async()=>"_site","getOutputDirName"),cachePattern:".cache/**"},{name:"Docusaurus (v2+)",slug:"docusaurus-2",demo:"https://docusaurus-2-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/docusaurus.svg",tagline:"Docusaurus makes it easy to maintain Open Source documentation websites.",description:"A static Docusaurus site that makes it easy to maintain OSS documentation.",website:"https://v2.docusaurus.io",detectors:{some:[{matchPackage:"@docusaurus/core"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `docusaurus build`",value:"docusaurus build"},devCommand:{value:"docusaurus start --port $PORT",placeholder:"docusaurus start"},outputDirectory:{value:"build"}},dependency:"@docusaurus/core",getOutputDirName:__name(async dirPrefix=>{let base="build";try{let location=(0,import_path3.join)(dirPrefix,base),content2=await readdir2(location,{withFileTypes:!0});if(content2.length===1&&content2[0].isDirectory())return(0,import_path3.join)(base,content2[0].name)}catch(error){console.error("Error detecting output directory: ",error)}return base},"getOutputDirName"),defaultRoutes:[{src:"^/[^./]+\\.[0-9a-f]{8}\\.(css|js)$",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{src:"^/assets/images/[^/]+-[0-9a-f]{32}\\.(ico|svg|jpg|jpeg|png|gif|webp)$",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{src:"^/assets/medias/[^/]+-[0-9a-f]{32}\\.(ogv|wav|mp3|m4a|aac|oga|flac)$",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{src:"^/assets/files/[^/]+-[0-9a-f]{32}\\.(pdf|doc|docx|xls|xlsx|zip|rar)$",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{src:"^/ideal-img/[^/]+\\.[0-9a-f]{7}\\.\\d+\\.(png|jpe?g|gif)$",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{handle:"filesystem"},{src:".*",status:404,dest:"404.html"}]},{name:"Docusaurus (v1)",slug:"docusaurus",demo:"https://docusaurus-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/docusaurus.svg",tagline:"Docusaurus makes it easy to maintain Open Source documentation websites.",description:"A static Docusaurus site that makes it easy to maintain OSS documentation.",website:"https://docusaurus.io/",detectors:{some:[{matchPackage:"docusaurus"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `docusaurus-build`",value:"docusaurus-build"},devCommand:{value:"docusaurus-start --port $PORT",placeholder:"docusaurus-start"},outputDirectory:{value:"build"}},dependency:"docusaurus",getOutputDirName:__name(async dirPrefix=>{let base="build";try{let location=(0,import_path3.join)(dirPrefix,base),content2=await readdir2(location,{withFileTypes:!0});if(content2.length===1&&content2[0].isDirectory())return(0,import_path3.join)(base,content2[0].name)}catch(error){console.error("Error detecting output directory: ",error)}return base},"getOutputDirName")},{name:"Preact",slug:"preact",demo:"https://preact-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/preact.svg",tagline:"Preact is a fast 3kB alternative to React with the same modern API.",description:"A Preact app, created with the Preact CLI.",website:"https://preactjs.com",detectors:{every:[{matchPackage:"preact-cli"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `preact build`",value:"preact build"},devCommand:{value:"preact watch --port $PORT",placeholder:"preact watch"},outputDirectory:{value:"build"}},dependency:"preact-cli",getOutputDirName:__name(async()=>"build","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"SolidStart (v1)",slug:"solidstart-1",demo:"https://solid-start-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/solid.svg",tagline:"Simple and performant reactivity for building user interfaces.",description:"A Solid app, created with SolidStart.",website:"https://start.solidjs.com",envPrefix:"VITE_",detectors:{every:[{matchPackage:"solid-js"},{matchPackage:"@solidjs/start"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vinxi build`",value:"vinxi build"},devCommand:{value:"vinxi dev"},outputDirectory:{value:".output"}},getOutputDirName:__name(async()=>".output","getOutputDirName")},{name:"SolidStart (v0)",slug:"solidstart",demo:"https://solid-start-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/solid.svg",tagline:"Simple and performant reactivity for building user interfaces.",description:"A Solid app, created with SolidStart.",website:"https://solidjs.com",envPrefix:"VITE_",sort:98,detectors:{every:[{matchPackage:"solid-js"},{matchPackage:"solid-start"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `solid-start build`",value:"solid-start build"},devCommand:{value:"solid-start dev"},outputDirectory:{value:".output"}},getOutputDirName:__name(async()=>".output","getOutputDirName")},{name:"Dojo",slug:"dojo",demo:"https://dojo-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/dojo.svg",tagline:"Dojo is a modern progressive, TypeScript first framework.",description:"A Dojo app, created with the Dojo CLI's cli-create-app command.",website:"https://dojo.io",detectors:{some:[{matchPackage:"@dojo/framework"},{path:".dojorc"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `dojo build`",value:"dojo build"},devCommand:{value:"dojo build -m dev -w -s -p $PORT",placeholder:"dojo build -m dev -w -s"},outputDirectory:{value:"output/dist"}},dependency:"@dojo/cli",getOutputDirName:__name(async()=>(0,import_path3.join)("output","dist"),"getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/service-worker.js",headers:{"cache-control":"s-maxage=0"},continue:!0},{src:"/(.*)",dest:"/index.html"}],defaulHeaders:[{source:"/service-worker.js",regex:"/service-worker.js",headers:{"cache-control":"s-maxage=0"},continue:!0}]},{name:"Ember.js",slug:"ember",demo:"https://ember-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/ember.svg",tagline:"Ember.js helps webapp developers be more productive out of the box.",description:"An Ember app, created with the Ember CLI.",website:"https://emberjs.com/",detectors:{some:[{matchPackage:"ember-source"},{matchPackage:"ember-cli"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `ember build`",value:"ember build"},devCommand:{value:"ember serve --port $PORT",placeholder:"ember serve"},outputDirectory:{value:"dist"}},dependency:"ember-cli",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Vue.js",slug:"vue",demo:"https://vue-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/vue.svg",tagline:"Vue.js is a versatile JavaScript framework that is as approachable as it is performant.",description:"A Vue.js app, created with the Vue CLI.",website:"https://vuejs.org",envPrefix:"VUE_APP_",detectors:{every:[{matchPackage:"@vue/cli-service"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vue-cli-service build`",value:"vue-cli-service build"},devCommand:{value:"vue-cli-service serve --port $PORT",placeholder:"vue-cli-service serve"},outputDirectory:{value:"dist"}},dependency:"@vue/cli-service",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{src:"^/[^/]*\\.(js|txt|ico|json)",headers:{"cache-control":"max-age=300"},continue:!0},{src:"^/(img|js|css|fonts|media)/[^/]+\\.[0-9a-f]{8}\\.*",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{handle:"filesystem"},{src:"^.*",dest:"/index.html"}]},{name:"Scully",slug:"scully",demo:"https://scully-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/scullyio-logo.svg",tagline:"Scully is a static site generator for Angular.",description:"The Static Site Generator for Angular apps.",website:"https://github.com/scullyio/scully",detectors:{every:[{matchPackage:"@scullyio/init"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `ng build && scully`",value:"ng build && scully"},devCommand:{value:"ng serve --port $PORT",placeholder:"ng serve"},outputDirectory:{value:"dist"}},dependency:"@scullyio/init",getOutputDirName:__name(async()=>"dist/static","getOutputDirName")},{name:"Ionic Angular",slug:"ionic-angular",demo:"https://ionic-angular-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/ionic.svg",tagline:"Ionic Angular allows you to build mobile PWAs with Angular and the Ionic Framework.",description:"An Ionic Angular site, created with the Ionic CLI.",website:"https://ionicframework.com",detectors:{every:[{matchPackage:"@ionic/angular"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `ng build`",value:"ng build"},devCommand:{value:"ng serve --port $PORT"},outputDirectory:{value:"www"}},dependency:"@ionic/angular",getOutputDirName:__name(async()=>"www","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Angular",slug:"angular",demo:"https://angular-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/angular.svg",tagline:"Angular is a TypeScript-based cross-platform framework from Google.",description:"An Angular app, created with the Angular CLI.",website:"https://angular.io",detectors:{every:[{matchPackage:"@angular/cli"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `ng build`",value:"ng build"},devCommand:{value:"ng serve --port $PORT",placeholder:"ng serve"},outputDirectory:{value:"dist"}},dependency:"@angular/cli",getOutputDirName:__name(async dirPrefix=>{let base="dist";try{let location=(0,import_path3.join)(dirPrefix,base),content2=await readdir2(location,{withFileTypes:!0});if(content2.length===1&&content2[0].isDirectory()){let potentialOutDir=(0,import_path3.join)(base,content2[0].name),potentialOutDirWithBrowser=(0,import_path3.join)(potentialOutDir,"browser");return(0,import_fs3.existsSync)(potentialOutDirWithBrowser)?potentialOutDirWithBrowser:potentialOutDir}}catch(error){console.error("Error detecting output directory: ",error)}return base},"getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Polymer",slug:"polymer",demo:"https://polymer-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/polymer.svg",tagline:"Polymer is an open-source webapps library from Google, for building using Web Components.",description:"A Polymer app, created with the Polymer CLI.",website:"https://www.polymer-project.org/",detectors:{every:[{matchPackage:"polymer-cli"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `polymer build`",value:"polymer build"},devCommand:{value:"polymer serve --port $PORT",placeholder:"polymer serve"},outputDirectory:{value:"build"}},dependency:"polymer-cli",getOutputDirName:__name(async dirPrefix=>{let base="build";try{let location=(0,import_path3.join)(dirPrefix,base),paths=(await readdir2(location)).filter(item=>!item.includes("."));return(0,import_path3.join)(base,paths[0])}catch(error){console.error("Error detecting output directory: ",error)}return base},"getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Svelte",slug:"svelte",demo:"https://svelte.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/svelte.svg",tagline:"Svelte lets you write high performance reactive apps with significantly less boilerplate.",description:"A basic Svelte app using the default template.",website:"https://svelte.dev",sort:3,detectors:{every:[{matchPackage:"svelte"},{matchPackage:"sirv-cli"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `rollup -c`",value:"rollup -c"},devCommand:{value:"rollup -c -w"},outputDirectory:{value:"public"}},dependency:"sirv-cli",getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"SvelteKit (v0)",slug:"sveltekit",demo:"https://sveltekit-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/svelte.svg",screenshot:"https://py8fhxnkzwtsqdo9.public.blob.vercel-storage.com/front/import/sveltekit.png",tagline:"SvelteKit is a framework for building web applications of all sizes.",description:"A SvelteKit legacy app optimized Edge-first.",website:"https://kit.svelte.dev",supersedes:["vite"],sort:99,envPrefix:"VITE_",detectors:{every:[{path:"package.json",matchContent:'"(dev)?(d|D)ependencies":\\s*{[^}]*"@sveltejs\\/kit":\\s*"1\\.0\\.0-next\\.(\\d+)"[^}]*}'}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `svelte-kit build`",value:"svelte-kit build"},devCommand:{value:"svelte-kit dev --port $PORT",placeholder:"svelte-kit dev"},outputDirectory:{value:"public"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"SvelteKit",slug:"sveltekit-1",demo:"https://sveltekit-1-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/svelte.svg",screenshot:"https://py8fhxnkzwtsqdo9.public.blob.vercel-storage.com/front/import/sveltekit.png",tagline:"SvelteKit is a framework for building web applications of all sizes.",description:"A SvelteKit app optimized Edge-first.",website:"https://kit.svelte.dev",supersedes:["vite"],detectors:{every:[{path:"package.json",matchContent:'"(dev)?(d|D)ependencies":\\s*{[^}]*"@sveltejs\\/kit":\\s*".+?"[^}]*}'}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"vite build",value:"vite build"},devCommand:{placeholder:"vite dev",value:"vite dev --port $PORT"},outputDirectory:{value:"public"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Ionic React",slug:"ionic-react",demo:"https://ionic-react-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/ionic.svg",tagline:"Ionic React allows you to build mobile PWAs with React and the Ionic Framework.",description:"An Ionic React site, created with the Ionic CLI.",website:"https://ionicframework.com",detectors:{every:[{matchPackage:"@ionic/react"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `react-scripts build`",value:"react-scripts build"},devCommand:{value:"react-scripts start"},outputDirectory:{value:"build"}},dependency:"@ionic/react",getOutputDirName:__name(async()=>"build","getOutputDirName"),defaultRoutes:[{src:"/static/(.*)",headers:{"cache-control":"s-maxage=31536000, immutable"},continue:!0},{src:"/service-worker.js",headers:{"cache-control":"s-maxage=0"},continue:!0},{src:"/sockjs-node/(.*)",dest:"/sockjs-node/$1"},{handle:"filesystem"},{src:"/static/(.*)",status:404,dest:"/404.html"},{src:"/(.*)",headers:{"cache-control":"s-maxage=0"},dest:"/index.html"}]},{name:"Create React App",slug:"create-react-app",demo:"https://create-react-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/react.svg",tagline:"Create React App allows you to get going with React in no time.",description:"A client-side React app created with create-react-app.",website:"https://create-react-app.dev",sort:4,envPrefix:"REACT_APP_",detectors:{some:[{matchPackage:"react-scripts"},{matchPackage:"react-dev-utils"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `react-scripts build`",value:"react-scripts build"},devCommand:{value:"react-scripts start"},outputDirectory:{value:"build"}},dependency:"react-scripts",getOutputDirName:__name(async()=>"build","getOutputDirName"),defaultRoutes:[{src:"/static/(.*)",headers:{"cache-control":"s-maxage=31536000, immutable"},continue:!0},{src:"/service-worker.js",headers:{"cache-control":"s-maxage=0"},continue:!0},{src:"/sockjs-node/(.*)",dest:"/sockjs-node/$1"},{handle:"filesystem"},{src:"/static/(.*)",status:404,dest:"/404.html"},{src:"/(.*)",headers:{"cache-control":"s-maxage=0"},dest:"/index.html"}]},{name:"Gridsome",slug:"gridsome",demo:"https://gridsome-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/gridsome.svg",tagline:"Gridsome is a Vue.js-powered framework for building websites & apps that are fast by default.",description:"A Gridsome app, created with the Gridsome CLI.",website:"https://gridsome.org/",detectors:{every:[{matchPackage:"gridsome"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `gridsome build`",value:"gridsome build"},devCommand:{value:"gridsome develop -p $PORT",placeholder:"gridsome develop"},outputDirectory:{value:"dist"}},dependency:"gridsome",getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"UmiJS",slug:"umijs",demo:"https://umijs-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/umi.svg",tagline:"UmiJS is an extensible enterprise-level React application framework.",description:"An UmiJS app, created using the Umi CLI.",website:"https://umijs.org",detectors:{every:[{matchPackage:"umi"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `umi build`",value:"umi build"},devCommand:{value:"umi dev --port $PORT",placeholder:"umi dev"},outputDirectory:{value:"dist"}},dependency:"umi",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Sapper",slug:"sapper",demo:"https://sapper-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/svelte.svg",tagline:"Sapper is a framework for building high-performance universal web apps with Svelte.",description:"A Sapper app, using the Sapper template.",website:"https://sapper.svelte.dev",detectors:{every:[{matchPackage:"sapper"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `sapper export`",value:"sapper export"},devCommand:{value:"sapper dev --port $PORT",placeholder:"sapper dev"},outputDirectory:{value:"__sapper__/export"}},dependency:"sapper",getOutputDirName:__name(async()=>"__sapper__/export","getOutputDirName")},{name:"Saber",slug:"saber",logo:"https://api-frameworks.vercel.sh/framework-logos/saber.svg",tagline:"Saber is a framework for building static sites in Vue.js that supports data from any source.",description:"A Saber site, created with npm init.",website:"https://saber.egoist.dev",detectors:{every:[{matchPackage:"saber"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `saber build`",value:"saber build"},devCommand:{value:"saber --port $PORT",placeholder:"saber"},outputDirectory:{value:"public"}},dependency:"saber",getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{src:"/_saber/.*",headers:{"cache-control":"max-age=31536000, immutable"}},{handle:"filesystem"},{src:".*",status:404,dest:"404.html"}]},{name:"Stencil",slug:"stencil",demo:"https://stencil.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/stencil.svg",tagline:"Stencil is a powerful toolchain for building Progressive Web Apps and Design Systems.",description:"A Stencil site, created with the Stencil CLI.",website:"https://stenciljs.com/",detectors:{every:[{matchPackage:"@stencil/core"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `stencil build`",value:"stencil build"},devCommand:{value:"stencil build --dev --watch --serve --port $PORT",placeholder:"stencil build --dev --watch --serve"},outputDirectory:{value:"www"}},dependency:"@stencil/core",getOutputDirName:__name(async()=>"www","getOutputDirName"),defaultRoutes:[{src:"/assets/(.*)",headers:{"cache-control":"max-age=2592000"},continue:!0},{src:"/build/p-.*",headers:{"cache-control":"max-age=31536000, immutable"},continue:!0},{src:"/sw.js",headers:{"cache-control":"no-cache"},continue:!0},{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Nuxt",slug:"nuxtjs",demo:"https://nuxtjs-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/nuxt.svg",screenshot:"https://py8fhxnkzwtsqdo9.public.blob.vercel-storage.com/front/import/nuxtjs.png",tagline:"Nuxt is the open source framework that makes full-stack development with Vue.js intuitive.",description:"A Nuxt app, bootstrapped with create-nuxt-app.",website:"https://nuxt.com",sort:2,envPrefix:"NUXT_ENV_",supersedes:["nitro"],detectors:{some:[{matchPackage:"nuxt"},{matchPackage:"nuxt3"},{matchPackage:"nuxt-edge"},{matchPackage:"nuxt-nightly"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `nuxt build`",value:"nuxt build"},devCommand:{value:"nuxt dev"},outputDirectory:{value:"dist"}},dependency:"nuxt",getOutputDirName:__name(async()=>"dist","getOutputDirName"),cachePattern:".nuxt/**",defaultRoutes:[{src:"/sw.js",headers:{"cache-control":"no-cache"},continue:!0},{src:"/_nuxt/(.*)",headers:{"cache-control":"public,max-age=31536000,immutable"},continue:!0},{handle:"filesystem"},{src:"/(.*)",dest:"/200.html"}]},{name:"RedwoodJS",slug:"redwoodjs",demo:"https://redwood-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/redwoodjs.svg",tagline:"RedwoodJS is a full-stack framework for the Jamstack.",description:"A RedwoodJS app, bootstraped with create-redwood-app.",website:"https://redwoodjs.com",envPrefix:"REDWOOD_ENV_",useRuntime:{src:"package.json",use:"@vercel/redwood"},ignoreRuntimes:["@vercel/node"],detectors:{every:[{matchPackage:"@redwoodjs/core"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"yarn rw deploy vercel"},devCommand:{value:'yarn rw dev --fwd="--port=$PORT --open=false"',placeholder:"yarn rw dev"},outputDirectory:{placeholder:"RedwoodJS default"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Hugo",slug:"hugo",demo:"https://hugo-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/hugo.svg",tagline:"Hugo is the world\u2019s fastest framework for building websites, written in Go.",description:"A Hugo site, created with the Hugo CLI.",website:"https://gohugo.io",detectors:{some:[{path:"config.yaml",matchContent:"baseURL"},{path:"config.toml",matchContent:"baseURL"},{path:"config.json",matchContent:"baseURL"}]},settings:{installCommand:{placeholder:"None"},buildCommand:{placeholder:"`npm run build` or `hugo --gc`",value:"hugo --gc"},devCommand:{value:"hugo server -D -w -p $PORT",placeholder:"hugo server -D"},outputDirectory:{placeholder:"`public` or `publishDir` from the `config` file"}},getOutputDirName:__name(async dirPrefix=>{let config=await(0,import_read_config_file.readConfigFile)(["config.json","config.yaml","config.toml"].map(fileName=>(0,import_path3.join)(dirPrefix,fileName)));return config&&config.publishDir||"public"},"getOutputDirName"),defaultVersion:"0.58.2"},{name:"Jekyll",slug:"jekyll",demo:"https://jekyll-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/jekyll.svg",tagline:"Jekyll makes it super easy to transform your plain text into static websites and blogs.",description:"A Jekyll site, created with the Jekyll CLI.",website:"https://jekyllrb.com/",detectors:{every:[{path:"_config.yml"}]},settings:{installCommand:{value:"bundle install"},buildCommand:{placeholder:"`npm run build` or `jekyll build`",value:"jekyll build"},devCommand:{value:"bundle exec jekyll serve --watch --port $PORT",placeholder:"bundle exec jekyll serve"},outputDirectory:{placeholder:"`_site` or `destination` from `_config.yml`"}},getOutputDirName:__name(async dirPrefix=>{let config=await(0,import_read_config_file.readConfigFile)((0,import_path3.join)(dirPrefix,"_config.yml"));return config&&config.destination||"_site"},"getOutputDirName"),cachePattern:"{vendor/bin,vendor/cache,vendor/bundle}/**"},{name:"Brunch",slug:"brunch",demo:"https://brunch-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/brunch.svg",tagline:"Brunch is a fast and simple webapp build tool with seamless incremental compilation for rapid development.",description:"A Brunch app, created with the Brunch CLI.",website:"https://brunch.io/",detectors:{some:[{matchPackage:"brunch"},{path:"brunch-config.js"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `brunch build --production`",value:"brunch build --production"},devCommand:{value:"brunch watch --server --port $PORT",placeholder:"brunch watch --server"},outputDirectory:{value:"public"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Middleman",slug:"middleman",demo:"https://middleman-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/middleman.svg",tagline:"Middleman is a static site generator that uses all the shortcuts and tools in modern web development.",description:"A Middleman app, created with the Middleman CLI.",website:"https://middlemanapp.com/",detectors:{every:[{path:"config.rb"}]},settings:{installCommand:{value:"bundle install"},buildCommand:{placeholder:"`npm run build` or `bundle exec middleman build`",value:"bundle exec middleman build"},devCommand:{placeholder:"bundle exec middleman server",value:"bundle exec middleman server -p $PORT"},outputDirectory:{value:"build"}},getOutputDirName:__name(async()=>"build","getOutputDirName"),cachePattern:"{vendor/bin,vendor/cache,vendor/bundle}/**"},{name:"Zola",slug:"zola",demo:"https://zola-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/zola.svg",tagline:"Everything you need to make a static site engine in one binary.",description:'A Zola app, created with the "Getting Started" tutorial.',website:"https://www.getzola.org",detectors:{every:[{path:"config.toml",matchContent:"base_url"}]},settings:{installCommand:{placeholder:"None"},buildCommand:{value:"zola build"},devCommand:{placeholder:"zola serve",value:"zola serve --port $PORT"},outputDirectory:{value:"public"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultVersion:"0.13.0"},{name:"Hydrogen (v1)",slug:"hydrogen",demo:"https://hydrogen-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/hydrogen.svg",tagline:"React framework for headless commerce",description:"React framework for headless commerce",website:"https://hydrogen.shopify.dev",supersedes:["vite"],useRuntime:{src:"package.json",use:"@vercel/hydrogen"},envPrefix:"PUBLIC_",detectors:{some:[{matchPackage:"@shopify/hydrogen"},{path:"hydrogen.config.js"},{path:"hydrogen.config.ts"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"shopify hydrogen build",placeholder:"`npm run build` or `shopify hydrogen build`"},devCommand:{value:"shopify hydrogen dev",placeholder:"shopify hydrogen dev"},outputDirectory:{value:"dist"}},dependency:"@shopify/hydrogen",getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"Vite",slug:"vite",demo:"https://vite-vue-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/vite.svg",tagline:"Vite is a new breed of frontend build tool that significantly improves the frontend development experience.",description:"A Vue.js app, created with Vite.",website:"https://vitejs.dev",supersedes:["ionic-react"],envPrefix:"VITE_",detectors:{every:[{matchPackage:"vite"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vite build`",value:"vite build"},devCommand:{placeholder:"vite",value:"vite --port $PORT"},outputDirectory:{value:"dist"}},dependency:"vite",getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"TanStack Start",slug:"tanstack-start",logo:"https://api-frameworks.vercel.sh/framework-logos/tanstack-start.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/tanstack-start-dark.svg",tagline:"Full-stack Framework powered by TanStack Router for React and Solid.",description:"Full-document SSR, Streaming, Server Functions, bundling and more, powered by TanStack Router and Vite - Ready to deploy to your favorite hosting provider.",website:"https://tanstack.com/start",supersedes:["ionic-react","vite"],detectors:{every:[{matchPackage:"@tanstack/router-plugin"}],some:[{matchPackage:"@tanstack/react-start"},{matchPackage:"@tanstack/solid-start"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vite build`",value:"vite build"},devCommand:{placeholder:"vite",value:"vite --port $PORT"},outputDirectory:{value:"dist"}},getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"TanStack Start",slug:"tanstack-start-lovable",logo:"https://api-frameworks.vercel.sh/framework-logos/tanstack-start.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/tanstack-start-dark.svg",platform:{name:"lovable",logo:"https://api-frameworks.vercel.sh/framework-logos/lovable.svg"},tagline:"Full-stack Framework powered by TanStack Router imported from Lovable",description:"Full-document SSR, Streaming, Server Functions, bundling and more, imported from Lovable",website:"https://lovable.dev/",supersedes:["tanstack-start","ionic-react","vite"],detectors:{every:[{matchPackage:"@lovable.dev/vite-tanstack-config"}],some:[{matchPackage:"@tanstack/react-start"},{matchPackage:"@tanstack/solid-start"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vite build`",value:"vite build"},devCommand:{placeholder:"vite",value:"vite --port $PORT"},outputDirectory:{value:"dist"}},getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"VitePress",slug:"vitepress",demo:"https://vitepress-starter-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/vite.svg",tagline:"VitePress is VuePress' little brother, built on top of Vite.",description:"VuePress on top of Vite",website:"https://vitepress.vuejs.org/",detectors:{every:[{matchPackage:"vitepress"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vitepress build docs`",value:"vitepress build docs"},devCommand:{value:"vitepress dev docs --port $PORT"},outputDirectory:{value:"docs/.vitepress/dist"}},getOutputDirName:__name(async()=>"docs/.vitepress/dist","getOutputDirName")},{name:"VuePress",slug:"vuepress",demo:"https://vuepress-starter-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/vuepress.svg",tagline:"Vue-powered Static Site Generator",description:"Vue-powered Static Site Generator",website:"https://vuepress.vuejs.org/",detectors:{every:[{matchPackage:"vuepress"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `vuepress build src`",value:"vuepress build src"},devCommand:{value:"vuepress dev src --port $PORT"},outputDirectory:{value:"src/.vuepress/dist"}},getOutputDirName:__name(async()=>"src/.vuepress/dist","getOutputDirName")},{name:"Parcel",slug:"parcel",demo:"https://parcel-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/parcel.svg",tagline:"Parcel is a zero configuration build tool for the web that scales to projects of any size and complexity.",description:"A vanilla web app built with Parcel.",website:"https://parceljs.org",detectors:{every:[{matchPackage:"parcel"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `parcel build`",value:"parcel build"},devCommand:{placeholder:"parcel",value:"parcel"},outputDirectory:{value:"dist"}},dependency:"parcel",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{src:"^/[^./]+\\.[0-9a-f]{8}\\.(css|js|png|jpg|webp|avif|svg)$",headers:{"cache-control":"s-maxage=31536000, immutable"},continue:!0},{handle:"filesystem"}]},{name:"FastAPI",slug:"fastapi",demo:"https://vercel-fastapi-gamma-smoky.vercel.app/",logo:"https://api-frameworks.vercel.sh/framework-logos/fastapi.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/fastapi.svg",tagline:"FastAPI framework, high performance, easy to learn, fast to code, ready for production",description:"FastAPI framework, high performance, easy to learn, fast to code, ready for production",website:"https://fastapi.tiangolo.com",supersedes:["python"],useRuntime:{src:"<detect>",use:"@vercel/python"},ignoreRuntimes:["@vercel/python"],detectors:{some:[{path:"requirements.txt",matchContent:"fastapi"},{path:"pyproject.toml",matchContent:"fastapi"},{path:"Pipfile",matchContent:"fastapi"}]},settings:{installCommand:{placeholder:"`pip install -r requirements.txt`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Flask",slug:"flask",logo:"https://api-frameworks.vercel.sh/framework-logos/flask.svg",tagline:"The Python micro web framework",description:"A Flask app, ready for production",website:"https://flask.palletsprojects.com",supersedes:["python"],useRuntime:{src:"<detect>",use:"@vercel/python"},ignoreRuntimes:["@vercel/python"],detectors:{some:[{path:"requirements.txt",matchContent:"[Ff]lask"},{path:"pyproject.toml",matchContent:"[Ff]lask"},{path:"Pipfile",matchContent:"[Ff]lask"}]},settings:{installCommand:{placeholder:"`pip install -r requirements.txt`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"FastHTML",slug:"fasthtml",demo:"https://fasthtml-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/fasthtml.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/fasthtml-dark.svg",tagline:"The fastest way to create an HTML app",description:"A library for writing fast and scalable Starlette-powered web applications",website:"https://fastht.ml",supersedes:["python"],useRuntime:{src:"main.py",use:"@vercel/python"},detectors:{every:[{path:"requirements.txt",matchContent:"python-fasthtml"}]},settings:{installCommand:{placeholder:"`pip install`"},buildCommand:{placeholder:"None",value:null},devCommand:{value:"uvicorn main:app --reload"},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/main"}]},{name:"Django",slug:"django",logo:"https://api-frameworks.vercel.sh/framework-logos/django.svg",tagline:"Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. ",description:"A Django project served via the Python Runtime.",website:"https://www.djangoproject.com",supersedes:["python"],useRuntime:{src:"<detect>",use:"@vercel/python"},ignoreRuntimes:["@vercel/python"],detectors:{some:[{path:"requirements.txt",matchContent:"[Dd]jango"},{path:"pyproject.toml",matchContent:"[Dd]jango"},{path:"Pipfile",matchContent:"[Dd]jango"},{path:"manage.py",matchContent:"DJANGO_SETTINGS_MODULE"}]},settings:{installCommand:{placeholder:"`pip install -r requirements.txt`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Ash",slug:"ash",logo:"https://api-frameworks.vercel.sh/framework-logos/ash.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/ash-dark.svg",tagline:"A filesystem-first framework for durable backend agents on Vercel.",description:"An Ash app: agents authored as a directory of files, compiled and served on Vercel.",detectors:{every:[{path:"package.json",matchContent:'"(dev)?(d|D)ependencies":\\s*{[^}]*"experimental-ash":\\s*".+?"[^}]*}'}]},settings:{installCommand:{placeholder:"`pnpm install`, `yarn install`, or `npm install`"},buildCommand:{value:"ash build",placeholder:"`npm run build` or `ash build`"},devCommand:{value:"ash dev",placeholder:"ash dev"},outputDirectory:{value:".output"}},getOutputDirName:__name(async()=>".output","getOutputDirName"),experimental:!0},{name:"eve",slug:"eve",logo:"https://api-frameworks.vercel.sh/framework-logos/eve.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/eve-dark.svg",tagline:"A filesystem-first framework for durable backend agents on Vercel.",description:"An eve app: agents authored as a directory of files, compiled and served on Vercel.",detectors:{every:[{path:"package.json",matchContent:'"(dev)?(d|D)ependencies":\\s*{[^}]*"eve":\\s*".+?"[^}]*}'}]},settings:{installCommand:{placeholder:"`pnpm install`, `yarn install`, or `npm install`"},buildCommand:{value:"eve build",placeholder:"`npm run build` or `eve build`"},devCommand:{value:"eve dev",placeholder:"eve dev"},outputDirectory:{value:".output"}},getOutputDirName:__name(async()=>".output","getOutputDirName")},{name:"Sanity",slug:"sanity",demo:"https://template-studio-clean.sanity.dev",logo:"https://api-frameworks.vercel.sh/framework-logos/sanity.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/sanity-dark.svg",tagline:"The back-end built for AI content operations. Power web, mobile, and agentic applications at scale.",description:"A Sanity Studio",website:"https://www.sanity.io",envPrefix:"SANITY_STUDIO_",detectors:{some:[{path:"sanity.config.js"},{path:"sanity.config.jsx"},{path:"sanity.config.ts"},{path:"sanity.config.tsx"}],every:[{matchPackage:"sanity"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `sanity build`",value:"sanity build"},devCommand:{value:"sanity dev --port $PORT"},outputDirectory:{value:"dist"}},dependency:"sanity",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Sanity (v2 - legacy)",slug:"sanity-v2",demo:"https://sanity-studio-template.vercel.app",logo:"https://api-frameworks.vercel.sh/framework-logos/sanity-v2.svg",tagline:"The structured content platform.",description:"A Sanity Studio",website:"https://www.sanity.io",envPrefix:"SANITY_STUDIO_",detectors:{some:[{path:"sanity.json"}],every:[{path:"package.json",matchContent:'"(dev)?(d|D)ependencies":\\s*{[^}]*"@sanity/cli":\\s*"\\^?2\\..*"[^}]*}'}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `sanity build`",value:"sanity build"},devCommand:{value:"sanity start --port $PORT"},outputDirectory:{value:"dist"}},dependency:"@sanity/cli",getOutputDirName:__name(async()=>"dist","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/index.html"}]},{name:"Storybook",slug:"storybook",logo:"https://api-frameworks.vercel.sh/framework-logos/storybook.svg",tagline:"Frontend workshop for UI development",description:"Storybook is a frontend workshop for building UI components and pages in isolation.",website:"https://storybook.js.org",ignoreRuntimes:["@vercel/next","@vercel/node"],disableRootMiddleware:!0,detectionConfidence:"weak",detectors:{every:[{matchPackage:"storybook"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{value:"storybook build",ignorePackageJsonScript:!0},devCommand:{value:"storybook dev -p $PORT"},outputDirectory:{value:"storybook-static"}},getOutputDirName:__name(async()=>"storybook-static","getOutputDirName")},{name:"Nitro",slug:"nitro",logo:"https://api-frameworks.vercel.sh/framework-logos/nitro.svg",demo:"https://nitro-template.vercel.app",tagline:"Nitro is a next generation server toolkit.",description:"Nitro lets you create web servers that run on multiple platforms.",website:"https://nitro.build/",detectors:{some:[{matchPackage:"nitropack"},{matchPackage:"nitro"}]},supersedes:["vite"],settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `nitro build`",value:"nitro build"},devCommand:{value:"nitro dev"},outputDirectory:{value:"dist"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Hono",slug:"hono",logo:"https://api-frameworks.vercel.sh/framework-logos/hono.svg",demo:"https://hono.vercel.dev",tagline:"Web framework built on Web Standards",description:"Fast, lightweight, built on Web Standards. Support for any JavaScript runtime.",website:"https://hono.dev",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/hono"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"hono"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']hono["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},dependency:"hono",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Express",slug:"express",logo:"https://api-frameworks.vercel.sh/framework-logos/express.svg",demo:"https://express-vercel-example-demo.vercel.app/",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/express-dark.svg",tagline:"Fast, unopinionated, minimalist web framework for Node.js",description:"Fast, unopinionated, minimalist web framework for Node.js",website:"https://expressjs.com",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/express"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"express"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']express["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},dependency:"express",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"H3",slug:"h3",logo:"https://api-frameworks.vercel.sh/framework-logos/h3.svg",tagline:"Universal, Tiny, and Fast Servers",description:"H(TTP) server framework built on top of web standards for high performance and composability.",website:"https://h3.dev/",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/h3"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"h3"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']h3["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},dependency:"h3",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Koa",slug:"koa",logo:"https://api-frameworks.vercel.sh/framework-logos/koa.svg",tagline:"Expressive middleware for Node.js using ES2017 async functions",description:"Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.",website:"https://koajs.com",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/koa"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"koa"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']koa["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},dependency:"koa",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"NestJS",slug:"nestjs",logo:"https://api-frameworks.vercel.sh/framework-logos/nestjs.svg",tagline:"Framework for building efficient, scalable Node.js server-side applications",description:"A progressive Node.js framework for building efficient, reliable and scalable server-side applications.",website:"https://nestjs.com/",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/nestjs"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"@nestjs/core"}],some:[{path:"src/main.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/main.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/main.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/main.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/main.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/main.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"main.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']@nestjs/core["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},dependency:"nestjs",getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Elysia",slug:"elysia",logo:"https://api-frameworks.vercel.sh/framework-logos/elysia.svg",tagline:"Ergonomic framework for humans",description:"TypeScript with End-to-End Type Safety, type integrity, and exceptional developer experience. Supercharged by Bun.",website:"https://elysiajs.com/",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/elysia"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"elysia"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']elysia["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Fastify",slug:"fastify",logo:"https://api-frameworks.vercel.sh/framework-logos/fastify.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/fastify-dark.svg",tagline:"Fast and low overhead web framework, for Node.js",description:"Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture.",website:"https://fastify.dev/",supersedes:["node"],useRuntime:{src:"index.js",use:"@vercel/fastify"},defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}],detectors:{every:[{matchPackage:"fastify"}],some:[{path:"app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/index.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/app.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.cjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.js",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.mjs",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.mts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.ts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`},{path:"src/server.cts",matchContent:`(?:from|require|import)\\s*(?:\\(\\s*)?["']fastify["']\\s*(?:\\))?`}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"xmcp",slug:"xmcp",logo:"https://api-frameworks.vercel.sh/framework-logos/xmcp.svg",demo:"https://xmcp-template.vercel.app/",tagline:"The MCP framework for building AI-powered tools",description:"A framework for building Model Context Protocol servers with zero configuration.",website:"https://xmcp.dev",detectors:{some:[{path:"xmcp.config.ts"},{path:"xmcp.config.js"},{matchPackage:"xmcp"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `xmcp build`",value:"xmcp build --vercel"},devCommand:{value:"xmcp dev",placeholder:"xmcp dev"},outputDirectory:{value:"dist"}},dependency:"xmcp",getOutputDirName:__name(async()=>"dist","getOutputDirName")},{name:"Python",slug:"python",runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/python.svg",tagline:"Python is a programming language that lets you work quickly and integrate systems more effectively.",description:"A generic Python application deployed as a serverless function.",website:"https://python.org",useRuntime:{src:"<detect>",use:"@vercel/python"},ignoreRuntimes:["@vercel/python"],detectors:{some:[{path:"requirements.txt"},{path:"pyproject.toml"},{path:"Pipfile"}]},settings:{installCommand:{placeholder:"`pip install -r requirements.txt`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Ruby",slug:"ruby",experimental:!0,runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/ruby.svg",tagline:"A dynamic, open source programming language with a focus on simplicity and productivity.",description:"A generic Ruby application deployed as a serverless function.",website:"https://www.ruby-lang.org",useRuntime:{src:"config.ru",use:"@vercel/ruby"},ignoreRuntimes:["@vercel/ruby"],detectors:{every:[{path:"config.ru"},{path:"Gemfile"}]},settings:{installCommand:{placeholder:"`bundle install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/config"}]},{name:"Rust",slug:"rust",experimental:!0,runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/rust.svg",tagline:"A language empowering everyone to build reliable and efficient software.",description:"A generic Rust application deployed as a serverless function.",website:"https://www.rust-lang.org",useRuntime:{src:"src/main.rs",use:"@vercel/rust"},ignoreRuntimes:["@vercel/rust"],detectors:{every:[{path:"Cargo.toml"},{path:"src/main.rs"}]},settings:{installCommand:{placeholder:"None"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`cargo run`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/src/main"}]},{name:"Axum",slug:"axum",experimental:!0,supersedes:["rust"],logo:"https://api-frameworks.vercel.sh/framework-logos/axum.svg",tagline:"Ergonomic and modular web framework built with Tokio, Tower, and Hyper.",description:"An Axum application deployed as a serverless function.",website:"https://github.com/tokio-rs/axum",useRuntime:{src:"src/main.rs",use:"@vercel/rust"},ignoreRuntimes:["@vercel/rust"],detectors:{every:[{path:"Cargo.toml",matchContent:"axum\\s*="},{path:"src/main.rs"}]},settings:{installCommand:{placeholder:"None"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`cargo run`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/src/main"}]},{name:"Actix Web",slug:"actix-web",experimental:!0,runtimeFramework:!0,supersedes:["rust"],logo:"https://api-frameworks.vercel.sh/framework-logos/actix-web.svg",tagline:"A powerful, pragmatic, and extremely fast web framework for Rust.",description:"An Actix Web application deployed as a serverless function.",website:"https://actix.rs",useRuntime:{src:"src/main.rs",use:"@vercel/rust"},ignoreRuntimes:["@vercel/rust"],detectors:{every:[{path:"Cargo.toml",matchContent:"actix-web\\s*="},{path:"src/main.rs"}]},settings:{installCommand:{placeholder:"None"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`cargo run`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/src/main"}]},{name:"Bun",slug:"bun",runtimeFramework:!0,experimental:!0,supersedes:["node"],logo:"https://api-frameworks.vercel.sh/framework-logos/bun.svg",tagline:"Bun is a fast all-in-one JavaScript runtime, bundler, and package manager.",description:"A Bun application deployed as a serverless function.",website:"https://bun.com",useRuntime:{src:"package.json",use:"@vercel/backends"},ignoreRuntimes:["@vercel/node"],detectors:{every:[{path:"bun.lock"}],some:[{path:"server.cjs"},{path:"server.js"},{path:"server.mjs"},{path:"server.mts"},{path:"server.ts"},{path:"server.cts"},{path:"src/server.cjs"},{path:"src/server.js"},{path:"src/server.mjs"},{path:"src/server.mts"},{path:"src/server.ts"},{path:"src/server.cts"}]},settings:{installCommand:{value:"bun install",placeholder:"bun install"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`bun dev`, `bun run dev`, or `bun --hot server.ts`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Node",slug:"node",runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/node.svg",tagline:"Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.",description:"A generic Node.js application deployed as a serverless function.",website:"https://nodejs.org",useRuntime:{src:"package.json",use:"@vercel/backends"},ignoreRuntimes:["@vercel/node"],detectors:{some:[{path:"server.cjs"},{path:"server.js"},{path:"server.mjs"},{path:"server.mts"},{path:"server.ts"},{path:"server.cts"},{path:"src/server.cjs"},{path:"src/server.js"},{path:"src/server.mjs"},{path:"src/server.mts"},{path:"src/server.ts"},{path:"src/server.cts"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`npm run dev`, `node server.js`, or `npx ts-node server.ts`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Go",slug:"go",runtimeFramework:!0,logo:"https://api-frameworks.vercel.sh/framework-logos/go.svg",tagline:"An open-source programming language supported by Google.",description:"A generic Go application deployed as a serverless function.",website:"https://go.dev",useRuntime:{src:"index.go",use:"@vercel/go"},ignoreRuntimes:["@vercel/go"],detectors:{every:[{path:"go.mod"}],some:[{path:"main.go"},{path:"cmd/api/main.go"},{path:"cmd/server/main.go"}]},settings:{installCommand:{placeholder:"`go mod download`"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"`go run .` or `go run ./cmd/api`",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName"),defaultRoutes:[{handle:"filesystem"},{src:"/(.*)",dest:"/"}]},{name:"Services",slug:"services",logo:"https://api-frameworks.vercel.sh/framework-logos/services.svg",tagline:"Multiple services deployed as serverless functions within your project.",description:"Multiple services deployed as serverless functions within your project.",website:"https://vercel.com",settings:{installCommand:{placeholder:"None"},buildCommand:{placeholder:"None",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{value:"N/A"}},getOutputDirName:__name(async()=>"public","getOutputDirName")},{name:"Mastra",slug:"mastra",logo:"https://api-frameworks.vercel.sh/framework-logos/mastra.svg",darkModeLogo:"https://api-frameworks.vercel.sh/framework-logos/mastra-dark.svg",tagline:"Build AI agents with a modern TypeScript stack",description:"Mastra is a framework for building AI-powered apps and agents with workflows, memory, streaming, evals, tracing, and Studio, an interactive UI for dev and testing.",website:"https://mastra.ai",detectors:{every:[{matchPackage:"mastra"}]},settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run build` or `mastra build`",value:"mastra build"},devCommand:{value:"mastra dev"},outputDirectory:{value:".mastra"}},getOutputDirName:__name(async()=>".mastra","getOutputDirName")},{name:"Other",slug:null,logo:"https://api-frameworks.vercel.sh/framework-logos/other.svg",description:"No framework or an unoptimized framework.",settings:{installCommand:{placeholder:"`yarn install`, `pnpm install`, `npm install`, or `bun install`"},buildCommand:{placeholder:"`npm run vercel-build` or `npm run build`",value:null},devCommand:{placeholder:"None",value:null},outputDirectory:{placeholder:"`public` if it exists, or `.`"}},getOutputDirName:__name(async()=>"public","getOutputDirName")}],frameworkList=frameworks2,frameworks_default=frameworkList}});var require_detect_framework=__commonJS({"../../node_modules/.pnpm/@vercel+fs-detectors@6.15.3/node_modules/@vercel/fs-detectors/dist/detect-framework.js"(exports2,module2){"use strict";var __defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),detect_framework_exports={};__export2(detect_framework_exports,{detectFramework:__name(()=>detectFramework,"detectFramework"),detectFrameworkRecord:__name(()=>detectFrameworkRecord2,"detectFrameworkRecord"),detectFrameworkVersion:__name(()=>detectFrameworkVersion,"detectFrameworkVersion"),detectFrameworks:__name(()=>detectFrameworks,"detectFrameworks"),removeSupersededFrameworks:__name(()=>removeSupersededFrameworks,"removeSupersededFrameworks")});module2.exports=__toCommonJS2(detect_framework_exports);var import_child_process=__require("child_process");function shouldIncludeExperimentalFrameworks(useExperimentalFrameworks){if(typeof useExperimentalFrameworks=="boolean")return useExperimentalFrameworks;let experimentalEnv=process.env.VERCEL_USE_EXPERIMENTAL_FRAMEWORKS;return __name(val2=>val2==="1"||typeof val2=="string"&&val2.toLowerCase()==="true","isEnabled")(experimentalEnv)}__name(shouldIncludeExperimentalFrameworks,"shouldIncludeExperimentalFrameworks");function filterFrameworkList(frameworkList,useExperimentalFrameworks){return shouldIncludeExperimentalFrameworks(useExperimentalFrameworks)?frameworkList:frameworkList.filter(f=>!f.experimental)}__name(filterFrameworkList,"filterFrameworkList");async function matches(fs49,framework){let{detectors}=framework;if(!detectors)return;let{every,some:some2}=detectors;if(every!==void 0&&!Array.isArray(every)||some2!==void 0&&!Array.isArray(some2))return;let check=__name(async({path:path50,matchContent,matchPackage})=>{if(matchPackage&&matchContent)throw new Error(`Cannot specify "matchPackage" and "matchContent" in the same detector for "${framework.slug}"`);if(matchPackage&&path50)throw new Error(`Cannot specify "matchPackage" and "path" in the same detector for "${framework.slug}" because "path" is assumed to be "package.json".`);if(!path50&&!matchPackage)throw new Error(`Must specify either "path" or "matchPackage" in detector for "${framework.slug}".`);if(path50||(path50="package.json"),matchPackage&&(matchContent=`"(dev)?(d|D)ependencies":\\s*{[^}]*"${matchPackage}":\\s*"(.+?)"[^}]*}`),await fs49.hasPath(path50)!==!1){if(matchContent){if(await fs49.isFile(path50)===!1)return;let regex=new RegExp(matchContent,"m"),match=(await fs49.readFile(path50)).toString().match(regex);if(!match)return;if(matchPackage&&match[3])return{framework,detectedVersion:match[3]}}return{framework}}},"check"),result=[];if(every){let everyResult=await Promise.all(every.map(item=>check(item)));result.push(...everyResult)}if(some2){let someResult;for(let item of some2){let itemResult=await check(item);if(itemResult){someResult=itemResult;break}}result.push(someResult)}if(!result.every(res=>!!res))return;let detectedVersion=result.find(r=>typeof r=="object"&&r.detectedVersion)?.detectedVersion;return{framework,detectedVersion}}__name(matches,"matches");function removeSupersededFramework(matches2,slug){let index2=matches2.findIndex(f=>f?.slug===slug),framework=matches2[index2];if(framework){if(framework.supersedes)for(let slug2 of framework.supersedes)removeSupersededFramework(matches2,slug2);matches2.splice(index2,1)}}__name(removeSupersededFramework,"removeSupersededFramework");function removeSupersededFrameworks(matches2){for(let match of matches2.slice())if(match?.supersedes)for(let slug of match.supersedes)removeSupersededFramework(matches2,slug)}__name(removeSupersededFrameworks,"removeSupersededFrameworks");async function detectFramework({fs:fs49,frameworkList,useExperimentalFrameworks}){let filteredList=filterFrameworkList(frameworkList,useExperimentalFrameworks),result=await Promise.all(filteredList.map(async frameworkMatch=>await matches(fs49,frameworkMatch)?frameworkMatch:null));return removeSupersededFrameworks(result),result.find(res=>res!==null)?.slug??null}__name(detectFramework,"detectFramework");async function detectFrameworks({fs:fs49,frameworkList,useExperimentalFrameworks}){let filteredList=filterFrameworkList(frameworkList,useExperimentalFrameworks),result=await Promise.all(filteredList.map(async frameworkMatch=>await matches(fs49,frameworkMatch)?frameworkMatch:null));return removeSupersededFrameworks(result),result.filter(res=>res!==null)}__name(detectFrameworks,"detectFrameworks");async function detectFrameworkRecord2({fs:fs49,frameworkList,useExperimentalFrameworks}){let filteredList=filterFrameworkList(frameworkList,useExperimentalFrameworks),result=await Promise.all(filteredList.map(async frameworkMatch=>{let matchResult=await matches(fs49,frameworkMatch);return matchResult?{...frameworkMatch,detectedVersion:matchResult?.detectedVersion}:null}));return removeSupersededFrameworks(result),result.find(res=>res!==null)??null}__name(detectFrameworkRecord2,"detectFrameworkRecord");function detectFrameworkVersion(frameworkRecord){let firstMatchPackage=[...frameworkRecord.detectors?.every||[],...frameworkRecord.detectors?.some||[]].find(d3=>d3.matchPackage);if(firstMatchPackage?.matchPackage)return lookupInstalledVersion(process.execPath,firstMatchPackage.matchPackage)}__name(detectFrameworkVersion,"detectFrameworkVersion");function lookupInstalledVersion(cwd,packageName){try{let script=`require('${packageName}/package.json').version`;return(0,import_child_process.spawnSync)(cwd,["-p",script],{encoding:"utf-8"}).stdout.trim()}catch(error){console.debug(`Error looking up version of installed package "${packageName}": ${error}`)}}__name(lookupInstalledVersion,"lookupInstalledVersion")}});var require_filesystem=__commonJS({"../../node_modules/.pnpm/@vercel+fs-detectors@6.15.3/node_modules/@vercel/fs-detectors/dist/detectors/filesystem.js"(exports2,module2){"use strict";var __defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),filesystem_exports={};__export2(filesystem_exports,{DetectorFilesystem:__name(()=>DetectorFilesystem,"DetectorFilesystem")});module2.exports=__toCommonJS2(filesystem_exports);var import_path3=__require("path"),DetectorFilesystem=class{static{__name(this,"DetectorFilesystem")}constructor(){this.hasPath=async path50=>{let p2=this.pathCache.get(path50);return p2||(p2=this._hasPath(path50),this.pathCache.set(path50,p2)),p2},this.isFile=async name=>{let p2=this.fileCache.get(name);return p2||(p2=this._isFile(name),this.fileCache.set(name,p2)),p2},this.readFile=async name=>{let p2=this.readFileCache.get(name);return p2||(p2=this._readFile(name),this.readFileCache.set(name,p2)),p2},this.readdir=async(dirPath,options)=>{let p2=this.readdirCache.get(dirPath);p2||(p2=this._readdir(dirPath),this.readdirCache.set(dirPath,p2));let directoryContent=await p2,directoryFiles=new Set;for(let file of directoryContent)file.type==="file"&&(this.fileCache.set(file.path,Promise.resolve(!0)),this.pathCache.set(file.path,Promise.resolve(!0)),directoryFiles.add(file.name));if(options?.potentialFiles){let filesThatDoNotExist=options.potentialFiles.filter(path50=>(0,import_path3.basename)(path50)===path50).filter(path50=>!directoryFiles.has(path50));for(let filePath of filesThatDoNotExist){let fullFilePath=dirPath==="/"?filePath:import_path3.posix.join(dirPath,filePath);this.fileCache.set(fullFilePath,Promise.resolve(!1)),this.pathCache.set(fullFilePath,Promise.resolve(!1))}}return p2},this.chdir=name=>this._chdir(name),this.writeFile=async(name,content2)=>{this.readFileCache.set(name,Promise.resolve(Buffer.from(content2))),this.fileCache.set(name,Promise.resolve(!0)),this.pathCache.set(name,Promise.resolve(!0))},this.pathCache=new Map,this.fileCache=new Map,this.readFileCache=new Map,this.readdirCache=new Map}}}});var require_local_file_system_detector=__commonJS({"../../node_modules/.pnpm/@vercel+fs-detectors@6.15.3/node_modules/@vercel/fs-detectors/dist/detectors/local-file-system-detector.js"(exports2,module2){"use strict";var __create2=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf2=Object.getPrototypeOf,__hasOwnProp2=Object.prototype.hasOwnProperty,__export2=__name((target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:!0})},"__export"),__copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to,key)&&key!==except&&__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to},"__copyProps"),__toESM2=__name((mod,isNodeMode,target)=>(target=mod!=null?__create2(__getProtoOf2(mod)):{},__copyProps2(isNodeMode||!mod||!mod.__esModule?__defProp2(target,"default",{value:mod,enumerable:!0}):target,mod)),"__toESM"),__toCommonJS2=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:!0}),mod),"__toCommonJS"),local_file_system_detector_exports={};__export2(local_file_system_detector_exports,{LocalFileSystemDetector:__name(()=>LocalFileSystemDetector2,"LocalFileSystemDetector")});module2.exports=__toCommonJS2(local_file_system_detector_exports);var import_promises9=__toESM2(__require("fs/promises")),import_path3=__require("path"),import_filesystem=require_filesystem(),import_error_utils=require_dist2(),LocalFileSystemDetector2=class _LocalFileSystemDetector extends import_filesystem.DetectorFilesystem{static{__name(this,"LocalFileSystemDetector")}constructor(rootPath){super(),this.rootPath=rootPath}async _hasPath(name){try{return await import_promises9.default.stat(this.getFilePath(name)),!0}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")return!1;throw err}}_readFile(name){return import_promises9.default.readFile(this.getFilePath(name))}async _isFile(name){return(await import_promises9.default.stat(this.getFilePath(name))).isFile()}async _readdir(dir){let dirPath=this.getFilePath(dir),entries2=await import_promises9.default.readdir(dirPath,{withFileTypes:!0}),result=[];for(let entry of entries2){let type;if(entry.isFile())type="file";else if(entry.isDirectory())type="dir";else continue;result.push({name:entry.name,path:(0,import_path3.join)(this.getRelativeFilePath(dir),entry.name),type})}return result}_chdir(name){return new _LocalFileSystemDetector(this.getFilePath(name))}getRelativeFilePath(name){return name.startsWith(this.rootPath)?(0,import_path3.relative)(this.rootPath,name):name}getFilePath(name){return(0,import_path3.join)(this.rootPath,this.getRelativeFilePath(name))}}}});function split(value){let result=value.trim();result=result.replace(SPLIT_LOWER_UPPER_RE,SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE,SPLIT_REPLACE_VALUE),result=result.replace(DEFAULT_STRIP_REGEXP,"\0");let start=0,end2=result.length;for(;result.charAt(start)==="\0";)start++;if(start===end2)return[];for(;result.charAt(end2-1)==="\0";)end2--;return result.slice(start,end2).split(/\0/g)}function splitSeparateNumbers(value){let words=split(value);for(let i=0;i<words.length;i++){let word=words[i],match=SPLIT_SEPARATE_NUMBER_RE.exec(word);if(match){let offset=match.index+(match[1]??match[2]).length;words.splice(i,1,word.slice(0,offset),word.slice(offset))}}return words}function camelCase(input,options){let[prefix,words,suffix]=splitPrefixSuffix(input,options),lower=lowerFactory(options?.locale),upper=upperFactory(options?.locale),transform=options?.mergeAmbiguousCharacters?capitalCaseTransformFactory(lower,upper):pascalCaseTransformFactory(lower,upper);return prefix+words.map((word,index2)=>index2===0?lower(word):transform(word,index2)).join(options?.delimiter??"")+suffix}function pascalCase(input,options){let[prefix,words,suffix]=splitPrefixSuffix(input,options),lower=lowerFactory(options?.locale),upper=upperFactory(options?.locale),transform=options?.mergeAmbiguousCharacters?capitalCaseTransformFactory(lower,upper):pascalCaseTransformFactory(lower,upper);return prefix+words.map(transform).join(options?.delimiter??"")+suffix}function lowerFactory(locale){return locale===!1?input=>input.toLowerCase():input=>input.toLocaleLowerCase(locale)}function upperFactory(locale){return locale===!1?input=>input.toUpperCase():input=>input.toLocaleUpperCase(locale)}function capitalCaseTransformFactory(lower,upper){return word=>`${upper(word[0])}${lower(word.slice(1))}`}function pascalCaseTransformFactory(lower,upper){return(word,index2)=>{let char0=word[0];return(index2>0&&char0>="0"&&char0<="9"?"_"+char0:upper(char0))+lower(word.slice(1))}}function splitPrefixSuffix(input,options={}){let splitFn=options.split??(options.separateNumbers?splitSeparateNumbers:split),prefixCharacters=options.prefixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,suffixCharacters=options.suffixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,prefixIndex=0,suffixIndex=input.length;for(;prefixIndex<input.length;){let char=input.charAt(prefixIndex);if(!prefixCharacters.includes(char))break;prefixIndex++}for(;suffixIndex>prefixIndex;){let index2=suffixIndex-1,char=input.charAt(index2);if(!suffixCharacters.includes(char))break;suffixIndex=index2}return[input.slice(0,prefixIndex),splitFn(input.slice(prefixIndex,suffixIndex)),input.slice(suffixIndex)]}var SPLIT_LOWER_UPPER_RE,SPLIT_UPPER_UPPER_RE,SPLIT_SEPARATE_NUMBER_RE,DEFAULT_STRIP_REGEXP,SPLIT_REPLACE_VALUE,DEFAULT_PREFIX_SUFFIX_CHARACTERS,init_dist7=__esm({"../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js"(){SPLIT_LOWER_UPPER_RE=new RegExp("([\\p{Ll}\\d])(\\p{Lu})","gu"),SPLIT_UPPER_UPPER_RE=new RegExp("(\\p{Lu})([\\p{Lu}][\\p{Ll}])","gu"),SPLIT_SEPARATE_NUMBER_RE=new RegExp("(\\d)\\p{Ll}|(\\p{L})\\d","u"),DEFAULT_STRIP_REGEXP=/[^\p{L}\d]+/giu,SPLIT_REPLACE_VALUE="$1\0$2",DEFAULT_PREFIX_SUFFIX_CHARACTERS="";__name(split,"split");__name(splitSeparateNumbers,"splitSeparateNumbers");__name(camelCase,"camelCase");__name(pascalCase,"pascalCase");__name(lowerFactory,"lowerFactory");__name(upperFactory,"upperFactory");__name(capitalCaseTransformFactory,"capitalCaseTransformFactory");__name(pascalCaseTransformFactory,"pascalCaseTransformFactory");__name(splitPrefixSuffix,"splitPrefixSuffix")}});import*as path21 from"node:path";import*as fs18 from"node:fs";function ParseErr(message,str,indx){let whitespace2=str.slice(0,indx).split(/\n/),lineNo=whitespace2.length,colNo=whitespace2[lineNo-1].length+1;throw message+=" at line "+lineNo+" col "+colNo+`:
|
|
319
319
|
|
|
320
320
|
`+str.split(/\n/)[lineNo-1]+`
|
|
321
321
|
`+Array(colNo).join(" ")+"^",new EtaParseError(message)}function RuntimeErr(originalError,str,lineNo,path50){let lines=str.split(`
|
|
@@ -1174,7 +1174,7 @@ ${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("
|
|
|
1174
1174
|
${target}: Fimo branch not created yet`}}function pickSurfaces(opts){let selected=[["code","code"],["content","content"],["i18n","translations"],["assets","assets"],["forms","forms"]].filter(([flag2])=>opts[flag2]===!0).map(([,surface])=>surface);return selected.length>0?selected:void 0}function withSoftTimeout(p2,ms){return new Promise(resolve10=>{let t2=setTimeout(()=>resolve10({kind:"timeout"}),ms);p2.then(value=>{clearTimeout(t2),resolve10({kind:"ok",value})},error=>{clearTimeout(t2),resolve10({kind:"error",error})})})}async function localCodeSurface(cwd){if(!await isGitRepo(cwd))return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]};try{let items=(await runGit(["status","--porcelain"],cwd)).split(`
|
|
1175
1175
|
`).filter(Boolean).map(line=>{let code2=line.slice(0,2),path50=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path50,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),checkoutPromise=localCheckoutStatus(api,ctx.projectId,ctx.env,cwd),serverPromise=withSoftTimeout(api.getEnvStatus(ctx.projectId,ctx.env,{against:options.vs,surfaces}),SOFT_TIMEOUT_MS*15),[local,checkout,serverResult]=await Promise.all([codePromise,checkoutPromise,serverPromise]);if(serverResult.kind==="timeout"){ui.error({command:"status",code:"STATUS_TIMEOUT",message:`Server did not respond within ${SOFT_TIMEOUT_MS*15/1e3}s. Try again, or run \`fimo diff\` to drill in.`});return}if(serverResult.kind==="error"){let err=serverResult.error,message=err instanceof Error?err.message:String(err);ui.error({command:"status",code:"STATUS_REQUEST_FAILED",message:`Failed to fetch status: ${message}`});return}let server=serverResult.value,serverCode=server.surfaces.find(s=>s.surface==="code"),code2=mergeCodeSurfaces(serverCode,local),merged={...server,checkout,surfaces:[code2,...server.surfaces.filter(s=>s.surface!=="code")]};ui.result({command:"status",data:merged,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0}),environmentStatus=renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii});return`${renderLocalCheckoutStatus(checkout)}
|
|
1176
1176
|
|
|
1177
|
-
${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_environment_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs48 from"node:fs";import path49 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z68}from"zod";var CapabilityTokenSchema=z68.string().min(1).regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,{error:"capability tokens must match verb:noun or verb:noun:qualifier (lowercase + digits + underscores; must start with a letter)"}),CapabilitiesFileSchema=z68.array(CapabilityTokenSchema);import{z as z69}from"zod";var CronTriggerSchema=z69.object({type:z69.literal("schedule"),cron:z69.string().min(1,"cron expression required"),tz:z69.string().optional()}),ManualTriggerSchema2=z69.object({type:z69.literal("manual")}),WebhookTriggerSchema2=z69.object({type:z69.literal("webhook"),path:z69.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z69.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z69.object({name:z69.string().min(1),capability_grant:z69.enum(["inherit","explicit"]).optional(),explicit_grants:z69.array(z69.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z69.object({"sub-agents":z69.array(SubAgentRefSchema)}),RuntimeConfigSchema=z69.object({cloud:z69.boolean().optional(),dev:z69.boolean().optional(),long_running:z69.boolean().optional()}),DataSourceSchema=z69.enum(["main","prod"]),ConfigValueKeySchema=z69.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z69.preprocess(value=>typeof value=="string"?{key:value}:value,z69.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z69.boolean().default(!0),delivery:z69.literal("process_env").default("process_env")})),IntegrationKeySchema=z69.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z69.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z69.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z69.object({enabled:z69.boolean().default(!0),tools:z69.record(IntegrationToolKeySchema,z69.boolean()).optional()})),IntegrationPolicySchema=z69.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z69.object({version:z69.literal(1),description:z69.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z69.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z69.array(DataSourceSchema).optional(),secrets:z69.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path4.relative(dir,path4.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path4.basename(bundlePath),goalPath=path4.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path4.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path4.join(bundlePath,"SOUL.md")),capsPath=path4.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=parsed.data}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash2("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path4.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path4.join(agentsDir,entry.name);if(await fileExists(path4.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");var ENTRIES=[{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read production logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"net:fetch",risk:"medium",declarable:!0,enforcedBy:"runtime",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",declarable:!0,enforcedBy:"runtime",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isDeclarableCapability(token){return getCapability(token)?.declarable===!0}__name(isDeclarableCapability,"isDeclarableCapability");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isDeclarableCapability(token)||issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is platform-internal; project-authored agents cannot declare it`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools===void 0||entry.tools[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry,availableTools=[]){return entry?.enabled?entry.tools===void 0?[...availableTools].sort((a,b)=>a.localeCompare(b)):Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown2=[],nonDeclarable=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown2.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown2.length===0&&nonDeclarable.length===0,unknown:unknown2,nonDeclarable,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z70}from"zod";var SurfaceGuardPolicySchema=z70.enum(["block","warn","allow"]),ClassificationSchema=z70.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z70.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z70.object({enabled:z70.boolean(),allowed_skills:z70.array(z70.string().min(1)).default([]),allowed_classifications:z70.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z70.enum(["off","daily","weekly"]),NotificationFormatSchema=z70.object({markdown:z70.boolean().default(!0),html:z70.boolean().default(!1)}),NotificationsPolicySchema=z70.object({email_recipients:z70.array(z70.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z70.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z70.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??".fimo/config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??".fimo/config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??".fimo/config.json"} schema validation failed: ${issues}`,{remediation:"See `.fimo/config.json` in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??".fimo/config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??".fimo/config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");import{z as z71}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z71.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z71.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union2=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union2.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union2).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_scaffold();import fs8 from"node:fs";import path8 from"node:path";init_dist();init_auth_errors();init_project();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path8.resolve(cwd);for(let i=0;i<8;i++){if(fs8.existsSync(resolveProjectConfigPath(dir))||fs8.existsSync(path8.join(dir,"package.json")))return dir;let parent2=path8.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no Fimo config or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let projectRoot=findProjectRoot(cwd);if(!projectRoot)return null;try{return{projectRoot,settings:loadProjectSettings(projectRoot)}}catch{return null}}__name(resolveFimoProject,"resolveFimoProject");function resolveAgentBundlesDir(projectRoot){return resolveProjectAgentsDir(projectRoot)}__name(resolveAgentBundlesDir,"resolveAgentBundlesDir");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a linked Fimo project. Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path9.join(resolveAgentBundlesDir(projectRoot),opts.name);if(fs9.existsSync(targetDir))return{ok:!1,error:`${path9.relative(projectRoot,targetDir)}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}return await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path9.join(targetDir,"config.yaml"),opts.description),{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs9.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
|
|
1177
|
+
${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_environment_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs48 from"node:fs";import path49 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z68}from"zod";var CapabilityTokenSchema=z68.string().min(1).regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,{error:"capability tokens must match verb:noun or verb:noun:qualifier (lowercase + digits + underscores; must start with a letter)"}),CapabilitiesFileSchema=z68.array(CapabilityTokenSchema);import{z as z69}from"zod";var CronTriggerSchema=z69.object({type:z69.literal("schedule"),cron:z69.string().min(1,"cron expression required"),tz:z69.string().optional()}),ManualTriggerSchema2=z69.object({type:z69.literal("manual")}),WebhookTriggerSchema2=z69.object({type:z69.literal("webhook"),path:z69.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z69.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z69.object({name:z69.string().min(1),capability_grant:z69.enum(["inherit","explicit"]).optional(),explicit_grants:z69.array(z69.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z69.object({"sub-agents":z69.array(SubAgentRefSchema)}),RuntimeConfigSchema=z69.object({cloud:z69.boolean().optional(),dev:z69.boolean().optional(),long_running:z69.boolean().optional()}),DataSourceSchema=z69.enum(["main","prod"]),ConfigValueKeySchema=z69.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z69.preprocess(value=>typeof value=="string"?{key:value}:value,z69.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z69.boolean().default(!0),delivery:z69.literal("process_env").default("process_env")})),IntegrationKeySchema=z69.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z69.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z69.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z69.object({enabled:z69.boolean().default(!0),tools:z69.record(IntegrationToolKeySchema,z69.boolean()).optional()})),IntegrationPolicySchema=z69.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z69.object({version:z69.literal(1),description:z69.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z69.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z69.array(DataSourceSchema).optional(),secrets:z69.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path4.relative(dir,path4.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path4.basename(bundlePath),goalPath=path4.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path4.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path4.join(bundlePath,"SOUL.md")),capsPath=path4.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=parsed.data}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash2("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path4.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path4.join(agentsDir,entry.name);if(await fileExists(path4.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");var ENTRIES=[{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"net:fetch",risk:"medium",declarable:!0,enforcedBy:"runtime",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",declarable:!0,enforcedBy:"runtime",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isDeclarableCapability(token){return getCapability(token)?.declarable===!0}__name(isDeclarableCapability,"isDeclarableCapability");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isDeclarableCapability(token)||issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is platform-internal; project-authored agents cannot declare it`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools===void 0||entry.tools[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry,availableTools=[]){return entry?.enabled?entry.tools===void 0?[...availableTools].sort((a,b)=>a.localeCompare(b)):Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown2=[],nonDeclarable=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown2.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown2.length===0&&nonDeclarable.length===0,unknown:unknown2,nonDeclarable,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z70}from"zod";var SurfaceGuardPolicySchema=z70.enum(["block","warn","allow"]),ClassificationSchema=z70.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z70.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z70.object({enabled:z70.boolean(),allowed_skills:z70.array(z70.string().min(1)).default([]),allowed_classifications:z70.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z70.enum(["off","daily","weekly"]),NotificationFormatSchema=z70.object({markdown:z70.boolean().default(!0),html:z70.boolean().default(!1)}),NotificationsPolicySchema=z70.object({email_recipients:z70.array(z70.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z70.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z70.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??".fimo/config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??".fimo/config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??".fimo/config.json"} schema validation failed: ${issues}`,{remediation:"See `.fimo/config.json` in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??".fimo/config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??".fimo/config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");import{z as z71}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z71.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z71.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union2=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union2.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union2).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_scaffold();import fs8 from"node:fs";import path8 from"node:path";init_dist();init_auth_errors();init_project();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path8.resolve(cwd);for(let i=0;i<8;i++){if(fs8.existsSync(resolveProjectConfigPath(dir))||fs8.existsSync(path8.join(dir,"package.json")))return dir;let parent2=path8.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no Fimo config or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let projectRoot=findProjectRoot(cwd);if(!projectRoot)return null;try{return{projectRoot,settings:loadProjectSettings(projectRoot)}}catch{return null}}__name(resolveFimoProject,"resolveFimoProject");function resolveAgentBundlesDir(projectRoot){return resolveProjectAgentsDir(projectRoot)}__name(resolveAgentBundlesDir,"resolveAgentBundlesDir");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a linked Fimo project. Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path9.join(resolveAgentBundlesDir(projectRoot),opts.name);if(fs9.existsSync(targetDir))return{ok:!1,error:`${path9.relative(projectRoot,targetDir)}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}return await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path9.join(targetDir,"config.yaml"),opts.description),{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs9.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
|
|
1178
1178
|
${line}`):next2=(content2.endsWith(`
|
|
1179
1179
|
`)?content2:content2+`
|
|
1180
1180
|
`)+line+`
|
|
@@ -1239,7 +1239,7 @@ This breaks source tracking for inline editing. Translation keys must be statica
|
|
|
1239
1239
|
`),process.exit(1)}}import fs24 from"node:fs";import path27 from"node:path";var SCAN_EXTENSIONS=[".ts",".tsx",".js",".jsx",".mjs"],SCAN_EXTENSIONS_SET=new Set(SCAN_EXTENSIONS),SKIP_DIRS=new Set(["node_modules","dist",".next",".fimo",".git","public"]),GLOBAL_PATTERNS=[/\.css$/,/\.scss$/,/tailwind\.config/,/postcss\.config/,/vite\.config/,/tsconfig/,/package\.json$/,/src\/main\.[tj]sx?$/,/src\/index\.[tj]sx?$/,/src\/root\.[tj]sx?$/,/react-router\.config/];function isGlobalFile(filePath){return GLOBAL_PATTERNS.some(p2=>p2.test(filePath))}__name(isGlobalFile,"isGlobalFile");function collectFiles(dir){let files=[];if(!fs24.existsSync(dir))return files;let entries2=fs24.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){if(SKIP_DIRS.has(entry.name))continue;let fullPath=path27.join(dir,entry.name);entry.isDirectory()?files.push(...collectFiles(fullPath)):SCAN_EXTENSIONS_SET.has(path27.extname(entry.name))&&files.push(fullPath)}return files}__name(collectFiles,"collectFiles");function extractImports(content2){let imports=[],staticRegex=/(?:import|export)\s+(?:[\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g;for(let match of content2.matchAll(staticRegex))imports.push(match[1]);let dynamicRegex=/import\(\s*['"]([^'"]+)['"]\s*\)/g;for(let match of content2.matchAll(dynamicRegex))imports.push(match[1]);let requireRegex=/require\(\s*['"]([^'"]+)['"]\s*\)/g;for(let match of content2.matchAll(requireRegex))imports.push(match[1]);return imports.filter(s=>s.startsWith(".")||s.startsWith("@/"))}__name(extractImports,"extractImports");function resolveImport(specifier,fromDir,srcDir){let targetPath;if(specifier.startsWith("@/"))targetPath=path27.resolve(srcDir,specifier.slice(2));else if(specifier.startsWith("."))targetPath=path27.resolve(fromDir,specifier);else return null;if(fs24.existsSync(targetPath)&&fs24.statSync(targetPath).isFile())return targetPath;for(let ext of SCAN_EXTENSIONS){let withExt=targetPath+ext;if(fs24.existsSync(withExt))return withExt}for(let ext of SCAN_EXTENSIONS){let indexFile=path27.join(targetPath,"index"+ext);if(fs24.existsSync(indexFile))return indexFile}return null}__name(resolveImport,"resolveImport");function discoverRoutes(srcDir,root2){let routesFilePath=path27.resolve(srcDir,"routes.ts");if(!fs24.existsSync(routesFilePath))return new Map;let source=fs24.readFileSync(routesFilePath,"utf-8"),parsed=parseRoutesSource(source),fileToRoutes=new Map;for(let r of parsed){if(r.isLayout||!r.path||!r.file)continue;let resolved=resolveImport(r.file,srcDir,srcDir);if(!resolved)continue;let rel=path27.relative(root2,resolved);fileToRoutes.has(rel)||fileToRoutes.set(rel,new Set),fileToRoutes.get(rel).add(r.path)}return fileToRoutes}__name(discoverRoutes,"discoverRoutes");function buildReverseImportGraph(srcDir,root2){let fileToImporters=new Map,allFiles=collectFiles(srcDir);for(let filePath of allFiles){let content2;try{content2=fs24.readFileSync(filePath,"utf-8")}catch{continue}let imports=extractImports(content2);for(let specifier of imports){let resolved=resolveImport(specifier,path27.dirname(filePath),srcDir);if(!resolved)continue;let resolvedRel=path27.relative(root2,resolved),importerRel=path27.relative(root2,filePath);fileToImporters.has(resolvedRel)||fileToImporters.set(resolvedRel,new Set),fileToImporters.get(resolvedRel).add(importerRel)}}return fileToImporters}__name(buildReverseImportGraph,"buildReverseImportGraph");function resolveAffectedRoutes(file,fileToImporters,fileToRoutes){let visited=new Set,queue=[file],affectedRoutes=new Set;for(;queue.length>0;){let current=queue.shift();if(visited.has(current))continue;visited.add(current);let routes=fileToRoutes.get(current);if(routes)for(let route of routes)affectedRoutes.add(route);let importers=fileToImporters.get(current);if(importers)for(let importer of importers)visited.has(importer)||queue.push(importer)}return Array.from(affectedRoutes)}__name(resolveAffectedRoutes,"resolveAffectedRoutes");function resolveRoutes(changedFiles,options={}){let root2=options.cwd??process.cwd(),srcDir=path27.resolve(root2,"src"),normalizedChangedFiles=changedFiles.map(f=>f.replace(/^\/+/,""));if(normalizedChangedFiles.length===0)return{routeMap:{},routes:[],unresolvedFiles:[]};let fileToRoutes=discoverRoutes(srcDir,root2),fileToImporters=buildReverseImportGraph(srcDir,root2),routeMap={},unresolvedFiles=[];for(let file of normalizedChangedFiles){if(isGlobalFile(file)){routeMap[file]=["*"];continue}let routes=resolveAffectedRoutes(file,fileToImporters,fileToRoutes);routes.length>0?routeMap[file]=routes:unresolvedFiles.push(file)}let allRoutes=[...new Set(Object.values(routeMap).flat().filter(r=>r!=="*"))];return{routeMap,routes:allRoutes,unresolvedFiles}}__name(resolveRoutes,"resolveRoutes");init_sync_forms();init_sync_schemas();function resolveCwd(options){return options.cwd?resolve7(options.cwd):process.cwd()}__name(resolveCwd,"resolveCwd");function renderPrettyJson4(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson4,"renderPrettyJson");async function syncSchemasCommand(options){let cwd=resolveCwd(options),framework=await detectProjectFramework(cwd),result=syncSchemas({cwd,framework:framework?.slug??null});ui.result({command:"scripts sync-schemas",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncSchemasCommand,"syncSchemasCommand");async function syncFormsCommand(options){let cwd=resolveCwd(options),framework=await detectProjectFramework(cwd),result=syncForms({cwd,framework:framework?.slug??null});ui.result({command:"scripts sync-forms",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncFormsCommand,"syncFormsCommand");async function exportStaticCommand(options){let result=await exportStatic({cwd:resolveCwd(options)});ui.result({command:"export-static",data:result??{ok:!0},render:__name(()=>renderPrettyJson4(result??{ok:!0}),"render")})}__name(exportStaticCommand,"exportStaticCommand");function validateRouteMetadataCommand(options){let result=validateRouteMetadata({cwd:resolveCwd(options)});result.errors.length>0&&(ui.error({command:"scripts validate-route-metadata",code:"ROUTE_METADATA_INVALID",message:`Route metadata validation failed (${result.errors.length} issue(s)):
|
|
1240
1240
|
${result.errors.map(e=>` - ${e}`).join(`
|
|
1241
1241
|
`)}`}),process.exit(1)),ui.ok({command:"scripts validate-route-metadata",headline:`Route metadata validation passed (${result.routesChecked} route${result.routesChecked===1?"":"s"}).`,details:{routes_checked:result.routesChecked}})}__name(validateRouteMetadataCommand,"validateRouteMetadataCommand");function extractTranslationsCommand(options){let cwd=resolveCwd(options),data2={keys:extractTranslations({cwd}).keys.length};ui.result({command:"scripts extract-translations",data:data2,render:__name(()=>JSON.stringify(data2),"render")})}__name(extractTranslationsCommand,"extractTranslationsCommand");function resolveRoutesCommand(changedFiles,options){let cwd=resolveCwd(options),files=[];if(changedFiles.length===1&&changedFiles[0].startsWith("{"))try{files=JSON.parse(changedFiles[0]).files??[]}catch{files=[]}else files=changedFiles;let output=resolveRoutes(files,{cwd});ui.result({command:"resolve-routes",data:output,render:__name(()=>JSON.stringify(output),"render")})}__name(resolveRoutesCommand,"resolveRoutesCommand");function lintProject(opts){let files=opts.targetPath?[resolve7(opts.cwd,opts.targetPath)]:collectFiles2(resolve7(opts.cwd,"src")),errors=[],filesChecked=0;for(let file of files)if(/\.(tsx?|jsx?)$/.test(file))try{let code2=readFileSync8(file,"utf-8");errors.push(...lintTranslationKeys(file,code2)),filesChecked++}catch{}return{errors,filesChecked}}__name(lintProject,"lintProject");function lintCommand(targetPath,options){let cwd=resolveCwd(options),result=lintProject({cwd,targetPath});ui.result({command:"scripts lint",data:result,render:__name(()=>JSON.stringify(result),"render")}),result.errors.length>0&&process.exit(1)}__name(lintCommand,"lintCommand");function collectFiles2(root2){if(!existsSync8(root2))return[];let results=[];for(let name of readdirSync6(root2)){if(name==="node_modules"||name==="dist"||name===".git")continue;let full=join9(root2,name);statSync3(full).isDirectory()?results.push(...collectFiles2(full)):results.push(full)}return results}__name(collectFiles2,"collectFiles");async function validateCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),envOverride2=envOverrideFromCommand(cmd),report=await runValidate({cwd,envOverride:envOverride2}),warnings=[getDbLabelsRuntimeWarning(cwd),getPackageManagerPinWarning(cwd)].filter(warning=>!!warning);ui.result({command:"validate",data:report,render:__name(()=>formatReportHuman(report),"render"),warnings:warnings.length>0?warnings:void 0}),report.ok||(process.exitCode=report.exitCode)}__name(validateCommand,"validateCommand");async function runValidate(opts){let{cwd,envOverride:envOverride2}=opts,checks=await runChecksPhase({cwd}),codegen,labelKeys=null;if(checks.errors.length>0)codegen=skippedPhase("Codegen","static checks failed");else{let codegenResult=await runCodegenPhase({cwd});codegen=codegenResult.phase,labelKeys=codegenResult.labelKeys}let sync;return checks.errors.length>0?sync=skippedPhase("Labels","static checks failed"):labelKeys===null?sync=skippedPhase("Labels","label key scan failed"):sync=await runLabelsPhase({cwd,labelKeys,envOverride:envOverride2}),finalizeReport({phases:{checks,codegen,sync}})}__name(runValidate,"runValidate");async function runChecksPhase(opts){let{cwd}=opts,[lintResult,routeResult,agentsResult,schemasResult,configResult]=await Promise.allSettled([Promise.resolve().then(()=>lintProject({cwd})),Promise.resolve().then(()=>runRouteMetadataCheck({cwd})),Promise.resolve().then(()=>runAgentsCheck({cwd})),Promise.resolve().then(()=>validateSchemas({cwd})),Promise.resolve().then(()=>validateFimoConfig(cwd))]),errors=[],stats={};if(lintResult.status==="fulfilled"){stats.filesLinted=lintResult.value.filesChecked;for(let err of lintResult.value.errors)errors.push(authorError({rule:`lint/${err.rule}`,message:err.message,file:err.file,line:err.line,column:err.column}))}else errors.push(infraErrorFromException("lint",lintResult.reason));if(routeResult.status==="fulfilled"){if(routeResult.value){stats.routesChecked=routeResult.value.routesChecked;for(let message of routeResult.value.errors)errors.push(authorError({rule:"route-metadata",message}))}}else errors.push(infraErrorFromException("route-metadata",routeResult.reason));if(agentsResult.status==="fulfilled"?(Object.assign(stats,agentsResult.value.stats),errors.push(...agentsResult.value.errors)):errors.push(infraErrorFromException("agents",agentsResult.reason)),schemasResult.status==="fulfilled"){stats.schemasChecked=schemasResult.value.schemasChecked;for(let err of schemasResult.value.errors)errors.push(authorError({rule:err.rule,message:err.message,file:err.file}))}else errors.push(infraErrorFromException("schemas",schemasResult.reason));if(configResult.status==="fulfilled"){stats.configsChecked=Number(configResult.value.configChecked);for(let message of configResult.value.errors)errors.push(authorError({rule:"fimo-config",message}))}else errors.push(infraErrorFromException("fimo-config",configResult.reason));return{name:"Checks",ok:errors.length===0,errors,stats}}__name(runChecksPhase,"runChecksPhase");async function runAgentsCheck(opts){let{cwd}=opts,report=await runValidateAgents({cwd,json:!0}),errors=[];if(report.policy&&!report.policy.ok)for(let issue of report.policy.issues)errors.push(authorError({rule:"agents/policy",message:issue.message,file:issue.pointer}));for(let bundle of report.bundles)for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)errors.push(authorError({rule:`agents/${phase}`,message:`${bundle.name}: ${issue.message}`,file:issue.pointer}));return{errors,stats:{agentsChecked:report.bundles.length}}}__name(runAgentsCheck,"runAgentsCheck");async function runRouteMetadataCheck(opts){let framework=await detectProjectFramework(opts.cwd);return framework&&framework.slug!=="react-router"?null:validateRouteMetadata({cwd:opts.cwd})}__name(runRouteMetadataCheck,"runRouteMetadataCheck");async function runCodegenPhase(opts){let{cwd}=opts,frameworkResult=detectProjectFramework(cwd),[schemasResult,formsResult,labelsResult]=await Promise.allSettled([frameworkResult.then(framework=>syncSchemas({cwd,framework:framework?.slug??null,verbose:!1})),frameworkResult.then(framework=>syncForms({cwd,framework:framework?.slug??null,verbose:!1})),Promise.resolve().then(()=>extractLabelKeys({cwd}))]),errors=[],stats={};schemasResult.status==="fulfilled"?(stats.schemasCreated=schemasResult.value.created,stats.schemasUpdated=schemasResult.value.updated,stats.schemasDeleted=schemasResult.value.deleted):errors.push(infraErrorFromException("sync-schemas",schemasResult.reason)),formsResult.status==="fulfilled"?(stats.formsCreated=formsResult.value.created,stats.formsUpdated=formsResult.value.updated,stats.formsDeleted=formsResult.value.deleted):errors.push(infraErrorFromException("sync-forms",formsResult.reason));let labelKeys=null;return labelsResult.status==="fulfilled"?(labelKeys=labelsResult.value,stats.labelsDeclared=labelKeys.length):errors.push(infraErrorFromException("extract-label-keys",labelsResult.reason)),{phase:{name:"Codegen",ok:errors.length===0,errors,stats},labelKeys}}__name(runCodegenPhase,"runCodegenPhase");async function runLabelsPhase(opts){let{cwd,labelKeys,envOverride:envOverride2}=opts;if(labelKeys.length===0)return{name:"Labels",ok:!0,errors:[],stats:{labelsDeclared:0,labelsMissing:0}};let ctx;try{ctx=await getProjectContext({cwd,envOverride:envOverride2})}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("load-project-settings",error)]}}let api=new FimoApiClient(loadConfig()).withEnv(ctx.env),locale=getConfigServer(cwd).i18n?.defaultLocale??"en";try{let labels2=await loadLabelsForValidation({cwd,locale,projectId:ctx.projectId,loadAuthenticatedLabels:__name(()=>api.listLabels(ctx.projectId,locale),"loadAuthenticatedLabels")}),existingKeys=new Set(Object.keys(labels2)),missing=labelKeys.filter(label=>!existingKeys.has(label.key));return{name:"Labels",ok:missing.length===0,errors:missing.map(label=>authorError({rule:"labels/missing",message:`Missing label "${label.key}" for locale "${locale}". Run: fimo labels set ${JSON.stringify(label.key)} --locale ${locale} --value "...".`,file:label.file})),stats:{labelsDeclared:labelKeys.length,labelsMissing:missing.length}}}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("labels-check",error)]}}}__name(runLabelsPhase,"runLabelsPhase");function labelsToRecord(labels2){return Object.fromEntries(labels2.map(label=>[label.key,label.value??label.defaultValue??""]))}__name(labelsToRecord,"labelsToRecord");async function loadPublicTenantLabels(cwd,locale){let env=await readProjectEnv(cwd),apiUrl=env.VITE_API_URL;if(!apiUrl)return null;try{let url=new URL("/labels",apiUrl);url.searchParams.set("locale",locale);let headers=env.FIMO_ENV?{"X-Fimo-Env":env.FIMO_ENV}:{},response=await fetchWithTimeout(url,3e4,headers);if(!response.ok)return null;let body=await response.json();return Array.isArray(body.data)?labelsToRecord(body.data):body.data?.labels??null}catch{return null}}__name(loadPublicTenantLabels,"loadPublicTenantLabels");async function loadLabelsForValidation({cwd,locale,projectId,loadAuthenticatedLabels}){let env=await readProjectEnv(cwd);if(!env.VITE_API_URL)return labelsToRecord(await loadAuthenticatedLabels());let labels2=await loadPublicTenantLabels(cwd,locale);if(labels2==null)throw new Error(`Could not read labels from project "${projectId}" env "${env.FIMO_ENV??"main"}"`);return labels2}__name(loadLabelsForValidation,"loadLabelsForValidation");async function fetchWithTimeout(url,timeoutMs,headers){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),timeoutMs);try{return await fetch(url,{signal:controller.signal,headers})}finally{clearTimeout(timeout)}}__name(fetchWithTimeout,"fetchWithTimeout");async function readProjectEnv(cwd){let values={...await readEnvFile(path28.join(cwd,".env")),...await readEnvFile(path28.join(cwd,".env.local"))};if(process.env.VITE_API_URL&&(values.VITE_API_URL=process.env.VITE_API_URL),process.env.FIMO_ENV&&(values.FIMO_ENV=process.env.FIMO_ENV),!values.VITE_API_URL){let derived=resolveLocalRuntimeEnv({cwd});derived&&(values.VITE_API_URL=derived.tenantApiUrl,values.FIMO_ENV??=derived.env)}return values}__name(readProjectEnv,"readProjectEnv");async function readEnvFile(filePath){try{let content2=await readFile3(filePath,"utf8"),values={};for(let line of content2.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let index2=trimmed.indexOf("=");if(index2===-1)continue;let key=trimmed.slice(0,index2).trim(),value=trimmed.slice(index2+1).trim().replace(/^['"]|['"]$/g,"");values[key]=value}return values}catch{return{}}}__name(readEnvFile,"readEnvFile");async function deployCommand(options,cmd){if(process.env.FIMO_MIGRATION_NO_DEPLOY==="1"){ui.error({command:"deploy",code:"MIGRATION_DEPLOY_BLOCKED",message:"Deployment is disabled while a migration is running.",hint:"Finish local migration and QA first, then request deployment separately."});return}let cwd=resolveProjectCwd(options.cwd),local;try{local=loadProjectSettings(cwd)}catch{ui.error({command:"deploy",code:"NOT_IN_PROJECT",message:"You are not in a Fimo project.",hint:"Run `fimo create` to start one, or cd into a linked project."});return}if(!await isGitRepo(cwd)){ui.error({command:"deploy",code:"NOT_A_GIT_REPO",message:"Not a git repository."});return}let isPretty2=currentMode().format==="pretty";isPretty2&&mt(options.publish?"Deploying and publishing":"Deploying to preview");let envOverride2=envOverrideFromCommand(cmd),ctx=await getProjectContext({cwd,envOverride:envOverride2});if(isPretty2&&process.stderr.write(`${envSourceBanner(ctx)}
|
|
1242
|
-
`),ctx.readOnly){ui.error({command:"deploy",code:"ENV_READONLY",message:`Refusing to deploy to read-only env '${ctx.env}'.`,hint:"Switch off the release/* tag or pass --env <writable-env>."});return}if(options.publish&&ctx.env!==DEFAULT_ENV){ui.error({command:"deploy",code:"PUBLISH_REQUIRES_DEFAULT_ENV",message:`Refusing to --publish from env '${ctx.env}'. Publish only runs from '${DEFAULT_ENV}'.`,hint:`Drop --publish to deploy a preview, or switch to '${DEFAULT_ENV}' first.`});return}let devFimoSelection;try{devFimoSelection=resolveDevFimoDependencyForDeploy(cwd)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}await requireOperation("fimo.deploy",{projectId:ctx.projectId,env:ctx.env});let cfg=loadConfig(),api=new FimoApiClient(cfg).withEnv(ctx.env),studioUrl=buildProjectPreviewUrl(cfg.webUrl,local.projectId,ctx.env),previewUrl=buildPreviewUrl(cfg.webUrl,local.projectId,ctx.env),previewEnabled=(await api.getProject(local.projectId)).previewEnabled!==!1,remoteSp=spinner("Checking the Fimo branch"),remote;try{remote=await api.getGitRemote(local.projectId,ctx.env),await ensureFimoRemote(cwd,remote.url);let preparation=await prepareDeployCheckout({cwd,remoteBranch:remote.branch});remoteSp.succeed(preparation==="missing-remote"?`Fimo branch ${remote.branch} will be created by this deploy`:`Checkout ready for fimo/${remote.branch}`)}catch(error){if(remoteSp.fail("Checkout is not ready to deploy"),error instanceof EnvironmentCheckoutError){ui.error({command:"deploy",code:error.code,message:error.message,hint:error.hint});return}rethrowCliAuthError(error),ui.error({command:"deploy",code:"ENV_GIT_PREFLIGHT_FAILED",message:`Could not compare this checkout with the Fimo branch: ${errorMessage(error)}`});return}let validateSp=spinner("Validating project"),report=await runValidate({cwd,envOverride:envOverride2}),packageManagerWarning=getPackageManagerPinWarning(cwd);if(packageManagerWarning&&ui.warn({command:"deploy",message:packageManagerWarning}),report.ok)validateSp.succeed("Validation passed");else if(options.force)validateSp.fail("Validation failed \u2014 continuing anyway (--force)"),ui.warn({command:"deploy",message:"Bypassing validation errors because --force was passed. The deploy may still fail later in the sandbox."});else{validateSp.fail("Validation failed"),ui.result({command:"deploy",data:{stage:"validate",report},render:__name(()=>formatReportHuman(report),"render")}),process.exitCode=report.exitCode;return}let devFimoDependency=null;try{devFimoDependency=prepareDevFimoDependencyForDeploy(cwd,devFimoSelection)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}devFimoDependency&&isPretty2&&O2.info(`Deploying with fimo ${devFimoDependency.version}; restoring local dependency state after push.`);try{if(await hasUncommittedChanges(cwd)){let message;if(options.message!==void 0)message=options.message;else{assertInteractive('Pass -m "<message>" or commit your changes manually.',"deploy"),isPretty2&&O2.warn("You have uncommitted changes. Commit them before deploying.");let answer=await Ot({message:"Commit message",placeholder:"Deploy",defaultValue:"Deploy"});if(q(answer)){ui.info({command:"deploy",message:"Cancelled."});return}message=String(answer)}let commitSp=spinner("Committing pending changes");await runGit(["add","-A"],cwd),await runGit(["commit","-m",message],cwd),commitSp.succeed("Changes committed")}let remoteBranch=remote.branch,pushSp=spinner(`Pushing to fimo/${remoteBranch}`);try{await runGit(["push","fimo",`HEAD:${remoteBranch}`],cwd),pushSp.succeed("Pushed to Fimo")}catch(error){pushSp.fail("Push failed");let failure=classifyPushError(error);emitPushFailure(failure,remoteBranch);return}}finally{devFimoDependency?.restore()}let stepLabel="",stepStartedAt=0,stepSp=null,finalizeStep=__name((status="ok",failMessage)=>{if(!stepSp)return;let elapsed=((Date.now()-stepStartedAt)/1e3).toFixed(1);status==="ok"?stepSp.succeed(`${stepLabel} (${elapsed}s)`):stepSp.fail(failMessage??`${stepLabel} failed`),stepSp=null},"finalizeStep"),readiness;try{readiness=(await api.sandboxPull(local.projectId,({message})=>{finalizeStep("ok"),stepLabel=message,stepStartedAt=Date.now(),stepSp=spinner(message)},ctx.env,{noRestart:options.restart===!1,wait:options.wait!==!1})).readiness,finalizeStep("ok")}catch(error){if(rethrowCliAuthError(error,()=>finalizeStep("fail","Authentication required")),error instanceof SandboxReadinessError){finalizeStep("fail",`Preview did not become ready: ${errorMessage(error)}`),ui.error({command:"deploy",code:"PREVIEW_NOT_READY",message:`The revision was synced, but the preview never served a page: ${errorMessage(error)}`,hint:"Run `fimo logs` to see what the dev server reported, fix it, then deploy again. Pass --no-wait to deploy without this check."});return}finalizeStep("fail",`Sandbox sync failed: ${errorMessage(error)}`),ui.error({command:"deploy",code:"SANDBOX_SYNC_FAILED",message:`Sandbox sync failed: ${errorMessage(error)}`});return}await syncDisplayNameIfRenamed({cwd,projectId:local.projectId,api});let sandboxUrl=null,sandboxExpiresAt=null;if(previewEnabled)try{let preview=await api.getPreviewUrl(local.projectId,ctx.env);sandboxUrl=preview.url,sandboxExpiresAt=preview.expiresAt}catch(error){isPretty2&&O2.warn(`Could not fetch preview URL: ${errorMessage(error)}`)}if(!options.publish){ui.result({command:"deploy",data:{project_id:local.projectId,env:ctx.env,preview_enabled:previewEnabled,preview_url:previewEnabled?previewUrl:null,sandbox_url:sandboxUrl,sandbox_expires_at:sandboxExpiresAt,studio_url:studioUrl,dashboard_url:studioUrl,published:!1,...readinessData(readiness,ctx.env)},render:__name(context=>renderDeployResult({previewUrl:previewEnabled?previewUrl:null,studioUrl,appUrl:null,previewEnabled,published:!1,readiness,env:ctx.env},context),"render")});return}let publishSp=spinner("Publishing (this can take a few minutes)");try{await api.publishProject(local.projectId)}catch(error){rethrowCliAuthError(error,()=>publishSp.fail("Authentication required")),publishSp.fail()
|
|
1242
|
+
`),ctx.readOnly){ui.error({command:"deploy",code:"ENV_READONLY",message:`Refusing to deploy to read-only env '${ctx.env}'.`,hint:"Switch off the release/* tag or pass --env <writable-env>."});return}if(options.publish&&ctx.env!==DEFAULT_ENV){ui.error({command:"deploy",code:"PUBLISH_REQUIRES_DEFAULT_ENV",message:`Refusing to --publish from env '${ctx.env}'. Publish only runs from '${DEFAULT_ENV}'.`,hint:`Drop --publish to deploy a preview, or switch to '${DEFAULT_ENV}' first.`});return}let devFimoSelection;try{devFimoSelection=resolveDevFimoDependencyForDeploy(cwd)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}await requireOperation("fimo.deploy",{projectId:ctx.projectId,env:ctx.env});let cfg=loadConfig(),api=new FimoApiClient(cfg).withEnv(ctx.env),studioUrl=buildProjectPreviewUrl(cfg.webUrl,local.projectId,ctx.env),previewUrl=buildPreviewUrl(cfg.webUrl,local.projectId,ctx.env),previewEnabled=(await api.getProject(local.projectId)).previewEnabled!==!1,remoteSp=spinner("Checking the Fimo branch"),remote;try{remote=await api.getGitRemote(local.projectId,ctx.env),await ensureFimoRemote(cwd,remote.url);let preparation=await prepareDeployCheckout({cwd,remoteBranch:remote.branch});remoteSp.succeed(preparation==="missing-remote"?`Fimo branch ${remote.branch} will be created by this deploy`:`Checkout ready for fimo/${remote.branch}`)}catch(error){if(remoteSp.fail("Checkout is not ready to deploy"),error instanceof EnvironmentCheckoutError){ui.error({command:"deploy",code:error.code,message:error.message,hint:error.hint});return}rethrowCliAuthError(error),ui.error({command:"deploy",code:"ENV_GIT_PREFLIGHT_FAILED",message:`Could not compare this checkout with the Fimo branch: ${errorMessage(error)}`});return}let validateSp=spinner("Validating project"),report=await runValidate({cwd,envOverride:envOverride2}),packageManagerWarning=getPackageManagerPinWarning(cwd);if(packageManagerWarning&&ui.warn({command:"deploy",message:packageManagerWarning}),report.ok)validateSp.succeed("Validation passed");else if(options.force)validateSp.fail("Validation failed \u2014 continuing anyway (--force)"),ui.warn({command:"deploy",message:"Bypassing validation errors because --force was passed. The deploy may still fail later in the sandbox."});else{validateSp.fail("Validation failed"),ui.result({command:"deploy",data:{stage:"validate",report},render:__name(()=>formatReportHuman(report),"render")}),process.exitCode=report.exitCode;return}let devFimoDependency=null;try{devFimoDependency=prepareDevFimoDependencyForDeploy(cwd,devFimoSelection)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}devFimoDependency&&isPretty2&&O2.info(`Deploying with fimo ${devFimoDependency.version}; restoring local dependency state after push.`);try{if(await hasUncommittedChanges(cwd)){let message;if(options.message!==void 0)message=options.message;else{assertInteractive('Pass -m "<message>" or commit your changes manually.',"deploy"),isPretty2&&O2.warn("You have uncommitted changes. Commit them before deploying.");let answer=await Ot({message:"Commit message",placeholder:"Deploy",defaultValue:"Deploy"});if(q(answer)){ui.info({command:"deploy",message:"Cancelled."});return}message=String(answer)}let commitSp=spinner("Committing pending changes");await runGit(["add","-A"],cwd),await runGit(["commit","-m",message],cwd),commitSp.succeed("Changes committed")}let remoteBranch=remote.branch,pushSp=spinner(`Pushing to fimo/${remoteBranch}`);try{await runGit(["push","fimo",`HEAD:${remoteBranch}`],cwd),pushSp.succeed("Pushed to Fimo")}catch(error){pushSp.fail("Push failed");let failure=classifyPushError(error);emitPushFailure(failure,remoteBranch);return}}finally{devFimoDependency?.restore()}let stepLabel="",stepStartedAt=0,stepSp=null,finalizeStep=__name((status="ok",failMessage)=>{if(!stepSp)return;let elapsed=((Date.now()-stepStartedAt)/1e3).toFixed(1);status==="ok"?stepSp.succeed(`${stepLabel} (${elapsed}s)`):stepSp.fail(failMessage??`${stepLabel} failed`),stepSp=null},"finalizeStep"),readiness;try{readiness=(await api.sandboxPull(local.projectId,({message})=>{finalizeStep("ok"),stepLabel=message,stepStartedAt=Date.now(),stepSp=spinner(message)},ctx.env,{noRestart:options.restart===!1,wait:options.wait!==!1})).readiness,finalizeStep("ok")}catch(error){if(rethrowCliAuthError(error,()=>finalizeStep("fail","Authentication required")),error instanceof SandboxReadinessError){finalizeStep("fail",`Preview did not become ready: ${errorMessage(error)}`),ui.error({command:"deploy",code:"PREVIEW_NOT_READY",message:`The revision was synced, but the preview never served a page: ${errorMessage(error)}`,hint:"Run `fimo logs` to see what the dev server reported, fix it, then deploy again. Pass --no-wait to deploy without this check."});return}finalizeStep("fail",`Sandbox sync failed: ${errorMessage(error)}`),ui.error({command:"deploy",code:"SANDBOX_SYNC_FAILED",message:`Sandbox sync failed: ${errorMessage(error)}`});return}await syncDisplayNameIfRenamed({cwd,projectId:local.projectId,api});let sandboxUrl=null,sandboxExpiresAt=null;if(previewEnabled)try{let preview=await api.getPreviewUrl(local.projectId,ctx.env);sandboxUrl=preview.url,sandboxExpiresAt=preview.expiresAt}catch(error){isPretty2&&O2.warn(`Could not fetch preview URL: ${errorMessage(error)}`)}if(!options.publish){ui.result({command:"deploy",data:{project_id:local.projectId,env:ctx.env,preview_enabled:previewEnabled,preview_url:previewEnabled?previewUrl:null,sandbox_url:sandboxUrl,sandbox_expires_at:sandboxExpiresAt,studio_url:studioUrl,dashboard_url:studioUrl,published:!1,...readinessData(readiness,ctx.env)},render:__name(context=>renderDeployResult({previewUrl:previewEnabled?previewUrl:null,studioUrl,appUrl:null,previewEnabled,published:!1,readiness,env:ctx.env},context),"render")});return}let publishSp=spinner("Publishing (this can take a few minutes)"),publicationId;try{publicationId=await api.publishProject(local.projectId)}catch(error){rethrowCliAuthError(error,()=>publishSp.fail("Authentication required")),publishSp.fail();let failedPublicationId=publicationIdFromError(error);ui.error({command:"deploy",code:"PUBLISH_FAILED",message:`Publish failed: ${errorMessage(error)}`,...failedPublicationId?{details:{publication_id:failedPublicationId},hint:`Run \`fimo publish logs ${failedPublicationId}\` for the build output that failed.`}:{}});return}publishSp.succeed("Published");let appUrl=null;try{appUrl=(await api.getProject(local.projectId)).appUrl}catch(error){isPretty2&&O2.warn(`Could not fetch published URL: ${errorMessage(error)}`)}ui.result({command:"deploy",data:{project_id:local.projectId,env:ctx.env,preview_enabled:previewEnabled,preview_url:previewEnabled?previewUrl:null,sandbox_url:sandboxUrl,sandbox_expires_at:sandboxExpiresAt,studio_url:studioUrl,dashboard_url:studioUrl,published:!0,publication_id:publicationId,app_url:appUrl,...readinessData(readiness,ctx.env)},render:__name(context=>renderDeployResult({previewUrl:previewEnabled?previewUrl:null,studioUrl,appUrl,previewEnabled,published:!0,readiness,env:ctx.env},context),"render")})}__name(deployCommand,"deployCommand");function readinessData(readiness,env){return{readiness:readiness.status,readiness_reason:readiness.reason??null,readiness_env:env,readiness_path:readiness.path??null,readiness_ms:readiness.durationMs}}__name(readinessData,"readinessData");function renderDeployResult(result,context){let lines=[];return result.previewUrl&&lines.push(`Preview: ${terminalLink("Open preview",result.previewUrl,context.hyperlinks)}`),result.appUrl&&lines.push(`Live: ${terminalLink("Open site",result.appUrl,context.hyperlinks)}`),lines.push(`Studio: ${terminalLink("Open in Studio",result.studioUrl,context.hyperlinks)}`),lines.push(renderReadiness(result.readiness,result.env)),result.published?lines.push(result.appUrl?"Your site is live.":"Publish completed. Check Fimo for the live URL."):lines.push(result.previewEnabled?"Deployed to preview. Run `fimo deploy --publish` or `fimo publish` to publish a new version.":"Changes synced. Preview is disabled for this project."),lines.join(`
|
|
1243
1243
|
`)}__name(renderDeployResult,"renderDeployResult");function renderReadiness(readiness,env){let seconds=(readiness.durationMs/1e3).toFixed(1);if(readiness.status==="ready")return`Readiness: ${env} served ${readiness.path??"the preview"} in ${seconds}s.`;switch(readiness.reason){case"preview_disabled":return`Readiness: not checked on ${env}; preview is disabled for this project.`;case"not_reported":return`Readiness: not checked on ${env}; this Fimo API does not report it.`;default:return`Readiness: skipped on ${env} (--no-wait). The preview is not known to serve this revision.`}}__name(renderReadiness,"renderReadiness");function emitPushFailure(failure,env){switch(failure.kind){case"non-fast-forward":ui.error({command:"deploy",code:"PUSH_NON_FAST_FORWARD",message:`The remote \`fimo/${env}\` has commits your local branch does not.`,hint:`Fix it manually, then re-run \`fimo deploy\`:
|
|
1244
1244
|
1. git pull --rebase fimo ${env}
|
|
1245
1245
|
2. resolve any conflicts, then \`git add\` + \`git rebase --continue\`
|
|
@@ -1350,11 +1350,11 @@ Run \`fimo integrations <command> --help\` for command-specific help.
|
|
|
1350
1350
|
`);let removal="entriesDeleted"in response?` Deleted ${response.entriesDeleted} entr${response.entriesDeleted===1?"y":"ies"} and ${response.labelsDeleted} label${response.labelsDeleted===1?"":"s"}.`:"";return`${spec.verb} locale '${response.locale}' in '${env}'.${removal}
|
|
1351
1351
|
Remote config and local checkout are synchronized.`}__name(renderMutationResult,"renderMutationResult");async function runLocaleMutation(locale,options,cmd,spec){let command=`locales ${spec.operation}`;if(rejectMissingConfirmation(spec,options))return;let cwd=resolveProjectCwd(options.cwd),{ctx,api}=await bootstrapProjectCommand(options,cmd,{requireBranch:!0,refuseReadOnly:!0});await requireOperation(spec.capability,{projectId:ctx.projectId,env:ctx.env});let plan;try{let remote=await api.getGitRemote(ctx.projectId,ctx.env);await ensureFimoRemote(cwd,remote.url),plan=await planLocaleMutationCheckout({cwd,remoteBranch:remote.branch,configPath:resolveProjectConfigPath(cwd)})}catch(error){if(emitPreflightError(command,error)||emitApiError(command,error))return;throw error}if(!await confirmMutation(spec,locale,ctx.env,plan,options))return;try{await applyLocaleMutationCheckoutPlan(plan)}catch(error){if(emitPreflightError(command,error))return;throw error}let response;try{response=await spec.mutate(api,ctx.projectId,locale)}catch(error){if(emitApiError(command,error))return;throw error}let sync=await synchronizeLocaleMutationCheckout({cwd,remoteBranch:plan.state.remoteBranch}),data2={operation:spec.operation,env:ctx.env,applied:!0,...response,...sync.status==="required"?{code:"LOCALE_APPLIED_SYNC_REQUIRED"}:{},sync};ui.result({command,data:data2,render:__name(()=>renderMutationResult(spec,response,ctx.env,sync),"render")}),sync.status==="required"&&(process.exitCode=2)}__name(runLocaleMutation,"runLocaleMutation");async function localesAddCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"add",capability:"i18n.create",verb:"Add",destructive:!1,mutate:__name((api,projectId,value)=>api.addProjectLocale(projectId,{locale:value}),"mutate")})}__name(localesAddCommand,"localesAddCommand");async function localesSetDefaultCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"set-default",capability:"i18n.update",verb:"Set the default to",destructive:!1,mutate:__name((api,projectId,value)=>api.setProjectDefaultLocale(projectId,{locale:value}),"mutate")})}__name(localesSetDefaultCommand,"localesSetDefaultCommand");async function localesRemoveCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"remove",capability:"i18n.delete",verb:"Remove",destructive:!0,mutate:__name((api,projectId,value)=>api.removeProjectLocale(projectId,value),"mutate")})}__name(localesRemoveCommand,"localesRemoveCommand");function registerLocalesCommands(program2){let locales=program2.command("locales").description("Manage project locale lifecycle");locales.command("list").description("List configured locales and stored content coverage").option("-C, --cwd <dir>","Project directory").action(localesListCommand),locales.command("add <locale>").description("Add a locale to the selected Branch").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesAddCommand),locales.command("set-default <locale>").description("Set the default locale for the selected Branch").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesSetDefaultCommand),locales.command("remove <locale>").description("Remove a locale and permanently delete its stored content").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesRemoveCommand)}__name(registerLocalesCommands,"registerLocalesCommands");init_login();init_dist();init_auth();init_config();async function logoutCommand(){let cfg=loadConfig(),creds=readCredentials(cfg);if(!creds?.access_token){ui.info({command:"logout",message:"Already signed out."});return}clearCredentials(cfg),ui.ok({command:"logout",headline:`Signed out${creds.user?.email?` (${creds.user.email})`:""}.`,details:creds.user?.email?{email:creds.user.email}:void 0})}__name(logoutCommand,"logoutCommand");init_dist();init_project_context();var MAX_LIMIT=1e3;async function logsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("fimo.logs.read",{projectId:ctx.projectId,env:ctx.env});let limit;try{limit=parseLimit2(options.limit)}catch(error){ui.error({command:"logs",code:"LOGS_INVALID_LIMIT",message:errorMessage2(error)});return}let result;try{result=await api.getSandboxLogs(ctx.projectId,ctx.env,{limit,before:options.before})}catch(error){ui.error({command:"logs",code:"LOGS_REQUEST_FAILED",message:`Could not read sandbox logs: ${errorMessage2(error)}`});return}let data2={project_id:ctx.projectId,env:ctx.env,...result};if(result.status==="unavailable"){let{message}=result;ui.result({command:"logs",data:data2,render:__name(()=>message,"render")});return}let page=result,hint=page.previousCursor?buildOlderHint(page.previousCursor,ctx.env,options):void 0;ui.result({command:"logs",data:data2,render:__name(()=>renderLogs(page,ctx.env),"render"),...hint?{hint}:{}})}__name(logsCommand,"logsCommand");function parseLimit2(value){if(value===void 0)return;let limit=Number(value);if(!Number.isInteger(limit)||limit<1||limit>MAX_LIMIT)throw new Error(`--limit must be an integer between 1 and ${MAX_LIMIT}.`);return limit}__name(parseLimit2,"parseLimit");function renderLogs(page,env){let lines=[],count=page.events.length;lines.push(`${env}: ${count} ${count===1?"event":"events"}${page.truncated?" (older ones remain)":""}`);for(let phase of page.retention.phases)lines.push(` ${renderPhase(phase)}`);if(page.retention.droppedOldest&&lines.push(" Note: the sandbox buffer dropped its oldest lines; they cannot be paged back to."),count===0)return lines.push(""),lines.push("No output recorded for these phases yet."),lines.join(`
|
|
1352
1352
|
`);lines.push("");let width=Math.max(...page.events.map(event=>event.source.length));for(let event of[...page.events].reverse())lines.push(`${event.source.padEnd(width)} ${event.message}`);return lines.join(`
|
|
1353
|
-
`)}__name(renderLogs,"renderLogs");function renderPhase(phase){let parts=[phase.status];return phase.exitCode!==null&&parts.push(`exit ${phase.exitCode}`),phase.startedAt&&parts.push(`started ${phase.startedAt}`),parts.push(`${phase.events} ${phase.events===1?"line":"lines"}`),`${phase.phase}: ${parts.join(", ")}`}__name(renderPhase,"renderPhase");function buildOlderHint(cursor,env,options){let args=["fimo","logs","--branch",env,"--before",cursor];return options.limit&&args.push("--limit",options.limit),options.cwd&&args.push("--cwd",options.cwd),`Older: ${args.map(quoteArgument).join(" ")}`}__name(buildOlderHint,"buildOlderHint");function quoteArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteArgument,"quoteArgument");function errorMessage2(error){return error instanceof Error?error.message:String(error)}__name(errorMessage2,"errorMessage");init_esm();import{z as z75}from"zod";var projectScopeShape={projectId:z75.uuid().optional().describe("The Fimo project ID. Optional when the MCP server is already bound to a project.")},envScopeShape={...projectScopeShape,env:EnvSchema.optional().describe("The environment name, for example 'main' or 'agents/content-review'. Optional when the server is bound to an environment.")},typeNameField=z75.string().min(1).max(255).describe("The content type name, for example BlogPost."),localeField=z75.string().min(1).optional().describe("The locale to read or write."),entryDataField=z75.record(z75.string(),z75.unknown()).describe("Entry field values, keyed by field name as declared in the content schema."),filePathField=z75.string().min(1).max(1024).describe("File path relative to the project root."),labelKeyField=z75.string().min(1).max(255).describe("The translation key, for example home.hero.title."),assetIdField=z75.uuid().describe("The Fimo media asset ID."),formIdField=z75.string().min(1).max(255).describe("The Fimo form ID."),formFieldsField=z75.record(z75.string().min(1),z75.unknown()).describe("Form fields keyed by field name; Fimo validates each field definition."),formContentShape={name:z75.string().min(1).max(255).describe("Stable form name."),label:z75.string().min(1).max(255).describe("Human-readable form label."),fields:formFieldsField},mediaGenerationSchema=z75.object({...envScopeShape,task:z75.string().min(1).optional().describe("A stable task, for example 'image.generate' or 'video.generate'."),model:z75.string().min(1).optional().describe("An explicit model ID, for example 'fal/...'."),options:z75.record(z75.string(),z75.unknown()).describe("Task or model options, such as prompt, quality, aspect ratio, and source assets."),name:z75.string().min(1).max(255).optional().describe("Optional name for the generated asset."),parentId:z75.uuid().nullable().optional().describe("Optional media-library folder ID."),altText:z75.string().max(2e3).optional().describe("Optional alternative text for the generated asset."),caption:z75.string().max(2e3).optional().describe("Optional caption for the generated asset.")}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})});function tenantPath(scope,suffix){return`/tenant/${encodeURIComponent(scope.projectId)}/envs/${encodeEnvPathSegment(scope.env)}${suffix}`}__name(tenantPath,"tenantPath");function managementProjectPath(scope,suffix){return`/management/projects/${encodeURIComponent(scope.projectId)}${suffix}`}__name(managementProjectPath,"managementProjectPath");function managementEnvPath(scope,suffix){return managementProjectPath(scope,`/envs/${encodeURIComponent(scope.env)}${suffix}`)}__name(managementEnvPath,"managementEnvPath");function addQuery(path50,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))if(value!==void 0){if(Array.isArray(value)){value.length>0&¶ms.set(key,value.join(","));continue}params.set(key,String(value))}let queryString=params.toString();return queryString?`${path50}?${queryString}`:path50}__name(addQuery,"addQuery");var mcpToolCatalog={whoami:{description:"Return the authenticated Fimo user identity.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z75.object({})},projects_list:{description:"List the Fimo projects the authenticated user can access.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z75.object({}),buildRequest:__name(()=>({method:"GET",path:"/management/projects"}),"buildRequest")},envs_list:{description:"List the environments of a project.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z75.object(projectScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementProjectPath(scope,"/envs")}),"buildRequest")},schemas_list:{description:"List content schemas in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.schema.list",inputSchema:z75.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/schema")}),"buildRequest")},entries_list:{description:"List entries for one content type in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,locale:localeField,limit:z75.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z75.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),{locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_get:{description:"Read one entry by ID from a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,id:z75.uuid().describe("The entry ID."),locale:localeField,populate:z75.array(z75.string().min(1)).max(50).optional().describe("Reference fields to populate."),localeFallbacks:z75.boolean().optional().describe("Use the configured default locale when needed.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale,populate:input.populate,localeFallbacks:input.localeFallbacks})}),"buildRequest")},entries_search:{description:"Search entries across content types in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z75.object({...envScopeShape,search:z75.string().min(1).optional().describe("A text search applied to entry content."),locale:localeField,limit:z75.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z75.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/entries"),{search:input.search,locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_create:{description:"Create one entry of a content type in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.create",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField,documentId:z75.string().min(1).optional().describe("Attach the new entry to an existing document (adds a locale variant).")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),body:{data:input.data,locale:input.locale,documentId:input.documentId}}),"buildRequest")},entries_update:{description:"Update one entry by ID in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,id:z75.uuid().describe("The entry ID."),data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},entries_delete:{description:"Delete one entry by ID in a project environment.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.delete",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,id:z75.uuid().describe("The entry ID."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale})}),"buildRequest")},entries_bulk_create:{description:`Create up to ${MAX_BULK_ENTRIES} entries of one content type in a project environment.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_create",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,entries:z75.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES).describe("Entries to create.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-create`),body:{entries:input.entries}}),"buildRequest")},entries_bulk_update:{description:`Update up to ${MAX_BULK_ENTRIES} entries by IDs, a bounded filter, or per-entry updates.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_update",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,selection:z75.union([z75.object({ids:z75.array(z75.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z75.object({where:EntryWhereSchema}),z75.object({updates:z75.array(z75.object({id:z75.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),body:EntryMutationBodySchema.optional().describe("Shared update body for ids or where selections.")}).superRefine((value,context)=>{let isPerEntry="updates"in value.selection;isPerEntry&&value.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!isPerEntry&&value.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),buildRequest:__name((input,scope)=>{let{selection,body}=input;return{method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}},"buildRequest")},entries_bulk_delete:{description:`Delete up to ${MAX_BULK_ENTRIES} entries by IDs or a bounded filter.`,annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.bulk_delete",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,selection:z75.union([z75.object({ids:z75.array(z75.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z75.object({where:EntryWhereSchema})]),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-delete`),body:{...input.selection,locale:input.locale}}),"buildRequest")},singles_get:{description:"Read the document-scoped value of a Single content type.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,locale:localeField,populate:z75.array(z75.string().min(1)).max(50).optional().describe("Reference fields to populate.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale,populate:input.populate})}),"buildRequest")},singles_update:{description:"Update the document-scoped value of a Single content type.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},labels_list:{description:'List localized labels in a project environment. Pass locale "*" to group all locales.',annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.list",inputSchema:z75.object({...envScopeShape,locale:z75.string().min(1).optional().describe('Locale code, or "*" for every configured locale.')}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/labels"),{locale:input.locale})}),"buildRequest")},labels_get:{description:"Read one localized label by locale and key.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.get",inputSchema:z75.object({...envScopeShape,locale:z75.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},labels_set:{description:"Create or set one localized label.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.create",inputSchema:z75.object({...envScopeShape,key:labelKeyField,value:z75.string().max(1e4).describe("Localized label text."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels"),body:{key:input.key,value:input.value,locale:input.locale}}),"buildRequest")},labels_set_many:{description:"Set many localized labels in one bounded request.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.update",inputSchema:z75.object({...envScopeShape,records:z75.array(z75.object({key:labelKeyField,value:z75.string().max(1e4),locale:localeField})).min(1).max(500).describe("Localized labels to set.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels/sync"),body:{created:input.records,updated:[],deleted:[]}}),"buildRequest")},labels_delete:{description:"Delete one localized label.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"i18n.delete",inputSchema:z75.object({...envScopeShape,locale:z75.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},assets_list:{description:"List media assets and folders, including public URLs for files the user can access.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.list",inputSchema:z75.object({...envScopeShape,parentId:z75.uuid().optional().describe("Limit results to one media-library folder."),search:z75.string().max(200).optional(),type:z75.enum(["file","folder"]).optional(),mimePrefix:z75.string().max(50).optional().describe("MIME prefix such as image/ or video/."),sortBy:z75.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z75.enum(["asc","desc"]).optional(),includePath:z75.boolean().optional(),excludeHidden:z75.boolean().optional(),limit:z75.number().int().min(1).max(100).optional(),offset:z75.number().int().min(0).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/assets"),{parentId:input.parentId,search:input.search,type:input.type,mimePrefix:input.mimePrefix,sortBy:input.sortBy,sortDirection:input.sortDirection,includePath:input.includePath,excludeHidden:input.excludeHidden,limit:input.limit,offset:input.offset})}),"buildRequest")},assets_get:{description:"Read one media asset or folder, including its public URL when it is a file.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.get",inputSchema:z75.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},assets_generate:{description:"Generate an image or video asset with Fimo AI credits and save it to the media library.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.generate",inputSchema:mediaGenerationSchema,buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/generate"),body:{...input.task?{task:input.task}:{model:input.model},options:input.options,name:input.name,parentId:input.parentId,altText:input.altText,caption:input.caption}}),"buildRequest")},assets_create_folder:{description:"Create a media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.create_folder",inputSchema:z75.object({...envScopeShape,name:z75.string().min(1).max(255).describe("Folder name."),parentId:z75.uuid().nullable().optional().describe("Optional parent folder ID.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/folders"),body:{name:input.name,parentId:input.parentId}}),"buildRequest")},assets_move:{description:"Move a media asset or folder to another media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.move",inputSchema:z75.object({...envScopeShape,id:assetIdField,parentId:z75.uuid().nullable().describe("Destination folder ID, or null for the library root.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}/move`),body:{parentId:input.parentId}}),"buildRequest")},assets_delete:{description:"Delete a media asset or folder.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"assets.delete",inputSchema:z75.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_list:{description:"List the forms configured in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z75.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/forms")}),"buildRequest")},forms_get:{description:"Read one form definition.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z75.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_create:{description:"Create a form definition. Email notification settings stay in the Fimo UI.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z75.object({...envScopeShape,...formContentShape}).strict(),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/forms"),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_update:{description:"Update the name, label, or fields of one form definition.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z75.object({...envScopeShape,id:formIdField,...z75.object(formContentShape).partial().shape}).strict(),buildRequest:__name((input,scope)=>({method:"PUT",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_delete:{description:"Delete one form definition.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"forms.delete",inputSchema:z75.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_submissions_list:{description:"List submissions for one form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z75.object({...envScopeShape,id:formIdField,limit:z75.number().int().min(1).max(100).optional(),offset:z75.number().int().min(0).optional(),searchQuery:z75.string().max(200).optional(),sortDirection:z75.enum(["asc","desc"]).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions`),{limit:input.limit,offset:input.offset,searchQuery:input.searchQuery,sortDirection:input.sortDirection})}),"buildRequest")},forms_submission_get:{description:"Read one submission for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z75.object({...envScopeShape,id:formIdField,submissionId:z75.string().min(1).max(255).describe("The submission ID.")}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/${encodeURIComponent(input.submissionId)}`)}),"buildRequest")},forms_submissions_stats:{description:"Read aggregate submission statistics for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z75.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/stats`)}),"buildRequest")},files_read:{description:"Read one project file from an environment. Hidden and sensitive files (.env, credentials, keys, lockfiles, .git, build output) are unavailable.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z75.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/file"),{path:input.path})}),"buildRequest")},files_glob:{description:"List project file paths in an environment, optionally filtered by a glob pattern.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z75.object({...envScopeShape,pattern:z75.string().min(1).max(300).optional().describe("Glob pattern, for example 'src/**/*.tsx'."),limit:z75.number().int().min(1).max(2e3).optional().describe("Maximum number of paths to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/paths"),{pattern:input.pattern,limit:input.limit})}),"buildRequest")},files_grep:{description:"Search project file contents in an environment with a regular expression. Matching is bounded (file count, bytes, match count) and complex patterns that exceed the time budget are rejected.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z75.object({...envScopeShape,pattern:z75.string().min(1).max(200).describe("Regular expression to search for."),include:z75.string().min(1).max(300).optional().describe("Glob pattern limiting which files are searched."),caseInsensitive:z75.boolean().optional().describe("Case-insensitive matching."),maxMatches:z75.number().int().min(1).max(200).optional().describe("Maximum number of matches to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/grep"),{pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.maxMatches})}),"buildRequest")},files_write:{description:"Create one project text file, or overwrite an existing one when overwrite is set. Fails if the file exists and overwrite is not set. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z75.object({...envScopeShape,path:filePathField,content:z75.string().max(262144).describe("Full UTF-8 text content of the file (256 KB max)."),overwrite:z75.boolean().optional().describe("Replace the file if it already exists. Without it, writing an existing path fails.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/write"),body:{path:input.path,content:input.content,overwrite:input.overwrite}}),"buildRequest")},files_edit:{description:"Edit one project file by exact string replacement. The old string must exist; set replaceAll when it occurs more than once. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z75.object({...envScopeShape,path:filePathField,oldString:z75.string().min(1).describe("Exact text to replace."),newString:z75.string().describe("Replacement text."),replaceAll:z75.boolean().optional().describe("Replace every occurrence instead of requiring a unique one.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/edit"),body:{path:input.path,oldString:input.oldString,newString:input.newString,replaceAll:input.replaceAll}}),"buildRequest")},files_delete:{description:"Delete one project file in an environment. The deletion lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z75.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/delete"),body:{path:input.path}}),"buildRequest")},agents_list:{description:"List the agent bundles declared in a project environment, with triggers and activations.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",inputSchema:z75.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementEnvPath(scope,"/agents")}),"buildRequest")},agents_run:{description:"Trigger a manual run of a project agent. Returns a durable session ID; poll agents_status for progress. The agent executes in the managed project sandbox under its declared capabilities.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"agents",operation:"agent.delegate",inputSchema:z75.object({...envScopeShape,agentName:z75.string().min(1).max(120).describe("The agent bundle name."),args:z75.record(z75.string(),z75.unknown()).optional().describe("Arguments passed to the agent run.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,`/agents/${encodeURIComponent(input.agentName)}/run`),body:input.args===void 0?{}:{args:input.args}}),"buildRequest")},agents_status:{description:"Read one agent session (status, report, checkpoints) by session ID.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z75.object({...projectScopeShape,sessionId:z75.uuid().describe("The agent session ID returned by agents_run.")}),buildRequest:__name((input,scope)=>({method:"GET",path:managementProjectPath(scope,`/agents/sessions/${encodeURIComponent(input.sessionId)}`)}),"buildRequest")}},mcpToolNames=Object.keys(mcpToolCatalog);import*as z3rt from"zod/v3";import*as z4mini from"zod/v4-mini";function isZ4Schema(s){return!!s._zod}__name(isZ4Schema,"isZ4Schema");function objectFromShape(shape){let values=Object.values(shape);if(values.length===0)return z4mini.object({});let allV4=values.every(isZ4Schema),allV3=values.every(s=>!isZ4Schema(s));if(allV4)return z4mini.object(shape);if(allV3)return z3rt.object(shape);throw new Error("Mixed Zod versions detected in object shape.")}__name(objectFromShape,"objectFromShape");function safeParse3(schema,data2){return isZ4Schema(schema)?z4mini.safeParse(schema,data2):schema.safeParse(data2)}__name(safeParse3,"safeParse");async function safeParseAsync2(schema,data2){return isZ4Schema(schema)?await z4mini.safeParseAsync(schema,data2):await schema.safeParseAsync(data2)}__name(safeParseAsync2,"safeParseAsync");function getObjectShape(schema){if(!schema)return;let rawShape;if(isZ4Schema(schema)?rawShape=schema._zod?.def?.shape:rawShape=schema.shape,!!rawShape){if(typeof rawShape=="function")try{return rawShape()}catch{return}return rawShape}}__name(getObjectShape,"getObjectShape");function normalizeObjectSchema(schema){if(schema){if(typeof schema=="object"){let asV3=schema,asV4=schema;if(!asV3._def&&!asV4._zod){let values=Object.values(schema);if(values.length>0&&values.every(v=>typeof v=="object"&&v!==null&&(v._def!==void 0||v._zod!==void 0||typeof v.parse=="function")))return objectFromShape(schema)}}if(isZ4Schema(schema)){let def=schema._zod?.def;if(def&&(def.type==="object"||def.shape!==void 0))return schema}else if(schema.shape!==void 0)return schema}}__name(normalizeObjectSchema,"normalizeObjectSchema");function getParseErrorMessage(error){if(error&&typeof error=="object"){if("message"in error&&typeof error.message=="string")return error.message;if("issues"in error&&Array.isArray(error.issues)&&error.issues.length>0){let firstIssue=error.issues[0];if(firstIssue&&typeof firstIssue=="object"&&"message"in firstIssue)return String(firstIssue.message)}try{return JSON.stringify(error)}catch{return String(error)}}return String(error)}__name(getParseErrorMessage,"getParseErrorMessage");function getSchemaDescription(schema){return schema.description}__name(getSchemaDescription,"getSchemaDescription");function isSchemaOptional(schema){if(isZ4Schema(schema))return schema._zod?.def?.type==="optional";let v3Schema=schema;return typeof schema.isOptional=="function"?schema.isOptional():v3Schema._def?.typeName==="ZodOptional"}__name(isSchemaOptional,"isSchemaOptional");function getLiteralValue(schema){if(isZ4Schema(schema)){let def2=schema._zod?.def;if(def2){if(def2.value!==void 0)return def2.value;if(Array.isArray(def2.values)&&def2.values.length>0)return def2.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue}__name(getLiteralValue,"getLiteralValue");import*as z76 from"zod/v4";var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=z76.custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=z76.union([z76.string(),z76.number().int()]),CursorSchema=z76.string(),TaskCreationParamsSchema=z76.looseObject({ttl:z76.union([z76.number(),z76.null()]).optional(),pollInterval:z76.number().optional()}),TaskMetadataSchema=z76.object({ttl:z76.number().optional()}),RelatedTaskMetadataSchema=z76.object({taskId:z76.string()}),RequestMetaSchema=z76.looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=z76.object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=__name(value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,"isTaskAugmentedRequestParams"),RequestSchema=z76.object({method:z76.string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=z76.object({_meta:RequestMetaSchema.optional()}),NotificationSchema=z76.object({method:z76.string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=z76.looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=z76.union([z76.string(),z76.number().int()]),JSONRPCRequestSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=__name(value=>JSONRPCRequestSchema.safeParse(value).success,"isJSONRPCRequest"),JSONRPCNotificationSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=__name(value=>JSONRPCNotificationSchema.safeParse(value).success,"isJSONRPCNotification"),JSONRPCResultResponseSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=__name(value=>JSONRPCResultResponseSchema.safeParse(value).success,"isJSONRPCResultResponse");var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:z76.object({code:z76.number().int(),message:z76.string(),data:z76.unknown().optional()})}).strict();var isJSONRPCErrorResponse=__name(value=>JSONRPCErrorResponseSchema.safeParse(value).success,"isJSONRPCErrorResponse");var JSONRPCMessageSchema=z76.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=z76.union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:z76.string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=z76.object({src:z76.string(),mimeType:z76.string().optional(),sizes:z76.array(z76.string()).optional(),theme:z76.enum(["light","dark"]).optional()}),IconsSchema=z76.object({icons:z76.array(IconSchema).optional()}),BaseMetadataSchema=z76.object({name:z76.string(),title:z76.string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:z76.string(),websiteUrl:z76.string().optional(),description:z76.string().optional()}),FormElicitationCapabilitySchema=z76.intersection(z76.object({applyDefaults:z76.boolean().optional()}),z76.record(z76.string(),z76.unknown())),ElicitationCapabilitySchema=z76.preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,z76.intersection(z76.object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),z76.record(z76.string(),z76.unknown()).optional())),ClientTasksCapabilitySchema=z76.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z76.looseObject({sampling:z76.looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:z76.looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=z76.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z76.looseObject({tools:z76.looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=z76.object({experimental:z76.record(z76.string(),AssertObjectSchema).optional(),sampling:z76.object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:z76.object({listChanged:z76.boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:z76.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:z76.literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=z76.object({experimental:z76.record(z76.string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:z76.object({listChanged:z76.boolean().optional()}).optional(),resources:z76.object({subscribe:z76.boolean().optional(),listChanged:z76.boolean().optional()}).optional(),tools:z76.object({listChanged:z76.boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:z76.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z76.string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:z76.literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=z76.object({progress:z76.number(),total:z76.optional(z76.number()),message:z76.optional(z76.string())}),ProgressNotificationParamsSchema=z76.object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=z76.enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=z76.object({taskId:z76.string(),status:TaskStatusSchema,ttl:z76.union([z76.number(),z76.null()]),createdAt:z76.string(),lastUpdatedAt:z76.string(),pollInterval:z76.optional(z76.number()),statusMessage:z76.optional(z76.string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:z76.literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:z76.string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:z76.literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:z76.string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:z76.array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:z76.literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:z76.string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=z76.object({uri:z76.string(),mimeType:z76.optional(z76.string()),_meta:z76.record(z76.string(),z76.unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z76.string()}),Base64Schema=z76.string().refine(val2=>{try{return atob(val2),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=z76.enum(["user","assistant"]),AnnotationsSchema=z76.object({audience:z76.array(RoleSchema).optional(),priority:z76.number().min(0).max(1).optional(),lastModified:z76.iso.datetime({offset:!0}).optional()}),ResourceSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:z76.string(),description:z76.optional(z76.string()),mimeType:z76.optional(z76.string()),annotations:AnnotationsSchema.optional(),_meta:z76.optional(z76.looseObject({}))}),ResourceTemplateSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:z76.string(),description:z76.optional(z76.string()),mimeType:z76.optional(z76.string()),annotations:AnnotationsSchema.optional(),_meta:z76.optional(z76.looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z76.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z76.array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:z76.string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:z76.literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:z76.array(z76.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:z76.literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:z76.literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:z76.string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=z76.object({name:z76.string(),description:z76.optional(z76.string()),required:z76.optional(z76.boolean())}),PromptSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z76.optional(z76.string()),arguments:z76.optional(z76.array(PromptArgumentSchema)),_meta:z76.optional(z76.looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z76.array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:z76.string(),arguments:z76.record(z76.string(),z76.string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:z76.literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=z76.object({type:z76.literal("text"),text:z76.string(),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ImageContentSchema=z76.object({type:z76.literal("image"),data:Base64Schema,mimeType:z76.string(),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),AudioContentSchema=z76.object({type:z76.literal("audio"),data:Base64Schema,mimeType:z76.string(),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ToolUseContentSchema=z76.object({type:z76.literal("tool_use"),name:z76.string(),id:z76.string(),input:z76.record(z76.string(),z76.unknown()),_meta:z76.record(z76.string(),z76.unknown()).optional()}),EmbeddedResourceSchema=z76.object({type:z76.literal("resource"),resource:z76.union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:z76.literal("resource_link")}),ContentBlockSchema=z76.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z76.object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:z76.string().optional(),messages:z76.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=z76.object({title:z76.string().optional(),readOnlyHint:z76.boolean().optional(),destructiveHint:z76.boolean().optional(),idempotentHint:z76.boolean().optional(),openWorldHint:z76.boolean().optional()}),ToolExecutionSchema=z76.object({taskSupport:z76.enum(["required","optional","forbidden"]).optional()}),ToolSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z76.string().optional(),inputSchema:z76.object({type:z76.literal("object"),properties:z76.record(z76.string(),AssertObjectSchema).optional(),required:z76.array(z76.string()).optional()}).catchall(z76.unknown()),outputSchema:z76.object({type:z76.literal("object"),properties:z76.record(z76.string(),AssertObjectSchema).optional(),required:z76.array(z76.string()).optional()}).catchall(z76.unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z76.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z76.array(ContentBlockSchema).default([]),structuredContent:z76.record(z76.string(),z76.unknown()).optional(),isError:z76.boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:z76.unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:z76.string(),arguments:z76.record(z76.string(),z76.unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:z76.literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=z76.object({autoRefresh:z76.boolean().default(!0),debounceMs:z76.number().int().nonnegative().default(300)}),LoggingLevelSchema=z76.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:z76.literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:z76.string().optional(),data:z76.unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=z76.object({name:z76.string().optional()}),ModelPreferencesSchema=z76.object({hints:z76.array(ModelHintSchema).optional(),costPriority:z76.number().min(0).max(1).optional(),speedPriority:z76.number().min(0).max(1).optional(),intelligencePriority:z76.number().min(0).max(1).optional()}),ToolChoiceSchema=z76.object({mode:z76.enum(["auto","required","none"]).optional()}),ToolResultContentSchema=z76.object({type:z76.literal("tool_result"),toolUseId:z76.string().describe("The unique identifier for the corresponding tool call."),content:z76.array(ContentBlockSchema).default([]),structuredContent:z76.object({}).loose().optional(),isError:z76.boolean().optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),SamplingContentSchema=z76.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=z76.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=z76.object({role:RoleSchema,content:z76.union([SamplingMessageContentBlockSchema,z76.array(SamplingMessageContentBlockSchema)]),_meta:z76.record(z76.string(),z76.unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:z76.array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:z76.string().optional(),includeContext:z76.enum(["none","thisServer","allServers"]).optional(),temperature:z76.number().optional(),maxTokens:z76.number().int(),stopSequences:z76.array(z76.string()).optional(),metadata:AssertObjectSchema.optional(),tools:z76.array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:z76.literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:z76.string(),stopReason:z76.optional(z76.enum(["endTurn","stopSequence","maxTokens"]).or(z76.string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:z76.string(),stopReason:z76.optional(z76.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(z76.string())),role:RoleSchema,content:z76.union([SamplingMessageContentBlockSchema,z76.array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=z76.object({type:z76.literal("boolean"),title:z76.string().optional(),description:z76.string().optional(),default:z76.boolean().optional()}),StringSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),minLength:z76.number().optional(),maxLength:z76.number().optional(),format:z76.enum(["email","uri","date","date-time"]).optional(),default:z76.string().optional()}),NumberSchemaSchema=z76.object({type:z76.enum(["number","integer"]),title:z76.string().optional(),description:z76.string().optional(),minimum:z76.number().optional(),maximum:z76.number().optional(),default:z76.number().optional()}),UntitledSingleSelectEnumSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),enum:z76.array(z76.string()),default:z76.string().optional()}),TitledSingleSelectEnumSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),oneOf:z76.array(z76.object({const:z76.string(),title:z76.string()})),default:z76.string().optional()}),LegacyTitledEnumSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),enum:z76.array(z76.string()),enumNames:z76.array(z76.string()).optional(),default:z76.string().optional()}),SingleSelectEnumSchemaSchema=z76.union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=z76.object({type:z76.literal("array"),title:z76.string().optional(),description:z76.string().optional(),minItems:z76.number().optional(),maxItems:z76.number().optional(),items:z76.object({type:z76.literal("string"),enum:z76.array(z76.string())}),default:z76.array(z76.string()).optional()}),TitledMultiSelectEnumSchemaSchema=z76.object({type:z76.literal("array"),title:z76.string().optional(),description:z76.string().optional(),minItems:z76.number().optional(),maxItems:z76.number().optional(),items:z76.object({anyOf:z76.array(z76.object({const:z76.string(),title:z76.string()}))}),default:z76.array(z76.string()).optional()}),MultiSelectEnumSchemaSchema=z76.union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=z76.union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=z76.union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z76.literal("form").optional(),message:z76.string(),requestedSchema:z76.object({type:z76.literal("object"),properties:z76.record(z76.string(),PrimitiveSchemaDefinitionSchema),required:z76.array(z76.string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z76.literal("url"),message:z76.string(),elicitationId:z76.string(),url:z76.string().url()}),ElicitRequestParamsSchema=z76.union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:z76.literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:z76.string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:z76.enum(["accept","decline","cancel"]),content:z76.preprocess(val2=>val2===null?void 0:val2,z76.record(z76.string(),z76.union([z76.string(),z76.number(),z76.boolean(),z76.array(z76.string())])).optional())}),ResourceTemplateReferenceSchema=z76.object({type:z76.literal("ref/resource"),uri:z76.string()});var PromptReferenceSchema=z76.object({type:z76.literal("ref/prompt"),name:z76.string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:z76.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z76.object({name:z76.string(),value:z76.string()}),context:z76.object({arguments:z76.record(z76.string(),z76.string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:z76.literal("completion/complete"),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}__name(assertCompleteRequestPrompt,"assertCompleteRequestPrompt");function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}__name(assertCompleteRequestResourceTemplate,"assertCompleteRequestResourceTemplate");var CompleteResultSchema=ResultSchema.extend({completion:z76.looseObject({values:z76.array(z76.string()).max(100),total:z76.optional(z76.number().int()),hasMore:z76.optional(z76.boolean())})}),RootSchema=z76.object({uri:z76.string().startsWith("file://"),name:z76.string().optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:z76.literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:z76.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=z76.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=z76.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=z76.union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=z76.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=z76.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=z76.union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{static{__name(this,"McpError")}constructor(code2,message,data2){super(`MCP error ${code2}: ${message}`),this.code=code2,this.data=data2,this.name="McpError"}static fromError(code2,message,data2){if(code2===ErrorCode.UrlElicitationRequired&&data2){let errorData=data2;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code2,message,data2)}},UrlElicitationRequiredError=class extends McpError{static{__name(this,"UrlElicitationRequiredError")}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}__name(isTerminal,"isTerminal");import*as z4mini2 from"zod/v4-mini";var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");var defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=__name(options=>typeof options=="string"?{...defaultOptions,name:options}:{...defaultOptions,...options},"getDefaultOptions");var getRefs=__name(options=>{let _options=getDefaultOptions(options),currentPath=_options.name!==void 0?[..._options.basePath,_options.definitionPath,_options.name]:_options.basePath;return{..._options,flags:{hasReferencedOpenAiAnyType:!1},currentPath,propertyPath:void 0,seen:new Map(Object.entries(_options.definitions).map(([name,def])=>[def._def,{def:def._def,path:[..._options.basePath,_options.definitionPath,name],jsonSchema:void 0}]))}},"getRefs");function addErrorMessage(res,key,errorMessage4,refs){refs?.errorMessages&&errorMessage4&&(res.errorMessage={...res.errorMessage,[key]:errorMessage4})}__name(addErrorMessage,"addErrorMessage");function setResponseValueAndErrors(res,key,value,errorMessage4,refs){res[key]=value,addErrorMessage(res,key,errorMessage4,refs)}__name(setResponseValueAndErrors,"setResponseValueAndErrors");var getRelativePath=__name((pathA,pathB)=>{let i=0;for(;i<pathA.length&&i<pathB.length&&pathA[i]===pathB[i];i++);return[(pathA.length-i).toString(),...pathB.slice(i)].join("/")},"getRelativePath");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3}from"zod/v3";function parseAnyDef(refs){if(refs.target!=="openAi")return{};let anyDefinitionPath=[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName];return refs.flags.hasReferencedOpenAiAnyType=!0,{$ref:refs.$refStrategy==="relative"?getRelativePath(anyDefinitionPath,refs.currentPath):anyDefinitionPath.join("/")}}__name(parseAnyDef,"parseAnyDef");import{ZodFirstPartyTypeKind}from"zod/v3";function parseArrayDef(def,refs){let res={type:"array"};return def.type?._def&&def.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(res.items=parseDef(def.type._def,{...refs,currentPath:[...refs.currentPath,"items"]})),def.minLength&&setResponseValueAndErrors(res,"minItems",def.minLength.value,def.minLength.message,refs),def.maxLength&&setResponseValueAndErrors(res,"maxItems",def.maxLength.value,def.maxLength.message,refs),def.exactLength&&(setResponseValueAndErrors(res,"minItems",def.exactLength.value,def.exactLength.message,refs),setResponseValueAndErrors(res,"maxItems",def.exactLength.value,def.exactLength.message,refs)),res}__name(parseArrayDef,"parseArrayDef");function parseBigintDef(def,refs){let res={type:"integer",format:"int64"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseBigintDef,"parseBigintDef");function parseBooleanDef(){return{type:"boolean"}}__name(parseBooleanDef,"parseBooleanDef");function parseBrandedDef(_def,refs){return parseDef(_def.type._def,refs)}__name(parseBrandedDef,"parseBrandedDef");var parseCatchDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseCatchDef");function parseDateDef(def,refs,overrideDateStrategy){let strategy=overrideDateStrategy??refs.dateStrategy;if(Array.isArray(strategy))return{anyOf:strategy.map((item,i)=>parseDateDef(def,refs,item))};switch(strategy){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(def,refs)}}__name(parseDateDef,"parseDateDef");var integerDateParser=__name((def,refs)=>{let res={type:"integer",format:"unix-time"};if(refs.target==="openApi3")return res;for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minimum",check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maximum",check.value,check.message,refs);break}return res},"integerDateParser");function parseDefaultDef(_def,refs){return{...parseDef(_def.innerType._def,refs),default:_def.defaultValue()}}__name(parseDefaultDef,"parseDefaultDef");function parseEffectsDef(_def,refs){return refs.effectStrategy==="input"?parseDef(_def.schema._def,refs):parseAnyDef(refs)}__name(parseEffectsDef,"parseEffectsDef");function parseEnumDef(def){return{type:"string",enum:Array.from(def.values)}}__name(parseEnumDef,"parseEnumDef");var isJsonSchema7AllOfType=__name(type=>"type"in type&&type.type==="string"?!1:"allOf"in type,"isJsonSchema7AllOfType");function parseIntersectionDef(def,refs){let allOf=[parseDef(def.left._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),parseDef(def.right._def,{...refs,currentPath:[...refs.currentPath,"allOf","1"]})].filter(x=>!!x),unevaluatedProperties=refs.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,mergedAllOf=[];return allOf.forEach(schema=>{if(isJsonSchema7AllOfType(schema))mergedAllOf.push(...schema.allOf),schema.unevaluatedProperties===void 0&&(unevaluatedProperties=void 0);else{let nestedSchema=schema;if("additionalProperties"in schema&&schema.additionalProperties===!1){let{additionalProperties,...rest}=schema;nestedSchema=rest}else unevaluatedProperties=void 0;mergedAllOf.push(nestedSchema)}}),mergedAllOf.length?{allOf:mergedAllOf,...unevaluatedProperties}:void 0}__name(parseIntersectionDef,"parseIntersectionDef");function parseLiteralDef(def,refs){let parsedType=typeof def.value;return parsedType!=="bigint"&&parsedType!=="number"&&parsedType!=="boolean"&&parsedType!=="string"?{type:Array.isArray(def.value)?"array":"object"}:refs.target==="openApi3"?{type:parsedType==="bigint"?"integer":parsedType,enum:[def.value]}:{type:parsedType==="bigint"?"integer":parsedType,const:def.value}}__name(parseLiteralDef,"parseLiteralDef");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2}from"zod/v3";var emojiRegex,zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:__name(()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(def,refs){let res={type:"string"};if(def.checks)for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"email":switch(refs.emailStrategy){case"format:email":addFormat(res,"email",check.message,refs);break;case"format:idn-email":addFormat(res,"idn-email",check.message,refs);break;case"pattern:zod":addPattern(res,zodPatterns.email,check.message,refs);break}break;case"url":addFormat(res,"uri",check.message,refs);break;case"uuid":addFormat(res,"uuid",check.message,refs);break;case"regex":addPattern(res,check.regex,check.message,refs);break;case"cuid":addPattern(res,zodPatterns.cuid,check.message,refs);break;case"cuid2":addPattern(res,zodPatterns.cuid2,check.message,refs);break;case"startsWith":addPattern(res,RegExp(`^${escapeLiteralCheckValue(check.value,refs)}`),check.message,refs);break;case"endsWith":addPattern(res,RegExp(`${escapeLiteralCheckValue(check.value,refs)}$`),check.message,refs);break;case"datetime":addFormat(res,"date-time",check.message,refs);break;case"date":addFormat(res,"date",check.message,refs);break;case"time":addFormat(res,"time",check.message,refs);break;case"duration":addFormat(res,"duration",check.message,refs);break;case"length":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs),setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"includes":{addPattern(res,RegExp(escapeLiteralCheckValue(check.value,refs)),check.message,refs);break}case"ip":{check.version!=="v6"&&addFormat(res,"ipv4",check.message,refs),check.version!=="v4"&&addFormat(res,"ipv6",check.message,refs);break}case"base64url":addPattern(res,zodPatterns.base64url,check.message,refs);break;case"jwt":addPattern(res,zodPatterns.jwt,check.message,refs);break;case"cidr":{check.version!=="v6"&&addPattern(res,zodPatterns.ipv4Cidr,check.message,refs),check.version!=="v4"&&addPattern(res,zodPatterns.ipv6Cidr,check.message,refs);break}case"emoji":addPattern(res,zodPatterns.emoji(),check.message,refs);break;case"ulid":{addPattern(res,zodPatterns.ulid,check.message,refs);break}case"base64":{switch(refs.base64Strategy){case"format:binary":{addFormat(res,"binary",check.message,refs);break}case"contentEncoding:base64":{setResponseValueAndErrors(res,"contentEncoding","base64",check.message,refs);break}case"pattern:zod":{addPattern(res,zodPatterns.base64,check.message,refs);break}}break}case"nanoid":addPattern(res,zodPatterns.nanoid,check.message,refs);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return res}__name(parseStringDef,"parseStringDef");function escapeLiteralCheckValue(literal2,refs){return refs.patternStrategy==="escape"?escapeNonAlphaNumeric(literal2):literal2}__name(escapeLiteralCheckValue,"escapeLiteralCheckValue");var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(source){let result="";for(let i=0;i<source.length;i++)ALPHA_NUMERIC.has(source[i])||(result+="\\"),result+=source[i];return result}__name(escapeNonAlphaNumeric,"escapeNonAlphaNumeric");function addFormat(schema,value,message,refs){schema.format||schema.anyOf?.some(x=>x.format)?(schema.anyOf||(schema.anyOf=[]),schema.format&&(schema.anyOf.push({format:schema.format,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{format:schema.errorMessage.format}}}),delete schema.format,schema.errorMessage&&(delete schema.errorMessage.format,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.anyOf.push({format:value,...message&&refs.errorMessages&&{errorMessage:{format:message}}})):setResponseValueAndErrors(schema,"format",value,message,refs)}__name(addFormat,"addFormat");function addPattern(schema,regex,message,refs){schema.pattern||schema.allOf?.some(x=>x.pattern)?(schema.allOf||(schema.allOf=[]),schema.pattern&&(schema.allOf.push({pattern:schema.pattern,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{pattern:schema.errorMessage.pattern}}}),delete schema.pattern,schema.errorMessage&&(delete schema.errorMessage.pattern,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.allOf.push({pattern:stringifyRegExpWithFlags(regex,refs),...message&&refs.errorMessages&&{errorMessage:{pattern:message}}})):setResponseValueAndErrors(schema,"pattern",stringifyRegExpWithFlags(regex,refs),message,refs)}__name(addPattern,"addPattern");function stringifyRegExpWithFlags(regex,refs){if(!refs.applyRegexFlags||!regex.flags)return regex.source;let flags={i:regex.flags.includes("i"),m:regex.flags.includes("m"),s:regex.flags.includes("s")},source=flags.i?regex.source.toLowerCase():regex.source,pattern="",isEscaped2=!1,inCharGroup=!1,inCharRange=!1;for(let i=0;i<source.length;i++){if(isEscaped2){pattern+=source[i],isEscaped2=!1;continue}if(flags.i){if(inCharGroup){if(source[i].match(/[a-z]/)){inCharRange?(pattern+=source[i],pattern+=`${source[i-2]}-${source[i]}`.toUpperCase(),inCharRange=!1):source[i+1]==="-"&&source[i+2]?.match(/[a-z]/)?(pattern+=source[i],inCharRange=!0):pattern+=`${source[i]}${source[i].toUpperCase()}`;continue}}else if(source[i].match(/[a-z]/)){pattern+=`[${source[i]}${source[i].toUpperCase()}]`;continue}}if(flags.m){if(source[i]==="^"){pattern+=`(^|(?<=[\r
|
|
1353
|
+
`)}__name(renderLogs,"renderLogs");function renderPhase(phase){let parts=[phase.status];return phase.exitCode!==null&&parts.push(`exit ${phase.exitCode}`),phase.startedAt&&parts.push(`started ${phase.startedAt}`),parts.push(`${phase.events} ${phase.events===1?"line":"lines"}`),`${phase.phase}: ${parts.join(", ")}`}__name(renderPhase,"renderPhase");function buildOlderHint(cursor,env,options){let args=["fimo","logs","--branch",env,"--before",cursor];return options.limit&&args.push("--limit",options.limit),options.cwd&&args.push("--cwd",options.cwd),`Older: ${args.map(quoteArgument).join(" ")}`}__name(buildOlderHint,"buildOlderHint");function quoteArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteArgument,"quoteArgument");function errorMessage2(error){return error instanceof Error?error.message:String(error)}__name(errorMessage2,"errorMessage");init_esm();import{z as z75}from"zod";var projectScopeShape={projectId:z75.uuid().optional().describe("The Fimo project ID. Optional when the MCP server is already bound to a project.")},envScopeShape={...projectScopeShape,env:EnvSchema.optional().describe("The environment name, for example 'main' or 'agents/content-review'. Optional when the server is bound to an environment.")},typeNameField=z75.string().min(1).max(255).describe("The content type name, for example BlogPost."),localeField=z75.string().min(1).optional().describe("The locale to read or write."),entryDataField=z75.record(z75.string(),z75.unknown()).describe("Entry field values, keyed by field name as declared in the content schema."),filePathField=z75.string().min(1).max(1024).describe("File path relative to the project root."),labelKeyField=z75.string().min(1).max(255).describe("The translation key, for example home.hero.title."),assetIdField=z75.uuid().describe("The Fimo media asset ID."),formIdField=z75.string().min(1).max(255).describe("The Fimo form ID."),formFieldsField=z75.record(z75.string().min(1),z75.unknown()).describe("Form fields keyed by field name; Fimo validates each field definition."),formContentShape={name:z75.string().min(1).max(255).describe("Stable form name."),label:z75.string().min(1).max(255).describe("Human-readable form label."),fields:formFieldsField},mediaGenerationSchema=z75.object({...envScopeShape,task:z75.string().min(1).optional().describe("A stable task, for example 'image.generate' or 'video.generate'."),model:z75.string().min(1).optional().describe("An explicit model ID, for example 'fal/...'."),options:z75.record(z75.string(),z75.unknown()).describe("Task or model options, such as prompt, quality, aspect ratio, and source assets."),name:z75.string().min(1).max(255).optional().describe("Optional name for the generated asset."),parentId:z75.uuid().nullable().optional().describe("Optional media-library folder ID."),altText:z75.string().max(2e3).optional().describe("Optional alternative text for the generated asset."),caption:z75.string().max(2e3).optional().describe("Optional caption for the generated asset.")}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})});function tenantPath(scope,suffix){return`/tenant/${encodeURIComponent(scope.projectId)}/envs/${encodeEnvPathSegment(scope.env)}${suffix}`}__name(tenantPath,"tenantPath");function managementProjectPath(scope,suffix){return`/management/projects/${encodeURIComponent(scope.projectId)}${suffix}`}__name(managementProjectPath,"managementProjectPath");function managementEnvPath(scope,suffix){return managementProjectPath(scope,`/envs/${encodeURIComponent(scope.env)}${suffix}`)}__name(managementEnvPath,"managementEnvPath");function addQuery(path50,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))if(value!==void 0){if(Array.isArray(value)){value.length>0&¶ms.set(key,value.join(","));continue}params.set(key,String(value))}let queryString=params.toString();return queryString?`${path50}?${queryString}`:path50}__name(addQuery,"addQuery");var mcpToolCatalog={whoami:{description:"Return the authenticated Fimo user identity.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z75.object({})},projects_list:{description:"List the Fimo projects the authenticated user can access.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z75.object({}),buildRequest:__name(()=>({method:"GET",path:"/management/projects"}),"buildRequest")},envs_list:{description:"List the environments of a project.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z75.object(projectScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementProjectPath(scope,"/envs")}),"buildRequest")},schemas_list:{description:"List content schemas in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.schema.list",inputSchema:z75.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/schema")}),"buildRequest")},entries_list:{description:"List entries for one content type in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,locale:localeField,limit:z75.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z75.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),{locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_get:{description:"Read one entry by ID from a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,id:z75.uuid().describe("The entry ID."),locale:localeField,populate:z75.array(z75.string().min(1)).max(50).optional().describe("Reference fields to populate."),localeFallbacks:z75.boolean().optional().describe("Use the configured default locale when needed.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale,populate:input.populate,localeFallbacks:input.localeFallbacks})}),"buildRequest")},entries_search:{description:"Search entries across content types in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z75.object({...envScopeShape,search:z75.string().min(1).optional().describe("A text search applied to entry content."),locale:localeField,limit:z75.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z75.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/entries"),{search:input.search,locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_create:{description:"Create one entry of a content type in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.create",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField,documentId:z75.string().min(1).optional().describe("Attach the new entry to an existing document (adds a locale variant).")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),body:{data:input.data,locale:input.locale,documentId:input.documentId}}),"buildRequest")},entries_update:{description:"Update one entry by ID in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,id:z75.uuid().describe("The entry ID."),data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},entries_delete:{description:"Delete one entry by ID in a project environment.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.delete",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,id:z75.uuid().describe("The entry ID."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale})}),"buildRequest")},entries_bulk_create:{description:`Create up to ${MAX_BULK_ENTRIES} entries of one content type in a project environment.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_create",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,entries:z75.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES).describe("Entries to create.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-create`),body:{entries:input.entries}}),"buildRequest")},entries_bulk_update:{description:`Update up to ${MAX_BULK_ENTRIES} entries by IDs, a bounded filter, or per-entry updates.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_update",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,selection:z75.union([z75.object({ids:z75.array(z75.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z75.object({where:EntryWhereSchema}),z75.object({updates:z75.array(z75.object({id:z75.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),body:EntryMutationBodySchema.optional().describe("Shared update body for ids or where selections.")}).superRefine((value,context)=>{let isPerEntry="updates"in value.selection;isPerEntry&&value.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!isPerEntry&&value.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),buildRequest:__name((input,scope)=>{let{selection,body}=input;return{method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}},"buildRequest")},entries_bulk_delete:{description:`Delete up to ${MAX_BULK_ENTRIES} entries by IDs or a bounded filter.`,annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.bulk_delete",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,selection:z75.union([z75.object({ids:z75.array(z75.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z75.object({where:EntryWhereSchema})]),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-delete`),body:{...input.selection,locale:input.locale}}),"buildRequest")},singles_get:{description:"Read the document-scoped value of a Single content type.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,locale:localeField,populate:z75.array(z75.string().min(1)).max(50).optional().describe("Reference fields to populate.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale,populate:input.populate})}),"buildRequest")},singles_update:{description:"Update the document-scoped value of a Single content type.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},labels_list:{description:'List localized labels in a project environment. Pass locale "*" to group all locales.',annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.list",inputSchema:z75.object({...envScopeShape,locale:z75.string().min(1).optional().describe('Locale code, or "*" for every configured locale.')}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/labels"),{locale:input.locale})}),"buildRequest")},labels_get:{description:"Read one localized label by locale and key.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.get",inputSchema:z75.object({...envScopeShape,locale:z75.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},labels_set:{description:"Create or set one localized label.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.create",inputSchema:z75.object({...envScopeShape,key:labelKeyField,value:z75.string().max(1e4).describe("Localized label text."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels"),body:{key:input.key,value:input.value,locale:input.locale}}),"buildRequest")},labels_set_many:{description:"Set many localized labels in one bounded request.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.update",inputSchema:z75.object({...envScopeShape,records:z75.array(z75.object({key:labelKeyField,value:z75.string().max(1e4),locale:localeField})).min(1).max(500).describe("Localized labels to set.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels/sync"),body:{created:input.records,updated:[],deleted:[]}}),"buildRequest")},labels_delete:{description:"Delete one localized label.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"i18n.delete",inputSchema:z75.object({...envScopeShape,locale:z75.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},assets_list:{description:"List media assets and folders, including public URLs for files the user can access.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.list",inputSchema:z75.object({...envScopeShape,parentId:z75.uuid().optional().describe("Limit results to one media-library folder."),search:z75.string().max(200).optional(),type:z75.enum(["file","folder"]).optional(),mimePrefix:z75.string().max(50).optional().describe("MIME prefix such as image/ or video/."),sortBy:z75.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z75.enum(["asc","desc"]).optional(),includePath:z75.boolean().optional(),excludeHidden:z75.boolean().optional(),limit:z75.number().int().min(1).max(100).optional(),offset:z75.number().int().min(0).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/assets"),{parentId:input.parentId,search:input.search,type:input.type,mimePrefix:input.mimePrefix,sortBy:input.sortBy,sortDirection:input.sortDirection,includePath:input.includePath,excludeHidden:input.excludeHidden,limit:input.limit,offset:input.offset})}),"buildRequest")},assets_get:{description:"Read one media asset or folder, including its public URL when it is a file.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.get",inputSchema:z75.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},assets_generate:{description:"Generate an image or video asset with Fimo AI credits and save it to the media library.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.generate",inputSchema:mediaGenerationSchema,buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/generate"),body:{...input.task?{task:input.task}:{model:input.model},options:input.options,name:input.name,parentId:input.parentId,altText:input.altText,caption:input.caption}}),"buildRequest")},assets_create_folder:{description:"Create a media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.create_folder",inputSchema:z75.object({...envScopeShape,name:z75.string().min(1).max(255).describe("Folder name."),parentId:z75.uuid().nullable().optional().describe("Optional parent folder ID.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/folders"),body:{name:input.name,parentId:input.parentId}}),"buildRequest")},assets_move:{description:"Move a media asset or folder to another media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.move",inputSchema:z75.object({...envScopeShape,id:assetIdField,parentId:z75.uuid().nullable().describe("Destination folder ID, or null for the library root.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}/move`),body:{parentId:input.parentId}}),"buildRequest")},assets_delete:{description:"Delete a media asset or folder.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"assets.delete",inputSchema:z75.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_list:{description:"List the forms configured in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z75.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/forms")}),"buildRequest")},forms_get:{description:"Read one form definition.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z75.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_create:{description:"Create a form definition. Email notification settings stay in the Fimo UI.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z75.object({...envScopeShape,...formContentShape}).strict(),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/forms"),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_update:{description:"Update the name, label, or fields of one form definition.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z75.object({...envScopeShape,id:formIdField,...z75.object(formContentShape).partial().shape}).strict(),buildRequest:__name((input,scope)=>({method:"PUT",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_delete:{description:"Delete one form definition.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"forms.delete",inputSchema:z75.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_submissions_list:{description:"List submissions for one form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z75.object({...envScopeShape,id:formIdField,limit:z75.number().int().min(1).max(100).optional(),offset:z75.number().int().min(0).optional(),searchQuery:z75.string().max(200).optional(),sortDirection:z75.enum(["asc","desc"]).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions`),{limit:input.limit,offset:input.offset,searchQuery:input.searchQuery,sortDirection:input.sortDirection})}),"buildRequest")},forms_submission_get:{description:"Read one submission for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z75.object({...envScopeShape,id:formIdField,submissionId:z75.string().min(1).max(255).describe("The submission ID.")}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/${encodeURIComponent(input.submissionId)}`)}),"buildRequest")},forms_submissions_stats:{description:"Read aggregate submission statistics for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z75.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/stats`)}),"buildRequest")},files_read:{description:"Read one project file from an environment. Hidden and sensitive files (.env, credentials, keys, lockfiles, .git, build output) are unavailable.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z75.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/file"),{path:input.path})}),"buildRequest")},files_glob:{description:"List project file paths in an environment, optionally filtered by a glob pattern.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z75.object({...envScopeShape,pattern:z75.string().min(1).max(300).optional().describe("Glob pattern, for example 'src/**/*.tsx'."),limit:z75.number().int().min(1).max(2e3).optional().describe("Maximum number of paths to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/paths"),{pattern:input.pattern,limit:input.limit})}),"buildRequest")},files_grep:{description:"Search project file contents in an environment with a regular expression. Matching is bounded (file count, bytes, match count) and complex patterns that exceed the time budget are rejected.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z75.object({...envScopeShape,pattern:z75.string().min(1).max(200).describe("Regular expression to search for."),include:z75.string().min(1).max(300).optional().describe("Glob pattern limiting which files are searched."),caseInsensitive:z75.boolean().optional().describe("Case-insensitive matching."),maxMatches:z75.number().int().min(1).max(200).optional().describe("Maximum number of matches to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/grep"),{pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.maxMatches})}),"buildRequest")},files_write:{description:"Create one project text file, or overwrite an existing one when overwrite is set. Fails if the file exists and overwrite is not set. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z75.object({...envScopeShape,path:filePathField,content:z75.string().max(262144).describe("Full UTF-8 text content of the file (256 KB max)."),overwrite:z75.boolean().optional().describe("Replace the file if it already exists. Without it, writing an existing path fails.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/write"),body:{path:input.path,content:input.content,overwrite:input.overwrite}}),"buildRequest")},files_edit:{description:"Edit one project file by exact string replacement. The old string must exist; set replaceAll when it occurs more than once. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z75.object({...envScopeShape,path:filePathField,oldString:z75.string().min(1).describe("Exact text to replace."),newString:z75.string().describe("Replacement text."),replaceAll:z75.boolean().optional().describe("Replace every occurrence instead of requiring a unique one.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/edit"),body:{path:input.path,oldString:input.oldString,newString:input.newString,replaceAll:input.replaceAll}}),"buildRequest")},files_delete:{description:"Delete one project file in an environment. The deletion lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z75.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/delete"),body:{path:input.path}}),"buildRequest")},agents_list:{description:"List the agent bundles declared in a project environment, with triggers and activations.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",inputSchema:z75.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementEnvPath(scope,"/agents")}),"buildRequest")},agents_run:{description:"Trigger a manual run of a project agent. Returns a durable session ID; poll agents_status for progress. The agent executes in the managed project sandbox under its declared capabilities.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"agents",operation:"agent.delegate",inputSchema:z75.object({...envScopeShape,agentName:z75.string().min(1).max(120).describe("The agent bundle name."),args:z75.record(z75.string(),z75.unknown()).optional().describe("Arguments passed to the agent run.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,`/agents/${encodeURIComponent(input.agentName)}/run`),body:input.args===void 0?{}:{args:input.args}}),"buildRequest")},agents_status:{description:"Read one agent session (status, report, checkpoints) by session ID.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z75.object({...projectScopeShape,sessionId:z75.uuid().describe("The agent session ID returned by agents_run.")}),buildRequest:__name((input,scope)=>({method:"GET",path:managementProjectPath(scope,`/agents/sessions/${encodeURIComponent(input.sessionId)}`)}),"buildRequest")}},mcpToolNames=Object.keys(mcpToolCatalog);import*as z3rt from"zod/v3";import*as z4mini from"zod/v4-mini";function isZ4Schema(s){return!!s._zod}__name(isZ4Schema,"isZ4Schema");function objectFromShape(shape){let values=Object.values(shape);if(values.length===0)return z4mini.object({});let allV4=values.every(isZ4Schema),allV3=values.every(s=>!isZ4Schema(s));if(allV4)return z4mini.object(shape);if(allV3)return z3rt.object(shape);throw new Error("Mixed Zod versions detected in object shape.")}__name(objectFromShape,"objectFromShape");function safeParse3(schema,data2){return isZ4Schema(schema)?z4mini.safeParse(schema,data2):schema.safeParse(data2)}__name(safeParse3,"safeParse");async function safeParseAsync2(schema,data2){return isZ4Schema(schema)?await z4mini.safeParseAsync(schema,data2):await schema.safeParseAsync(data2)}__name(safeParseAsync2,"safeParseAsync");function getObjectShape(schema){if(!schema)return;let rawShape;if(isZ4Schema(schema)?rawShape=schema._zod?.def?.shape:rawShape=schema.shape,!!rawShape){if(typeof rawShape=="function")try{return rawShape()}catch{return}return rawShape}}__name(getObjectShape,"getObjectShape");function normalizeObjectSchema(schema){if(schema){if(typeof schema=="object"){let asV3=schema,asV4=schema;if(!asV3._def&&!asV4._zod){let values=Object.values(schema);if(values.length>0&&values.every(v=>typeof v=="object"&&v!==null&&(v._def!==void 0||v._zod!==void 0||typeof v.parse=="function")))return objectFromShape(schema)}}if(isZ4Schema(schema)){let def=schema._zod?.def;if(def&&(def.type==="object"||def.shape!==void 0))return schema}else if(schema.shape!==void 0)return schema}}__name(normalizeObjectSchema,"normalizeObjectSchema");function getParseErrorMessage(error){if(error&&typeof error=="object"){if("message"in error&&typeof error.message=="string")return error.message;if("issues"in error&&Array.isArray(error.issues)&&error.issues.length>0){let firstIssue=error.issues[0];if(firstIssue&&typeof firstIssue=="object"&&"message"in firstIssue)return String(firstIssue.message)}try{return JSON.stringify(error)}catch{return String(error)}}return String(error)}__name(getParseErrorMessage,"getParseErrorMessage");function getSchemaDescription(schema){return schema.description}__name(getSchemaDescription,"getSchemaDescription");function isSchemaOptional(schema){if(isZ4Schema(schema))return schema._zod?.def?.type==="optional";let v3Schema=schema;return typeof schema.isOptional=="function"?schema.isOptional():v3Schema._def?.typeName==="ZodOptional"}__name(isSchemaOptional,"isSchemaOptional");function getLiteralValue(schema){if(isZ4Schema(schema)){let def2=schema._zod?.def;if(def2){if(def2.value!==void 0)return def2.value;if(Array.isArray(def2.values)&&def2.values.length>0)return def2.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue}__name(getLiteralValue,"getLiteralValue");import*as z76 from"zod/v4";var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=z76.custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=z76.union([z76.string(),z76.number().int()]),CursorSchema=z76.string(),TaskCreationParamsSchema=z76.looseObject({ttl:z76.union([z76.number(),z76.null()]).optional(),pollInterval:z76.number().optional()}),TaskMetadataSchema=z76.object({ttl:z76.number().optional()}),RelatedTaskMetadataSchema=z76.object({taskId:z76.string()}),RequestMetaSchema=z76.looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=z76.object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=__name(value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,"isTaskAugmentedRequestParams"),RequestSchema=z76.object({method:z76.string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=z76.object({_meta:RequestMetaSchema.optional()}),NotificationSchema=z76.object({method:z76.string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=z76.looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=z76.union([z76.string(),z76.number().int()]),JSONRPCRequestSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=__name(value=>JSONRPCRequestSchema.safeParse(value).success,"isJSONRPCRequest"),JSONRPCNotificationSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=__name(value=>JSONRPCNotificationSchema.safeParse(value).success,"isJSONRPCNotification"),JSONRPCResultResponseSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=__name(value=>JSONRPCResultResponseSchema.safeParse(value).success,"isJSONRPCResultResponse");var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:z76.object({code:z76.number().int(),message:z76.string(),data:z76.unknown().optional()})}).strict();var isJSONRPCErrorResponse=__name(value=>JSONRPCErrorResponseSchema.safeParse(value).success,"isJSONRPCErrorResponse");var JSONRPCMessageSchema=z76.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=z76.union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:z76.string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=z76.object({src:z76.string(),mimeType:z76.string().optional(),sizes:z76.array(z76.string()).optional(),theme:z76.enum(["light","dark"]).optional()}),IconsSchema=z76.object({icons:z76.array(IconSchema).optional()}),BaseMetadataSchema=z76.object({name:z76.string(),title:z76.string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:z76.string(),websiteUrl:z76.string().optional(),description:z76.string().optional()}),FormElicitationCapabilitySchema=z76.intersection(z76.object({applyDefaults:z76.boolean().optional()}),z76.record(z76.string(),z76.unknown())),ElicitationCapabilitySchema=z76.preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,z76.intersection(z76.object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),z76.record(z76.string(),z76.unknown()).optional())),ClientTasksCapabilitySchema=z76.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z76.looseObject({sampling:z76.looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:z76.looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=z76.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z76.looseObject({tools:z76.looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=z76.object({experimental:z76.record(z76.string(),AssertObjectSchema).optional(),sampling:z76.object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:z76.object({listChanged:z76.boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:z76.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:z76.literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=z76.object({experimental:z76.record(z76.string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:z76.object({listChanged:z76.boolean().optional()}).optional(),resources:z76.object({subscribe:z76.boolean().optional(),listChanged:z76.boolean().optional()}).optional(),tools:z76.object({listChanged:z76.boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:z76.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z76.string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:z76.literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=z76.object({progress:z76.number(),total:z76.optional(z76.number()),message:z76.optional(z76.string())}),ProgressNotificationParamsSchema=z76.object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=z76.enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=z76.object({taskId:z76.string(),status:TaskStatusSchema,ttl:z76.union([z76.number(),z76.null()]),createdAt:z76.string(),lastUpdatedAt:z76.string(),pollInterval:z76.optional(z76.number()),statusMessage:z76.optional(z76.string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:z76.literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:z76.string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:z76.literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:z76.string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:z76.array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:z76.literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:z76.string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=z76.object({uri:z76.string(),mimeType:z76.optional(z76.string()),_meta:z76.record(z76.string(),z76.unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z76.string()}),Base64Schema=z76.string().refine(val2=>{try{return atob(val2),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=z76.enum(["user","assistant"]),AnnotationsSchema=z76.object({audience:z76.array(RoleSchema).optional(),priority:z76.number().min(0).max(1).optional(),lastModified:z76.iso.datetime({offset:!0}).optional()}),ResourceSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:z76.string(),description:z76.optional(z76.string()),mimeType:z76.optional(z76.string()),annotations:AnnotationsSchema.optional(),_meta:z76.optional(z76.looseObject({}))}),ResourceTemplateSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:z76.string(),description:z76.optional(z76.string()),mimeType:z76.optional(z76.string()),annotations:AnnotationsSchema.optional(),_meta:z76.optional(z76.looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z76.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z76.array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:z76.string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:z76.literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:z76.array(z76.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:z76.literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:z76.literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:z76.string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=z76.object({name:z76.string(),description:z76.optional(z76.string()),required:z76.optional(z76.boolean())}),PromptSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z76.optional(z76.string()),arguments:z76.optional(z76.array(PromptArgumentSchema)),_meta:z76.optional(z76.looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z76.array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:z76.string(),arguments:z76.record(z76.string(),z76.string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:z76.literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=z76.object({type:z76.literal("text"),text:z76.string(),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ImageContentSchema=z76.object({type:z76.literal("image"),data:Base64Schema,mimeType:z76.string(),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),AudioContentSchema=z76.object({type:z76.literal("audio"),data:Base64Schema,mimeType:z76.string(),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ToolUseContentSchema=z76.object({type:z76.literal("tool_use"),name:z76.string(),id:z76.string(),input:z76.record(z76.string(),z76.unknown()),_meta:z76.record(z76.string(),z76.unknown()).optional()}),EmbeddedResourceSchema=z76.object({type:z76.literal("resource"),resource:z76.union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:z76.literal("resource_link")}),ContentBlockSchema=z76.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z76.object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:z76.string().optional(),messages:z76.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=z76.object({title:z76.string().optional(),readOnlyHint:z76.boolean().optional(),destructiveHint:z76.boolean().optional(),idempotentHint:z76.boolean().optional(),openWorldHint:z76.boolean().optional()}),ToolExecutionSchema=z76.object({taskSupport:z76.enum(["required","optional","forbidden"]).optional()}),ToolSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z76.string().optional(),inputSchema:z76.object({type:z76.literal("object"),properties:z76.record(z76.string(),AssertObjectSchema).optional(),required:z76.array(z76.string()).optional()}).catchall(z76.unknown()),outputSchema:z76.object({type:z76.literal("object"),properties:z76.record(z76.string(),AssertObjectSchema).optional(),required:z76.array(z76.string()).optional()}).catchall(z76.unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z76.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z76.array(ContentBlockSchema).default([]),structuredContent:z76.record(z76.string(),z76.unknown()).optional(),isError:z76.boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:z76.unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:z76.string(),arguments:z76.record(z76.string(),z76.unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:z76.literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=z76.object({autoRefresh:z76.boolean().default(!0),debounceMs:z76.number().int().nonnegative().default(300)}),LoggingLevelSchema=z76.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:z76.literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:z76.string().optional(),data:z76.unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=z76.object({name:z76.string().optional()}),ModelPreferencesSchema=z76.object({hints:z76.array(ModelHintSchema).optional(),costPriority:z76.number().min(0).max(1).optional(),speedPriority:z76.number().min(0).max(1).optional(),intelligencePriority:z76.number().min(0).max(1).optional()}),ToolChoiceSchema=z76.object({mode:z76.enum(["auto","required","none"]).optional()}),ToolResultContentSchema=z76.object({type:z76.literal("tool_result"),toolUseId:z76.string().describe("The unique identifier for the corresponding tool call."),content:z76.array(ContentBlockSchema).default([]),structuredContent:z76.object({}).loose().optional(),isError:z76.boolean().optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),SamplingContentSchema=z76.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=z76.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=z76.object({role:RoleSchema,content:z76.union([SamplingMessageContentBlockSchema,z76.array(SamplingMessageContentBlockSchema)]),_meta:z76.record(z76.string(),z76.unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:z76.array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:z76.string().optional(),includeContext:z76.enum(["none","thisServer","allServers"]).optional(),temperature:z76.number().optional(),maxTokens:z76.number().int(),stopSequences:z76.array(z76.string()).optional(),metadata:AssertObjectSchema.optional(),tools:z76.array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:z76.literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:z76.string(),stopReason:z76.optional(z76.enum(["endTurn","stopSequence","maxTokens"]).or(z76.string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:z76.string(),stopReason:z76.optional(z76.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(z76.string())),role:RoleSchema,content:z76.union([SamplingMessageContentBlockSchema,z76.array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=z76.object({type:z76.literal("boolean"),title:z76.string().optional(),description:z76.string().optional(),default:z76.boolean().optional()}),StringSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),minLength:z76.number().optional(),maxLength:z76.number().optional(),format:z76.enum(["email","uri","date","date-time"]).optional(),default:z76.string().optional()}),NumberSchemaSchema=z76.object({type:z76.enum(["number","integer"]),title:z76.string().optional(),description:z76.string().optional(),minimum:z76.number().optional(),maximum:z76.number().optional(),default:z76.number().optional()}),UntitledSingleSelectEnumSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),enum:z76.array(z76.string()),default:z76.string().optional()}),TitledSingleSelectEnumSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),oneOf:z76.array(z76.object({const:z76.string(),title:z76.string()})),default:z76.string().optional()}),LegacyTitledEnumSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),enum:z76.array(z76.string()),enumNames:z76.array(z76.string()).optional(),default:z76.string().optional()}),SingleSelectEnumSchemaSchema=z76.union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=z76.object({type:z76.literal("array"),title:z76.string().optional(),description:z76.string().optional(),minItems:z76.number().optional(),maxItems:z76.number().optional(),items:z76.object({type:z76.literal("string"),enum:z76.array(z76.string())}),default:z76.array(z76.string()).optional()}),TitledMultiSelectEnumSchemaSchema=z76.object({type:z76.literal("array"),title:z76.string().optional(),description:z76.string().optional(),minItems:z76.number().optional(),maxItems:z76.number().optional(),items:z76.object({anyOf:z76.array(z76.object({const:z76.string(),title:z76.string()}))}),default:z76.array(z76.string()).optional()}),MultiSelectEnumSchemaSchema=z76.union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=z76.union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=z76.union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z76.literal("form").optional(),message:z76.string(),requestedSchema:z76.object({type:z76.literal("object"),properties:z76.record(z76.string(),PrimitiveSchemaDefinitionSchema),required:z76.array(z76.string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z76.literal("url"),message:z76.string(),elicitationId:z76.string(),url:z76.string().url()}),ElicitRequestParamsSchema=z76.union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:z76.literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:z76.string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:z76.enum(["accept","decline","cancel"]),content:z76.preprocess(val2=>val2===null?void 0:val2,z76.record(z76.string(),z76.union([z76.string(),z76.number(),z76.boolean(),z76.array(z76.string())])).optional())}),ResourceTemplateReferenceSchema=z76.object({type:z76.literal("ref/resource"),uri:z76.string()});var PromptReferenceSchema=z76.object({type:z76.literal("ref/prompt"),name:z76.string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:z76.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z76.object({name:z76.string(),value:z76.string()}),context:z76.object({arguments:z76.record(z76.string(),z76.string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:z76.literal("completion/complete"),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}__name(assertCompleteRequestPrompt,"assertCompleteRequestPrompt");function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}__name(assertCompleteRequestResourceTemplate,"assertCompleteRequestResourceTemplate");var CompleteResultSchema=ResultSchema.extend({completion:z76.looseObject({values:z76.array(z76.string()).max(100),total:z76.optional(z76.number().int()),hasMore:z76.optional(z76.boolean())})}),RootSchema=z76.object({uri:z76.string().startsWith("file://"),name:z76.string().optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:z76.literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:z76.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=z76.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=z76.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=z76.union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=z76.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=z76.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=z76.union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{static{__name(this,"McpError")}constructor(code2,message,data2){super(`MCP error ${code2}: ${message}`),this.code=code2,this.data=data2,this.name="McpError"}static fromError(code2,message,data2){if(code2===ErrorCode.UrlElicitationRequired&&data2){let errorData=data2;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code2,message,data2)}},UrlElicitationRequiredError=class extends McpError{static{__name(this,"UrlElicitationRequiredError")}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}__name(isTerminal,"isTerminal");import*as z4mini2 from"zod/v4-mini";var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");var defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=__name(options=>typeof options=="string"?{...defaultOptions,name:options}:{...defaultOptions,...options},"getDefaultOptions");var getRefs=__name(options=>{let _options=getDefaultOptions(options),currentPath=_options.name!==void 0?[..._options.basePath,_options.definitionPath,_options.name]:_options.basePath;return{..._options,flags:{hasReferencedOpenAiAnyType:!1},currentPath,propertyPath:void 0,seen:new Map(Object.entries(_options.definitions).map(([name,def])=>[def._def,{def:def._def,path:[..._options.basePath,_options.definitionPath,name],jsonSchema:void 0}]))}},"getRefs");function addErrorMessage(res,key,errorMessage5,refs){refs?.errorMessages&&errorMessage5&&(res.errorMessage={...res.errorMessage,[key]:errorMessage5})}__name(addErrorMessage,"addErrorMessage");function setResponseValueAndErrors(res,key,value,errorMessage5,refs){res[key]=value,addErrorMessage(res,key,errorMessage5,refs)}__name(setResponseValueAndErrors,"setResponseValueAndErrors");var getRelativePath=__name((pathA,pathB)=>{let i=0;for(;i<pathA.length&&i<pathB.length&&pathA[i]===pathB[i];i++);return[(pathA.length-i).toString(),...pathB.slice(i)].join("/")},"getRelativePath");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3}from"zod/v3";function parseAnyDef(refs){if(refs.target!=="openAi")return{};let anyDefinitionPath=[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName];return refs.flags.hasReferencedOpenAiAnyType=!0,{$ref:refs.$refStrategy==="relative"?getRelativePath(anyDefinitionPath,refs.currentPath):anyDefinitionPath.join("/")}}__name(parseAnyDef,"parseAnyDef");import{ZodFirstPartyTypeKind}from"zod/v3";function parseArrayDef(def,refs){let res={type:"array"};return def.type?._def&&def.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(res.items=parseDef(def.type._def,{...refs,currentPath:[...refs.currentPath,"items"]})),def.minLength&&setResponseValueAndErrors(res,"minItems",def.minLength.value,def.minLength.message,refs),def.maxLength&&setResponseValueAndErrors(res,"maxItems",def.maxLength.value,def.maxLength.message,refs),def.exactLength&&(setResponseValueAndErrors(res,"minItems",def.exactLength.value,def.exactLength.message,refs),setResponseValueAndErrors(res,"maxItems",def.exactLength.value,def.exactLength.message,refs)),res}__name(parseArrayDef,"parseArrayDef");function parseBigintDef(def,refs){let res={type:"integer",format:"int64"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseBigintDef,"parseBigintDef");function parseBooleanDef(){return{type:"boolean"}}__name(parseBooleanDef,"parseBooleanDef");function parseBrandedDef(_def,refs){return parseDef(_def.type._def,refs)}__name(parseBrandedDef,"parseBrandedDef");var parseCatchDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseCatchDef");function parseDateDef(def,refs,overrideDateStrategy){let strategy=overrideDateStrategy??refs.dateStrategy;if(Array.isArray(strategy))return{anyOf:strategy.map((item,i)=>parseDateDef(def,refs,item))};switch(strategy){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(def,refs)}}__name(parseDateDef,"parseDateDef");var integerDateParser=__name((def,refs)=>{let res={type:"integer",format:"unix-time"};if(refs.target==="openApi3")return res;for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minimum",check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maximum",check.value,check.message,refs);break}return res},"integerDateParser");function parseDefaultDef(_def,refs){return{...parseDef(_def.innerType._def,refs),default:_def.defaultValue()}}__name(parseDefaultDef,"parseDefaultDef");function parseEffectsDef(_def,refs){return refs.effectStrategy==="input"?parseDef(_def.schema._def,refs):parseAnyDef(refs)}__name(parseEffectsDef,"parseEffectsDef");function parseEnumDef(def){return{type:"string",enum:Array.from(def.values)}}__name(parseEnumDef,"parseEnumDef");var isJsonSchema7AllOfType=__name(type=>"type"in type&&type.type==="string"?!1:"allOf"in type,"isJsonSchema7AllOfType");function parseIntersectionDef(def,refs){let allOf=[parseDef(def.left._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),parseDef(def.right._def,{...refs,currentPath:[...refs.currentPath,"allOf","1"]})].filter(x=>!!x),unevaluatedProperties=refs.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,mergedAllOf=[];return allOf.forEach(schema=>{if(isJsonSchema7AllOfType(schema))mergedAllOf.push(...schema.allOf),schema.unevaluatedProperties===void 0&&(unevaluatedProperties=void 0);else{let nestedSchema=schema;if("additionalProperties"in schema&&schema.additionalProperties===!1){let{additionalProperties,...rest}=schema;nestedSchema=rest}else unevaluatedProperties=void 0;mergedAllOf.push(nestedSchema)}}),mergedAllOf.length?{allOf:mergedAllOf,...unevaluatedProperties}:void 0}__name(parseIntersectionDef,"parseIntersectionDef");function parseLiteralDef(def,refs){let parsedType=typeof def.value;return parsedType!=="bigint"&&parsedType!=="number"&&parsedType!=="boolean"&&parsedType!=="string"?{type:Array.isArray(def.value)?"array":"object"}:refs.target==="openApi3"?{type:parsedType==="bigint"?"integer":parsedType,enum:[def.value]}:{type:parsedType==="bigint"?"integer":parsedType,const:def.value}}__name(parseLiteralDef,"parseLiteralDef");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2}from"zod/v3";var emojiRegex,zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:__name(()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(def,refs){let res={type:"string"};if(def.checks)for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"email":switch(refs.emailStrategy){case"format:email":addFormat(res,"email",check.message,refs);break;case"format:idn-email":addFormat(res,"idn-email",check.message,refs);break;case"pattern:zod":addPattern(res,zodPatterns.email,check.message,refs);break}break;case"url":addFormat(res,"uri",check.message,refs);break;case"uuid":addFormat(res,"uuid",check.message,refs);break;case"regex":addPattern(res,check.regex,check.message,refs);break;case"cuid":addPattern(res,zodPatterns.cuid,check.message,refs);break;case"cuid2":addPattern(res,zodPatterns.cuid2,check.message,refs);break;case"startsWith":addPattern(res,RegExp(`^${escapeLiteralCheckValue(check.value,refs)}`),check.message,refs);break;case"endsWith":addPattern(res,RegExp(`${escapeLiteralCheckValue(check.value,refs)}$`),check.message,refs);break;case"datetime":addFormat(res,"date-time",check.message,refs);break;case"date":addFormat(res,"date",check.message,refs);break;case"time":addFormat(res,"time",check.message,refs);break;case"duration":addFormat(res,"duration",check.message,refs);break;case"length":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs),setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"includes":{addPattern(res,RegExp(escapeLiteralCheckValue(check.value,refs)),check.message,refs);break}case"ip":{check.version!=="v6"&&addFormat(res,"ipv4",check.message,refs),check.version!=="v4"&&addFormat(res,"ipv6",check.message,refs);break}case"base64url":addPattern(res,zodPatterns.base64url,check.message,refs);break;case"jwt":addPattern(res,zodPatterns.jwt,check.message,refs);break;case"cidr":{check.version!=="v6"&&addPattern(res,zodPatterns.ipv4Cidr,check.message,refs),check.version!=="v4"&&addPattern(res,zodPatterns.ipv6Cidr,check.message,refs);break}case"emoji":addPattern(res,zodPatterns.emoji(),check.message,refs);break;case"ulid":{addPattern(res,zodPatterns.ulid,check.message,refs);break}case"base64":{switch(refs.base64Strategy){case"format:binary":{addFormat(res,"binary",check.message,refs);break}case"contentEncoding:base64":{setResponseValueAndErrors(res,"contentEncoding","base64",check.message,refs);break}case"pattern:zod":{addPattern(res,zodPatterns.base64,check.message,refs);break}}break}case"nanoid":addPattern(res,zodPatterns.nanoid,check.message,refs);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return res}__name(parseStringDef,"parseStringDef");function escapeLiteralCheckValue(literal2,refs){return refs.patternStrategy==="escape"?escapeNonAlphaNumeric(literal2):literal2}__name(escapeLiteralCheckValue,"escapeLiteralCheckValue");var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(source){let result="";for(let i=0;i<source.length;i++)ALPHA_NUMERIC.has(source[i])||(result+="\\"),result+=source[i];return result}__name(escapeNonAlphaNumeric,"escapeNonAlphaNumeric");function addFormat(schema,value,message,refs){schema.format||schema.anyOf?.some(x=>x.format)?(schema.anyOf||(schema.anyOf=[]),schema.format&&(schema.anyOf.push({format:schema.format,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{format:schema.errorMessage.format}}}),delete schema.format,schema.errorMessage&&(delete schema.errorMessage.format,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.anyOf.push({format:value,...message&&refs.errorMessages&&{errorMessage:{format:message}}})):setResponseValueAndErrors(schema,"format",value,message,refs)}__name(addFormat,"addFormat");function addPattern(schema,regex,message,refs){schema.pattern||schema.allOf?.some(x=>x.pattern)?(schema.allOf||(schema.allOf=[]),schema.pattern&&(schema.allOf.push({pattern:schema.pattern,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{pattern:schema.errorMessage.pattern}}}),delete schema.pattern,schema.errorMessage&&(delete schema.errorMessage.pattern,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.allOf.push({pattern:stringifyRegExpWithFlags(regex,refs),...message&&refs.errorMessages&&{errorMessage:{pattern:message}}})):setResponseValueAndErrors(schema,"pattern",stringifyRegExpWithFlags(regex,refs),message,refs)}__name(addPattern,"addPattern");function stringifyRegExpWithFlags(regex,refs){if(!refs.applyRegexFlags||!regex.flags)return regex.source;let flags={i:regex.flags.includes("i"),m:regex.flags.includes("m"),s:regex.flags.includes("s")},source=flags.i?regex.source.toLowerCase():regex.source,pattern="",isEscaped2=!1,inCharGroup=!1,inCharRange=!1;for(let i=0;i<source.length;i++){if(isEscaped2){pattern+=source[i],isEscaped2=!1;continue}if(flags.i){if(inCharGroup){if(source[i].match(/[a-z]/)){inCharRange?(pattern+=source[i],pattern+=`${source[i-2]}-${source[i]}`.toUpperCase(),inCharRange=!1):source[i+1]==="-"&&source[i+2]?.match(/[a-z]/)?(pattern+=source[i],inCharRange=!0):pattern+=`${source[i]}${source[i].toUpperCase()}`;continue}}else if(source[i].match(/[a-z]/)){pattern+=`[${source[i]}${source[i].toUpperCase()}]`;continue}}if(flags.m){if(source[i]==="^"){pattern+=`(^|(?<=[\r
|
|
1354
1354
|
]))`;continue}else if(source[i]==="$"){pattern+=`($|(?=[\r
|
|
1355
1355
|
]))`;continue}}if(flags.s&&source[i]==="."){pattern+=inCharGroup?`${source[i]}\r
|
|
1356
1356
|
`:`[${source[i]}\r
|
|
1357
|
-
]`;continue}pattern+=source[i],source[i]==="\\"?isEscaped2=!0:inCharGroup&&source[i]==="]"?inCharGroup=!1:!inCharGroup&&source[i]==="["&&(inCharGroup=!0)}try{new RegExp(pattern)}catch{return console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),regex.source}return pattern}__name(stringifyRegExpWithFlags,"stringifyRegExpWithFlags");function parseRecordDef(def,refs){if(refs.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),refs.target==="openApi3"&&def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodEnum)return{type:"object",required:def.keyType._def.values,properties:def.keyType._def.values.reduce((acc,key)=>({...acc,[key]:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"properties",key]})??parseAnyDef(refs)}),{}),additionalProperties:refs.rejectedAdditionalProperties};let schema={type:"object",additionalProperties:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]})??refs.allowedAdditionalProperties};if(refs.target==="openApi3")return schema;if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodString&&def.keyType._def.checks?.length){let{type,...keyType}=parseStringDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}else{if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodEnum)return{...schema,propertyNames:{enum:def.keyType._def.values}};if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodBranded&&def.keyType._def.type._def.typeName===ZodFirstPartyTypeKind2.ZodString&&def.keyType._def.type._def.checks?.length){let{type,...keyType}=parseBrandedDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}}return schema}__name(parseRecordDef,"parseRecordDef");function parseMapDef(def,refs){if(refs.mapStrategy==="record")return parseRecordDef(def,refs);let keys=parseDef(def.keyType._def,{...refs,currentPath:[...refs.currentPath,"items","items","0"]})||parseAnyDef(refs),values=parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items","items","1"]})||parseAnyDef(refs);return{type:"array",maxItems:125,items:{type:"array",items:[keys,values],minItems:2,maxItems:2}}}__name(parseMapDef,"parseMapDef");function parseNativeEnumDef(def){let object4=def.values,actualValues=Object.keys(def.values).filter(key=>typeof object4[object4[key]]!="number").map(key=>object4[key]),parsedTypes=Array.from(new Set(actualValues.map(values=>typeof values)));return{type:parsedTypes.length===1?parsedTypes[0]==="string"?"string":"number":["string","number"],enum:actualValues}}__name(parseNativeEnumDef,"parseNativeEnumDef");function parseNeverDef(refs){return refs.target==="openAi"?void 0:{not:parseAnyDef({...refs,currentPath:[...refs.currentPath,"not"]})}}__name(parseNeverDef,"parseNeverDef");function parseNullDef(refs){return refs.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}__name(parseNullDef,"parseNullDef");var primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(def,refs){if(refs.target==="openApi3")return asAnyOf(def,refs);let options=def.options instanceof Map?Array.from(def.options.values()):def.options;if(options.every(x=>x._def.typeName in primitiveMappings&&(!x._def.checks||!x._def.checks.length))){let types=options.reduce((types2,x)=>{let type=primitiveMappings[x._def.typeName];return type&&!types2.includes(type)?[...types2,type]:types2},[]);return{type:types.length>1?types:types[0]}}else if(options.every(x=>x._def.typeName==="ZodLiteral"&&!x.description)){let types=options.reduce((acc,x)=>{let type=typeof x._def.value;switch(type){case"string":case"number":case"boolean":return[...acc,type];case"bigint":return[...acc,"integer"];case"object":if(x._def.value===null)return[...acc,"null"];default:return acc}},[]);if(types.length===options.length){let uniqueTypes=types.filter((x,i,a)=>a.indexOf(x)===i);return{type:uniqueTypes.length>1?uniqueTypes:uniqueTypes[0],enum:options.reduce((acc,x)=>acc.includes(x._def.value)?acc:[...acc,x._def.value],[])}}}else if(options.every(x=>x._def.typeName==="ZodEnum"))return{type:"string",enum:options.reduce((acc,x)=>[...acc,...x._def.values.filter(x2=>!acc.includes(x2))],[])};return asAnyOf(def,refs)}__name(parseUnionDef,"parseUnionDef");var asAnyOf=__name((def,refs)=>{let anyOf=(def.options instanceof Map?Array.from(def.options.values()):def.options).map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"anyOf",`${i}`]})).filter(x=>!!x&&(!refs.strictUnions||typeof x=="object"&&Object.keys(x).length>0));return anyOf.length?{anyOf}:void 0},"asAnyOf");function parseNullableDef(def,refs){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(def.innerType._def.typeName)&&(!def.innerType._def.checks||!def.innerType._def.checks.length))return refs.target==="openApi3"?{type:primitiveMappings[def.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[def.innerType._def.typeName],"null"]};if(refs.target==="openApi3"){let base2=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath]});return base2&&"$ref"in base2?{allOf:[base2],nullable:!0}:base2&&{...base2,nullable:!0}}let base=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","0"]});return base&&{anyOf:[base,{type:"null"}]}}__name(parseNullableDef,"parseNullableDef");function parseNumberDef(def,refs){let res={type:"number"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"int":res.type="integer",addErrorMessage(res,"type",check.message,refs);break;case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseNumberDef,"parseNumberDef");function parseObjectDef(def,refs){let forceOptionalIntoNullable=refs.target==="openAi",result={type:"object",properties:{}},required=[],shape=def.shape();for(let propName in shape){let propDef=shape[propName];if(propDef===void 0||propDef._def===void 0)continue;let propOptional=safeIsOptional(propDef);propOptional&&forceOptionalIntoNullable&&(propDef._def.typeName==="ZodOptional"&&(propDef=propDef._def.innerType),propDef.isNullable()||(propDef=propDef.nullable()),propOptional=!1);let parsedDef=parseDef(propDef._def,{...refs,currentPath:[...refs.currentPath,"properties",propName],propertyPath:[...refs.currentPath,"properties",propName]});parsedDef!==void 0&&(result.properties[propName]=parsedDef,propOptional||required.push(propName))}required.length&&(result.required=required);let additionalProperties=decideAdditionalProperties(def,refs);return additionalProperties!==void 0&&(result.additionalProperties=additionalProperties),result}__name(parseObjectDef,"parseObjectDef");function decideAdditionalProperties(def,refs){if(def.catchall._def.typeName!=="ZodNever")return parseDef(def.catchall._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]});switch(def.unknownKeys){case"passthrough":return refs.allowedAdditionalProperties;case"strict":return refs.rejectedAdditionalProperties;case"strip":return refs.removeAdditionalStrategy==="strict"?refs.allowedAdditionalProperties:refs.rejectedAdditionalProperties}}__name(decideAdditionalProperties,"decideAdditionalProperties");function safeIsOptional(schema){try{return schema.isOptional()}catch{return!0}}__name(safeIsOptional,"safeIsOptional");var parseOptionalDef=__name((def,refs)=>{if(refs.currentPath.toString()===refs.propertyPath?.toString())return parseDef(def.innerType._def,refs);let innerSchema=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","1"]});return innerSchema?{anyOf:[{not:parseAnyDef(refs)},innerSchema]}:parseAnyDef(refs)},"parseOptionalDef");var parsePipelineDef=__name((def,refs)=>{if(refs.pipeStrategy==="input")return parseDef(def.in._def,refs);if(refs.pipeStrategy==="output")return parseDef(def.out._def,refs);let a=parseDef(def.in._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),b=parseDef(def.out._def,{...refs,currentPath:[...refs.currentPath,"allOf",a?"1":"0"]});return{allOf:[a,b].filter(x=>x!==void 0)}},"parsePipelineDef");function parsePromiseDef(def,refs){return parseDef(def.type._def,refs)}__name(parsePromiseDef,"parsePromiseDef");function parseSetDef(def,refs){let schema={type:"array",uniqueItems:!0,items:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items"]})};return def.minSize&&setResponseValueAndErrors(schema,"minItems",def.minSize.value,def.minSize.message,refs),def.maxSize&&setResponseValueAndErrors(schema,"maxItems",def.maxSize.value,def.maxSize.message,refs),schema}__name(parseSetDef,"parseSetDef");function parseTupleDef(def,refs){return def.rest?{type:"array",minItems:def.items.length,items:def.items.map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"items",`${i}`]})).reduce((acc,x)=>x===void 0?acc:[...acc,x],[]),additionalItems:parseDef(def.rest._def,{...refs,currentPath:[...refs.currentPath,"additionalItems"]})}:{type:"array",minItems:def.items.length,maxItems:def.items.length,items:def.items.map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"items",`${i}`]})).reduce((acc,x)=>x===void 0?acc:[...acc,x],[])}}__name(parseTupleDef,"parseTupleDef");function parseUndefinedDef(refs){return{not:parseAnyDef(refs)}}__name(parseUndefinedDef,"parseUndefinedDef");function parseUnknownDef(refs){return parseAnyDef(refs)}__name(parseUnknownDef,"parseUnknownDef");var parseReadonlyDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseReadonlyDef");var selectParser=__name((def,typeName,refs)=>{switch(typeName){case ZodFirstPartyTypeKind3.ZodString:return parseStringDef(def,refs);case ZodFirstPartyTypeKind3.ZodNumber:return parseNumberDef(def,refs);case ZodFirstPartyTypeKind3.ZodObject:return parseObjectDef(def,refs);case ZodFirstPartyTypeKind3.ZodBigInt:return parseBigintDef(def,refs);case ZodFirstPartyTypeKind3.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind3.ZodDate:return parseDateDef(def,refs);case ZodFirstPartyTypeKind3.ZodUndefined:return parseUndefinedDef(refs);case ZodFirstPartyTypeKind3.ZodNull:return parseNullDef(refs);case ZodFirstPartyTypeKind3.ZodArray:return parseArrayDef(def,refs);case ZodFirstPartyTypeKind3.ZodUnion:case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:return parseUnionDef(def,refs);case ZodFirstPartyTypeKind3.ZodIntersection:return parseIntersectionDef(def,refs);case ZodFirstPartyTypeKind3.ZodTuple:return parseTupleDef(def,refs);case ZodFirstPartyTypeKind3.ZodRecord:return parseRecordDef(def,refs);case ZodFirstPartyTypeKind3.ZodLiteral:return parseLiteralDef(def,refs);case ZodFirstPartyTypeKind3.ZodEnum:return parseEnumDef(def);case ZodFirstPartyTypeKind3.ZodNativeEnum:return parseNativeEnumDef(def);case ZodFirstPartyTypeKind3.ZodNullable:return parseNullableDef(def,refs);case ZodFirstPartyTypeKind3.ZodOptional:return parseOptionalDef(def,refs);case ZodFirstPartyTypeKind3.ZodMap:return parseMapDef(def,refs);case ZodFirstPartyTypeKind3.ZodSet:return parseSetDef(def,refs);case ZodFirstPartyTypeKind3.ZodLazy:return()=>def.getter()._def;case ZodFirstPartyTypeKind3.ZodPromise:return parsePromiseDef(def,refs);case ZodFirstPartyTypeKind3.ZodNaN:case ZodFirstPartyTypeKind3.ZodNever:return parseNeverDef(refs);case ZodFirstPartyTypeKind3.ZodEffects:return parseEffectsDef(def,refs);case ZodFirstPartyTypeKind3.ZodAny:return parseAnyDef(refs);case ZodFirstPartyTypeKind3.ZodUnknown:return parseUnknownDef(refs);case ZodFirstPartyTypeKind3.ZodDefault:return parseDefaultDef(def,refs);case ZodFirstPartyTypeKind3.ZodBranded:return parseBrandedDef(def,refs);case ZodFirstPartyTypeKind3.ZodReadonly:return parseReadonlyDef(def,refs);case ZodFirstPartyTypeKind3.ZodCatch:return parseCatchDef(def,refs);case ZodFirstPartyTypeKind3.ZodPipeline:return parsePipelineDef(def,refs);case ZodFirstPartyTypeKind3.ZodFunction:case ZodFirstPartyTypeKind3.ZodVoid:case ZodFirstPartyTypeKind3.ZodSymbol:return;default:return(_=>{})(typeName)}},"selectParser");function parseDef(def,refs,forceResolution=!1){let seenItem=refs.seen.get(def);if(refs.override){let overrideResult=refs.override?.(def,refs,seenItem,forceResolution);if(overrideResult!==ignoreOverride)return overrideResult}if(seenItem&&!forceResolution){let seenSchema=get$ref(seenItem,refs);if(seenSchema!==void 0)return seenSchema}let newItem={def,path:refs.currentPath,jsonSchema:void 0};refs.seen.set(def,newItem);let jsonSchemaOrGetter=selectParser(def,def.typeName,refs),jsonSchema=typeof jsonSchemaOrGetter=="function"?parseDef(jsonSchemaOrGetter(),refs):jsonSchemaOrGetter;if(jsonSchema&&addMeta(def,refs,jsonSchema),refs.postProcess){let postProcessResult=refs.postProcess(jsonSchema,def,refs);return newItem.jsonSchema=jsonSchema,postProcessResult}return newItem.jsonSchema=jsonSchema,jsonSchema}__name(parseDef,"parseDef");var get$ref=__name((item,refs)=>{switch(refs.$refStrategy){case"root":return{$ref:item.path.join("/")};case"relative":return{$ref:getRelativePath(refs.currentPath,item.path)};case"none":case"seen":return item.path.length<refs.currentPath.length&&item.path.every((value,index2)=>refs.currentPath[index2]===value)?(console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`),parseAnyDef(refs)):refs.$refStrategy==="seen"?parseAnyDef(refs):void 0}},"get$ref"),addMeta=__name((def,refs,jsonSchema)=>(def.description&&(jsonSchema.description=def.description,refs.markdownDescription&&(jsonSchema.markdownDescription=def.description)),jsonSchema),"addMeta");var zodToJsonSchema=__name((schema,options)=>{let refs=getRefs(options),definitions=typeof options=="object"&&options.definitions?Object.entries(options.definitions).reduce((acc,[name2,schema2])=>({...acc,[name2]:parseDef(schema2._def,{...refs,currentPath:[...refs.basePath,refs.definitionPath,name2]},!0)??parseAnyDef(refs)}),{}):void 0,name=typeof options=="string"?options:options?.nameStrategy==="title"?void 0:options?.name,main=parseDef(schema._def,name===void 0?refs:{...refs,currentPath:[...refs.basePath,refs.definitionPath,name]},!1)??parseAnyDef(refs),title=typeof options=="object"&&options.name!==void 0&&options.nameStrategy==="title"?options.name:void 0;title!==void 0&&(main.title=title),refs.flags.hasReferencedOpenAiAnyType&&(definitions||(definitions={}),definitions[refs.openAiAnyTypeName]||(definitions[refs.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:refs.$refStrategy==="relative"?"1":[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName].join("/")}}));let combined=name===void 0?definitions?{...main,[refs.definitionPath]:definitions}:main:{$ref:[...refs.$refStrategy==="relative"?[]:refs.basePath,refs.definitionPath,name].join("/"),[refs.definitionPath]:{...definitions,[name]:main}};return refs.target==="jsonSchema7"?combined.$schema="http://json-schema.org/draft-07/schema#":(refs.target==="jsonSchema2019-09"||refs.target==="openAi")&&(combined.$schema="https://json-schema.org/draft/2019-09/schema#"),refs.target==="openAi"&&("anyOf"in combined||"oneOf"in combined||"allOf"in combined||"type"in combined&&Array.isArray(combined.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),combined},"zodToJsonSchema");function mapMiniTarget(t2){return!t2||t2==="jsonSchema7"||t2==="draft-7"?"draft-7":t2==="jsonSchema2019-09"||t2==="draft-2020-12"?"draft-2020-12":"draft-7"}__name(mapMiniTarget,"mapMiniTarget");function toJsonSchemaCompat(schema,opts){return isZ4Schema(schema)?z4mini2.toJSONSchema(schema,{target:mapMiniTarget(opts?.target),io:opts?.pipeStrategy??"input"}):zodToJsonSchema(schema,{strictUnions:opts?.strictUnions??!0,pipeStrategy:opts?.pipeStrategy??"input"})}__name(toJsonSchemaCompat,"toJsonSchemaCompat");function getMethodLiteral(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value!="string")throw new Error("Schema method literal must be a string");return value}__name(getMethodLiteral,"getMethodLiteral");function parseWithCompat(schema,data2){let result=safeParse3(schema,data2);if(!result.success)throw result.error;return result.data}__name(parseWithCompat,"parseWithCompat");var DEFAULT_REQUEST_TIMEOUT_MSEC=6e4,Protocol=class{static{__name(this,"Protocol")}constructor(_options){this._options=_options,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(CancelledNotificationSchema,notification=>{this._oncancel(notification)}),this.setNotificationHandler(ProgressNotificationSchema,notification=>{this._onprogress(notification)}),this.setRequestHandler(PingRequestSchema,_request=>({})),this._taskStore=_options?.taskStore,this._taskMessageQueue=_options?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(request,extra)=>{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return{...task}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(request,extra)=>{let handleTaskResult=__name(async()=>{let taskId=request.params.taskId;if(this._taskMessageQueue){let queuedMessage;for(;queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId);){if(queuedMessage.type==="response"||queuedMessage.type==="error"){let message=queuedMessage.message,requestId=message.id,resolver=this._requestResolvers.get(requestId);if(resolver)if(this._requestResolvers.delete(requestId),queuedMessage.type==="response")resolver(message);else{let errorMessage4=message,error=new McpError(errorMessage4.error.code,errorMessage4.error.message,errorMessage4.error.data);resolver(error)}else{let messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(new Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}let task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(!isTerminal(task.status))return await this._waitForTaskUpdate(taskId,extra.signal),await handleTaskResult();if(isTerminal(task.status)){let result=await this._taskStore.getTaskResult(taskId,extra.sessionId);return this._clearTaskQueue(taskId),{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()},"handleTaskResult");return await handleTaskResult()}),this.setRequestHandler(ListTasksRequestSchema,async(request,extra)=>{try{let{tasks,nextCursor}=await this._taskStore.listTasks(request.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error instanceof Error?error.message:String(error)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(request,extra)=>{try{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request.params.taskId}`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`);await this._taskStore.updateTaskStatus(request.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId),this._clearTaskQueue(request.params.taskId);let cancelledTask=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!cancelledTask)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request.params.taskId}`);return{_meta:{},...cancelledTask}}catch(error){throw error instanceof McpError?error:new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error instanceof Error?error.message:String(error)}`)}}))}async _oncancel(notification){if(!notification.params.requestId)return;this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);info&&(clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId))}async connect(transport){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.(),this._onclose()};let _onerror=this.transport?.onerror;this._transport.onerror=error=>{_onerror?.(error),this._onerror(error)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?this._onresponse(message):isJSONRPCRequest(message)?this._onrequest(message,extra):isJSONRPCNotification(message)?this._onnotification(message):this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))},await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let controller of this._requestHandlerAbortControllers.values())controller.abort();this._requestHandlerAbortControllers.clear();let error=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let handler of responseHandlers.values())handler(error)}_onerror(error){this.onerror?.(error)}_onnotification(notification){let handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;handler!==void 0&&Promise.resolve().then(()=>handler(notification)).catch(error=>this._onerror(new Error(`Uncaught error in notification handler: ${error}`)))}_onrequest(request,extra){let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler,capturedTransport=this._transport,relatedTaskId=request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(handler===void 0){let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};relatedTaskId&&this._taskMessageQueue?this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch(error=>this._onerror(new Error(`Failed to enqueue error response: ${error}`))):capturedTransport?.send(errorResponse).catch(error=>this._onerror(new Error(`Failed to send an error response: ${error}`)));return}let abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let taskCreationParams=isTaskAugmentedRequestParams(request.params)?request.params.task:void 0,taskStore=this._taskStore?this.requestTaskStore(request,capturedTransport?.sessionId):void 0,fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request.params?._meta,sendNotification:__name(async notification=>{if(abortController.signal.aborted)return;let notificationOptions={relatedRequestId:request.id};relatedTaskId&&(notificationOptions.relatedTask={taskId:relatedTaskId}),await this.notification(notification,notificationOptions)},"sendNotification"),sendRequest:__name(async(r,resultSchema,options)=>{if(abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");let requestOptions={...options,relatedRequestId:request.id};relatedTaskId&&!requestOptions.relatedTask&&(requestOptions.relatedTask={taskId:relatedTaskId});let effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;return effectiveTaskId&&taskStore&&await taskStore.updateTaskStatus(effectiveTaskId,"input_required"),await this.request(r,resultSchema,requestOptions)},"sendRequest"),authInfo:extra?.authInfo,requestId:request.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};Promise.resolve().then(()=>{taskCreationParams&&this.assertTaskHandlerCapability(request.method)}).then(()=>handler(request,fullExtra)).then(async result=>{if(abortController.signal.aborted)return;let response={result,jsonrpc:"2.0",id:request.id};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(response)},async error=>{if(abortController.signal.aborted)return;let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:Number.isSafeInteger(error.code)?error.code:ErrorCode.InternalError,message:error.message??"Internal error",...error.data!==void 0&&{data:error.data}}};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(errorResponse)}).catch(error=>this._onerror(new Error(`Failed to send response: ${error}`))).finally(()=>{this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error);return}handler(params)}_onresponse(response){let messageId=Number(response.id),resolver=this._requestResolvers.get(messageId);if(resolver){if(this._requestResolvers.delete(messageId),isJSONRPCResultResponse(response))resolver(response);else{let error=new McpError(response.error.code,response.error.message,response.error.data);resolver(error)}return}let handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId);let isTaskResponse=!1;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result=="object"){let result=response.result;if(result.task&&typeof result.task=="object"){let task=result.task;typeof task.taskId=="string"&&(isTaskResponse=!0,this._taskProgressTokens.set(task.taskId,messageId))}}if(isTaskResponse||this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response))handler(response);else{let error=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request,resultSchema,options){let{task}=options??{};if(!task){try{yield{type:"result",result:await this.request(request,resultSchema,options)}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}return}let taskId;try{let createResult=await this.request(request,CreateTaskResultSchema,options);if(createResult.task)taskId=createResult.task.taskId,yield{type:"taskCreated",task:createResult.task};else throw new McpError(ErrorCode.InternalError,"Task creation did not return a task");for(;;){let task2=await this.getTask({taskId},options);if(yield{type:"taskStatus",task:task2},isTerminal(task2.status)){task2.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)}:task2.status==="failed"?yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)}:task2.status==="cancelled"&&(yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)});return}if(task2.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)};return}let pollInterval=task2.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(resolve10=>setTimeout(resolve10,pollInterval)),options?.signal?.throwIfAborted()}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}}request(request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve10,reject)=>{let earlyReject=__name(error=>{reject(error)},"earlyReject");if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method),task&&this.assertTaskCapability(request.method)}catch(e){earlyReject(e);return}options?.signal?.throwIfAborted();let messageId=this._requestMessageId++,jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};options?.onprogress&&(this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta||{},progressToken:messageId}}),task&&(jsonrpcRequest.params={...jsonrpcRequest.params,task}),relatedTask&&(jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}});let cancel=__name(reason=>{this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error2=>this._onerror(new Error(`Failed to send cancellation: ${error2}`)));let error=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));reject(error)},"cancel");this._responseHandlers.set(messageId,response=>{if(!options?.signal?.aborted){if(response instanceof Error)return reject(response);try{let parseResult=safeParse3(resultSchema,response.result);parseResult.success?resolve10(parseResult.data):reject(parseResult.error)}catch(error){reject(error)}}}),options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=__name(()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout})),"timeoutHandler");this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1);let relatedTaskId=relatedTask?.taskId;if(relatedTaskId){let responseResolver=__name(response=>{let handler=this._responseHandlers.get(messageId);handler?handler(response):this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`))},"responseResolver");this._requestResolvers.set(messageId,responseResolver),this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch(error=>{this._cleanupTimeout(messageId),reject(error)})}else this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error=>{this._cleanupTimeout(messageId),reject(error)})})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(notification.method);let relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){let jsonrpcNotification2={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification2,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(notification.method),!this._transport)return;let jsonrpcNotification2={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification2={...jsonrpcNotification2,params:{...jsonrpcNotification2.params,_meta:{...jsonrpcNotification2.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),this._transport?.send(jsonrpcNotification2,options).catch(error=>this._onerror(error))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){let method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method),this._requestHandlers.set(method,(request,extra)=>{let parsed=parseWithCompat(requestSchema,request);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw new Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(notificationSchema,handler){let method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,notification=>{let parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){let progressToken=this._taskProgressTokens.get(taskId);progressToken!==void 0&&(this._progressHandlers.delete(progressToken),this._taskProgressTokens.delete(taskId))}async _enqueueTaskMessage(taskId,message,sessionId){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message,sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){let messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(let message of messages)if(message.type==="request"&&isJSONRPCRequest(message.message)){let requestId=message.message.id,resolver=this._requestResolvers.get(requestId);resolver?(resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(requestId)):this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}async _waitForTaskUpdate(taskId,signal){let interval=this._options?.defaultTaskPollInterval??1e3;try{let task=await this._taskStore?.getTask(taskId);task?.pollInterval&&(interval=task.pollInterval)}catch{}return new Promise((resolve10,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}let timeoutId=setTimeout(resolve10,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId),reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(request,sessionId){let taskStore=this._taskStore;if(!taskStore)throw new Error("No task store configured");return{createTask:__name(async taskParams=>{if(!request)throw new Error("No request provided");return await taskStore.createTask(taskParams,request.id,{method:request.method,params:request.params},sessionId)},"createTask"),getTask:__name(async taskId=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return task},"getTask"),storeTaskResult:__name(async(taskId,status,result)=>{await taskStore.storeTaskResult(taskId,status,result,sessionId);let task=await taskStore.getTask(taskId,sessionId);if(task){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});await this.notification(notification),isTerminal(task.status)&&this._cleanupTaskProgressHandler(taskId)}},"storeTaskResult"),getTaskResult:__name(taskId=>taskStore.getTaskResult(taskId,sessionId),"getTaskResult"),updateTaskStatus:__name(async(taskId,status,statusMessage)=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await taskStore.updateTaskStatus(taskId,status,statusMessage,sessionId);let updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});await this.notification(notification),isTerminal(updatedTask.status)&&this._cleanupTaskProgressHandler(taskId)}},"updateTaskStatus"),listTasks:__name(cursor=>taskStore.listTasks(cursor,sessionId),"listTasks")}}};function isPlainObject2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}__name(isPlainObject2,"isPlainObject");function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];isPlainObject2(baseValue)&&isPlainObject2(addValue)?result[k]={...baseValue,...addValue}:result[k]=addValue}return result}__name(mergeCapabilities,"mergeCapabilities");var import_ajv=__toESM(require_ajv(),1),import_ajv_formats=__toESM(require_dist4(),1);function createDefaultAjvInstance(){let ajv=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_ajv_formats.default)(ajv),ajv}__name(createDefaultAjvInstance,"createDefaultAjvInstance");var AjvJsonSchemaValidator=class{static{__name(this,"AjvJsonSchemaValidator")}constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){let ajvValidator="$id"in schema&&typeof schema.$id=="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return input=>ajvValidator(input)?{valid:!0,data:input,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}};var ExperimentalServerTasks=class{static{__name(this,"ExperimentalServerTasks")}constructor(_server){this._server=_server}requestStream(request,resultSchema,options){return this._server.requestStream(request,resultSchema,options)}createMessageStream(params,options){let clientCapabilities=this._server.getClientCapabilities();if((params.tools||params.toolChoice)&&!clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c2=>c2.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c2=>c2.type==="tool_use");if(hasToolResults){if(lastContent.some(c2=>c2.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c2=>c2.type==="tool_use").map(c2=>c2.id)),toolResultIds=new Set(lastContent.filter(c2=>c2.type==="tool_result").map(c2=>c2.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}elicitInputStream(params,options){let clientCapabilities=this._server.getClientCapabilities(),mode2=params.mode??"form";switch(mode2){case"url":{if(!clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let normalizedParams=mode2==="form"&¶ms.mode===void 0?{...params,mode:"form"}:params;return this.requestStream({method:"elicitation/create",params:normalizedParams},ElicitResultSchema,options)}async getTask(taskId,options){return this._server.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._server.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._server.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._server.cancelTask({taskId},options)}};function assertToolsCallTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"tools/call":if(!requests.tools?.call)throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);break;default:break}}__name(assertToolsCallTaskCapability,"assertToolsCallTaskCapability");function assertClientRequestTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage)throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);break;case"elicitation/create":if(!requests.elicitation?.create)throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);break;default:break}}__name(assertClientRequestTaskCapability,"assertClientRequestTaskCapability");var Server=class extends Protocol{static{__name(this,"Server")}constructor(_serverInfo,options){super(options),this._serverInfo=_serverInfo,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index2)=>[level,index2])),this.isMessageIgnored=(level,sessionId)=>{let currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):!1},this._capabilities=options?.capabilities??{},this._instructions=options?.instructions,this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,request=>this._oninitialize(request)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(request,extra)=>{let transportSessionId=extra.sessionId||extra.requestInfo?.headers["mcp-session-id"]||void 0,{level}=request.params,parseResult=LoggingLevelSchema.safeParse(level);return parseResult.success&&this._loggingLevels.set(transportSessionId,parseResult.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalServerTasks(this)}),this._experimental}registerCapabilities(capabilities){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){let methodSchema=getObjectShape(requestSchema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let methodValue;if(isZ4Schema(methodSchema)){let v4Schema=methodSchema;methodValue=v4Schema._zod?.def?.value??v4Schema.value}else{let v3Schema=methodSchema;methodValue=v3Schema._def?.value??v3Schema.value}if(typeof methodValue!="string")throw new Error("Schema method literal must be a string");if(methodValue==="tools/call"){let wrappedHandler=__name(async(request,extra)=>{let validatedRequest=safeParse3(CallToolRequestSchema,request);if(!validatedRequest.success){let errorMessage4=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${errorMessage4}`)}let{params}=validatedRequest.data,result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse3(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage4=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage4}`)}return taskValidationResult.data}let validationResult=safeParse3(CallToolResultSchema,result);if(!validationResult.success){let errorMessage4=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${errorMessage4}`)}return validationResult.data},"wrappedHandler");return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${method})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${method})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${method})`);break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${method})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${method})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(this._capabilities)switch(method){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${method})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${method})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${method})`);break;case"ping":case"initialize":break}}assertTaskCapability(method){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,method,"Client")}assertTaskHandlerCapability(method){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,method,"Server")}async _oninitialize(request){let requestedVersion=request.params.protocolVersion;return this._clientCapabilities=request.params.capabilities,this._clientVersion=request.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},EmptyResultSchema)}async createMessage(params,options){if((params.tools||params.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c2=>c2.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c2=>c2.type==="tool_use");if(hasToolResults){if(lastContent.some(c2=>c2.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c2=>c2.type==="tool_use").map(c2=>c2.id)),toolResultIds=new Set(lastContent.filter(c2=>c2.type==="tool_result").map(c2=>c2.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return params.tools?this.request({method:"sampling/createMessage",params},CreateMessageResultWithToolsSchema,options):this.request({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}async elicitInput(params,options){switch(params.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let urlParams=params;return this.request({method:"elicitation/create",params:urlParams},ElicitResultSchema,options)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let formParams=params.mode==="form"?params:{...params,mode:"form"},result=await this.request({method:"elicitation/create",params:formParams},ElicitResultSchema,options);if(result.action==="accept"&&result.content&&formParams.requestedSchema)try{let validationResult=this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);if(!validationResult.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}catch(error){throw error instanceof McpError?error:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${error instanceof Error?error.message:String(error)}`)}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this.request({method:"roots/list",params},ListRootsResultSchema,options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging&&!this.isMessageIgnored(params.level,sessionId))return this.notification({method:"notifications/message",params})}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");function isCompletable(schema){return!!schema&&typeof schema=="object"&&COMPLETABLE_SYMBOL in schema}__name(isCompletable,"isCompletable");function getCompleter(schema){return schema[COMPLETABLE_SYMBOL]?.complete}__name(getCompleter,"getCompleter");var McpZodTypeKind;(function(McpZodTypeKind2){McpZodTypeKind2.Completable="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));var TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(name){let warnings=[];if(name.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(name.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]};if(name.includes(" ")&&warnings.push("Tool name contains spaces, which may cause parsing issues"),name.includes(",")&&warnings.push("Tool name contains commas, which may cause parsing issues"),(name.startsWith("-")||name.endsWith("-"))&&warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(name.startsWith(".")||name.endsWith("."))&&warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!TOOL_NAME_REGEX.test(name)){let invalidChars=name.split("").filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index2,arr)=>arr.indexOf(char)===index2);return warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c2=>`"${c2}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings}}return{isValid:!0,warnings}}__name(validateToolName,"validateToolName");function issueToolNameWarning(name,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name}":`);for(let warning of warnings)console.warn(` - ${warning}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}__name(issueToolNameWarning,"issueToolNameWarning");function validateAndWarnToolName(name){let result=validateToolName(name);return issueToolNameWarning(name,result.warnings),result.isValid}__name(validateAndWarnToolName,"validateAndWarnToolName");var ExperimentalMcpServerTasks=class{static{__name(this,"ExperimentalMcpServerTasks")}constructor(_mcpServer){this._mcpServer=_mcpServer}registerToolTask(name,config,handler){let execution={taskSupport:"required",...config.execution};if(execution.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(name,config.title,config.description,config.inputSchema,config.outputSchema,config.annotations,execution,config._meta,handler)}};import{ZodOptional}from"zod";var McpServer=class{static{__name(this,"McpServer")}constructor(serverInfo,options){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(serverInfo,options)}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalMcpServerTasks(this)}),this._experimental}async connect(transport){return await this.server.connect(transport)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,tool])=>tool.enabled).map(([name,tool])=>{let toolDefinition={name,title:tool.title,description:tool.description,inputSchema:(()=>{let obj=normalizeObjectSchema(tool.inputSchema);return obj?toJsonSchemaCompat(obj,{strictUnions:!0,pipeStrategy:"input"}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:tool.annotations,execution:tool.execution,_meta:tool._meta};if(tool.outputSchema){let obj=normalizeObjectSchema(tool.outputSchema);obj&&(toolDefinition.outputSchema=toJsonSchemaCompat(obj,{strictUnions:!0,pipeStrategy:"output"}))}return toolDefinition})})),this.server.setRequestHandler(CallToolRequestSchema,async(request,extra)=>{try{let tool=this._registeredTools[request.params.name];if(!tool)throw new McpError(ErrorCode.InvalidParams,`Tool ${request.params.name} not found`);if(!tool.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${request.params.name} disabled`);let isTaskRequest=!!request.params.task,taskSupport=tool.execution?.taskSupport,isTaskHandler="createTask"in tool.handler;if((taskSupport==="required"||taskSupport==="optional")&&!isTaskHandler)throw new McpError(ErrorCode.InternalError,`Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);if(taskSupport==="required"&&!isTaskRequest)throw new McpError(ErrorCode.MethodNotFound,`Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);if(taskSupport==="optional"&&!isTaskRequest&&isTaskHandler)return await this.handleAutomaticTaskPolling(tool,request,extra);let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),result=await this.executeToolHandler(tool,args,extra);return isTaskRequest||await this.validateToolOutput(tool,result,request.params.name),result}catch(error){if(error instanceof McpError&&error.code===ErrorCode.UrlElicitationRequired)throw error;return this.createToolError(error instanceof Error?error.message:String(error))}}),this._toolHandlersInitialized=!0)}createToolError(errorMessage4){return{content:[{type:"text",text:errorMessage4}],isError:!0}}async validateToolInput(tool,args,toolName){if(!tool.inputSchema)return;let schemaToParse=normalizeObjectSchema(tool.inputSchema)??tool.inputSchema,parseResult=await safeParseAsync2(schemaToParse,args);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage4=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage4}`)}return parseResult.data}async validateToolOutput(tool,result,toolName){if(!tool.outputSchema||!("content"in result)||result.isError)return;if(!result.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);let outputObj=normalizeObjectSchema(tool.outputSchema),parseResult=await safeParseAsync2(outputObj,result.structuredContent);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage4=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage4}`)}}async executeToolHandler(tool,args,extra){let handler=tool.handler;if("createTask"in handler){if(!extra.taskStore)throw new Error("No task store provided.");let taskExtra={...extra,taskStore:extra.taskStore};if(tool.inputSchema){let typedHandler=handler;return await Promise.resolve(typedHandler.createTask(args,taskExtra))}else{let typedHandler=handler;return await Promise.resolve(typedHandler.createTask(taskExtra))}}if(tool.inputSchema){let typedHandler=handler;return await Promise.resolve(typedHandler(args,extra))}else{let typedHandler=handler;return await Promise.resolve(typedHandler(extra))}}async handleAutomaticTaskPolling(tool,request,extra){if(!extra.taskStore)throw new Error("No task store provided for task-capable tool.");let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),handler=tool.handler,taskExtra={...extra,taskStore:extra.taskStore},createTaskResult=args?await Promise.resolve(handler.createTask(args,taskExtra)):await Promise.resolve(handler.createTask(taskExtra)),taskId=createTaskResult.task.taskId,task=createTaskResult.task,pollInterval=task.pollInterval??5e3;for(;task.status!=="completed"&&task.status!=="failed"&&task.status!=="cancelled";){await new Promise(resolve10=>setTimeout(resolve10,pollInterval));let updatedTask=await extra.taskStore.getTask(taskId);if(!updatedTask)throw new McpError(ErrorCode.InternalError,`Task ${taskId} not found during polling`);task=updatedTask}return await extra.taskStore.getTaskResult(taskId)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async request=>{switch(request.params.ref.type){case"ref/prompt":return assertCompleteRequestPrompt(request),this.handlePromptCompletion(request,request.params.ref);case"ref/resource":return assertCompleteRequestResourceTemplate(request),this.handleResourceCompletion(request,request.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${request.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(request,ref){let prompt=this._registeredPrompts[ref.name];if(!prompt)throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} not found`);if(!prompt.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} disabled`);if(!prompt.argsSchema)return EMPTY_COMPLETION_RESULT;let field=getObjectShape(prompt.argsSchema)?.[request.params.argument.name];if(!isCompletable(field))return EMPTY_COMPLETION_RESULT;let completer=getCompleter(field);if(!completer)return EMPTY_COMPLETION_RESULT;let suggestions=await completer(request.params.argument.value,request.params.context);return createCompletionResult(suggestions)}async handleResourceCompletion(request,ref){let template=Object.values(this._registeredResourceTemplates).find(t2=>t2.resourceTemplate.uriTemplate.toString()===ref.uri);if(!template){if(this._registeredResources[ref.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${request.params.ref.uri} not found`)}let completer=template.resourceTemplate.completeCallback(request.params.argument.name);if(!completer)return EMPTY_COMPLETION_RESULT;let suggestions=await completer(request.params.argument.value,request.params.context);return createCompletionResult(suggestions)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(request,extra)=>{let resources=Object.entries(this._registeredResources).filter(([_,resource])=>resource.enabled).map(([uri,resource])=>({uri,name:resource.name,...resource.metadata})),templateResources=[];for(let template of Object.values(this._registeredResourceTemplates)){if(!template.resourceTemplate.listCallback)continue;let result=await template.resourceTemplate.listCallback(extra);for(let resource of result.resources)templateResources.push({...template.metadata,...resource})}return{resources:[...resources,...templateResources]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([name,template])=>({name,uriTemplate:template.resourceTemplate.uriTemplate.toString(),...template.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(request,extra)=>{let uri=new URL(request.params.uri),resource=this._registeredResources[uri.toString()];if(resource){if(!resource.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} disabled`);return resource.readCallback(uri,extra)}for(let template of Object.values(this._registeredResourceTemplates)){let variables=template.resourceTemplate.uriTemplate.match(uri.toString());if(variables)return template.readCallback(uri,variables,extra)}throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,prompt])=>prompt.enabled).map(([name,prompt])=>({name,title:prompt.title,description:prompt.description,arguments:prompt.argsSchema?promptArgumentsFromSchema(prompt.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(request,extra)=>{let prompt=this._registeredPrompts[request.params.name];if(!prompt)throw new McpError(ErrorCode.InvalidParams,`Prompt ${request.params.name} not found`);if(!prompt.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${request.params.name} disabled`);if(prompt.argsSchema){let argsObj=normalizeObjectSchema(prompt.argsSchema),parseResult=await safeParseAsync2(argsObj,request.params.arguments);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage4=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${request.params.name}: ${errorMessage4}`)}let args=parseResult.data,cb=prompt.callback;return await Promise.resolve(cb(args,extra))}else{let cb=prompt.callback;return await Promise.resolve(cb(extra))}}),this._promptHandlersInitialized=!0)}resource(name,uriOrTemplate,...rest){let metadata;typeof rest[0]=="object"&&(metadata=rest.shift());let readCallback=rest[0];if(typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,void 0,uriOrTemplate,metadata,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,void 0,uriOrTemplate,metadata,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}registerResource(name,uriOrTemplate,config,readCallback){if(typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,config.title,uriOrTemplate,config,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,config.title,uriOrTemplate,config,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}_createRegisteredResource(name,title,uri,metadata,readCallback){let registeredResource={name,title,metadata,readCallback,enabled:!0,disable:__name(()=>registeredResource.update({enabled:!1}),"disable"),enable:__name(()=>registeredResource.update({enabled:!0}),"enable"),remove:__name(()=>registeredResource.update({uri:null}),"remove"),update:__name(updates=>{typeof updates.uri<"u"&&updates.uri!==uri&&(delete this._registeredResources[uri],updates.uri&&(this._registeredResources[updates.uri]=registeredResource)),typeof updates.name<"u"&&(registeredResource.name=updates.name),typeof updates.title<"u"&&(registeredResource.title=updates.title),typeof updates.metadata<"u"&&(registeredResource.metadata=updates.metadata),typeof updates.callback<"u"&&(registeredResource.readCallback=updates.callback),typeof updates.enabled<"u"&&(registeredResource.enabled=updates.enabled),this.sendResourceListChanged()},"update")};return this._registeredResources[uri]=registeredResource,registeredResource}_createRegisteredResourceTemplate(name,title,template,metadata,readCallback){let registeredResourceTemplate={resourceTemplate:template,title,metadata,readCallback,enabled:!0,disable:__name(()=>registeredResourceTemplate.update({enabled:!1}),"disable"),enable:__name(()=>registeredResourceTemplate.update({enabled:!0}),"enable"),remove:__name(()=>registeredResourceTemplate.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(delete this._registeredResourceTemplates[name],updates.name&&(this._registeredResourceTemplates[updates.name]=registeredResourceTemplate)),typeof updates.title<"u"&&(registeredResourceTemplate.title=updates.title),typeof updates.template<"u"&&(registeredResourceTemplate.resourceTemplate=updates.template),typeof updates.metadata<"u"&&(registeredResourceTemplate.metadata=updates.metadata),typeof updates.callback<"u"&&(registeredResourceTemplate.readCallback=updates.callback),typeof updates.enabled<"u"&&(registeredResourceTemplate.enabled=updates.enabled),this.sendResourceListChanged()},"update")};this._registeredResourceTemplates[name]=registeredResourceTemplate;let variableNames=template.uriTemplate.variableNames;return Array.isArray(variableNames)&&variableNames.some(v=>!!template.completeCallback(v))&&this.setCompletionRequestHandler(),registeredResourceTemplate}_createRegisteredPrompt(name,title,description,argsSchema,callback){let registeredPrompt={title,description,argsSchema:argsSchema===void 0?void 0:objectFromShape(argsSchema),callback,enabled:!0,disable:__name(()=>registeredPrompt.update({enabled:!1}),"disable"),enable:__name(()=>registeredPrompt.update({enabled:!0}),"enable"),remove:__name(()=>registeredPrompt.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(delete this._registeredPrompts[name],updates.name&&(this._registeredPrompts[updates.name]=registeredPrompt)),typeof updates.title<"u"&&(registeredPrompt.title=updates.title),typeof updates.description<"u"&&(registeredPrompt.description=updates.description),typeof updates.argsSchema<"u"&&(registeredPrompt.argsSchema=objectFromShape(updates.argsSchema)),typeof updates.callback<"u"&&(registeredPrompt.callback=updates.callback),typeof updates.enabled<"u"&&(registeredPrompt.enabled=updates.enabled),this.sendPromptListChanged()},"update")};return this._registeredPrompts[name]=registeredPrompt,argsSchema&&Object.values(argsSchema).some(field=>{let inner=field instanceof ZodOptional?field._def?.innerType:field;return isCompletable(inner)})&&this.setCompletionRequestHandler(),registeredPrompt}_createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations2,execution,_meta,handler){validateAndWarnToolName(name);let registeredTool={title,description,inputSchema:getZodSchemaObject(inputSchema),outputSchema:getZodSchemaObject(outputSchema),annotations:annotations2,execution,_meta,handler,enabled:!0,disable:__name(()=>registeredTool.update({enabled:!1}),"disable"),enable:__name(()=>registeredTool.update({enabled:!0}),"enable"),remove:__name(()=>registeredTool.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(typeof updates.name=="string"&&validateAndWarnToolName(updates.name),delete this._registeredTools[name],updates.name&&(this._registeredTools[updates.name]=registeredTool)),typeof updates.title<"u"&&(registeredTool.title=updates.title),typeof updates.description<"u"&&(registeredTool.description=updates.description),typeof updates.paramsSchema<"u"&&(registeredTool.inputSchema=objectFromShape(updates.paramsSchema)),typeof updates.outputSchema<"u"&&(registeredTool.outputSchema=objectFromShape(updates.outputSchema)),typeof updates.callback<"u"&&(registeredTool.handler=updates.callback),typeof updates.annotations<"u"&&(registeredTool.annotations=updates.annotations),typeof updates._meta<"u"&&(registeredTool._meta=updates._meta),typeof updates.enabled<"u"&&(registeredTool.enabled=updates.enabled),this.sendToolListChanged()},"update")};return this._registeredTools[name]=registeredTool,this.setToolRequestHandlers(),this.sendToolListChanged(),registeredTool}tool(name,...rest){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let description,inputSchema,outputSchema,annotations2;if(typeof rest[0]=="string"&&(description=rest.shift()),rest.length>1){let firstArg=rest[0];isZodRawShapeCompat(firstArg)?(inputSchema=rest.shift(),rest.length>1&&typeof rest[0]=="object"&&rest[0]!==null&&!isZodRawShapeCompat(rest[0])&&(annotations2=rest.shift())):typeof firstArg=="object"&&firstArg!==null&&(annotations2=rest.shift())}let callback=rest[0];return this._createRegisteredTool(name,void 0,description,inputSchema,outputSchema,annotations2,{taskSupport:"forbidden"},void 0,callback)}registerTool(name,config,cb){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let{title,description,inputSchema,outputSchema,annotations:annotations2,_meta}=config;return this._createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations2,{taskSupport:"forbidden"},_meta,cb)}prompt(name,...rest){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let description;typeof rest[0]=="string"&&(description=rest.shift());let argsSchema;rest.length>1&&(argsSchema=rest.shift());let cb=rest[0],registeredPrompt=this._createRegisteredPrompt(name,void 0,description,argsSchema,cb);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}registerPrompt(name,config,cb){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let{title,description,argsSchema}=config,registeredPrompt=this._createRegisteredPrompt(name,title,description,argsSchema,cb);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(params,sessionId){return this.server.sendLoggingMessage(params,sessionId)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};function isZodTypeLike(value){return value!==null&&typeof value=="object"&&"parse"in value&&typeof value.parse=="function"&&"safeParse"in value&&typeof value.safeParse=="function"}__name(isZodTypeLike,"isZodTypeLike");function isZodSchemaInstance(obj){return"_def"in obj||"_zod"in obj||isZodTypeLike(obj)}__name(isZodSchemaInstance,"isZodSchemaInstance");function isZodRawShapeCompat(obj){return typeof obj!="object"||obj===null||isZodSchemaInstance(obj)?!1:Object.keys(obj).length===0?!0:Object.values(obj).some(isZodTypeLike)}__name(isZodRawShapeCompat,"isZodRawShapeCompat");function getZodSchemaObject(schema){if(schema)return isZodRawShapeCompat(schema)?objectFromShape(schema):schema}__name(getZodSchemaObject,"getZodSchemaObject");function promptArgumentsFromSchema(schema){let shape=getObjectShape(schema);return shape?Object.entries(shape).map(([name,field])=>{let description=getSchemaDescription(field),isOptional=isSchemaOptional(field);return{name,description,required:!isOptional}}):[]}__name(promptArgumentsFromSchema,"promptArgumentsFromSchema");function getMethodValue(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value=="string")return value;throw new Error("Schema method literal must be a string")}__name(getMethodValue,"getMethodValue");function createCompletionResult(suggestions){return{completion:{values:suggestions.slice(0,100),total:suggestions.length,hasMore:suggestions.length>100}}}__name(createCompletionResult,"createCompletionResult");var EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var MCP_SERVER_NAME="fimo",MCP_SERVER_VERSION="0.2.0";function toolError(code2,message){return{content:[{type:"text",text:JSON.stringify({code:code2,message})}],isError:!0}}__name(toolError,"toolError");function toolResult(payload){return{content:[{type:"text",text:JSON.stringify(payload)}]}}__name(toolResult,"toolResult");async function responseBody(response){let text3=await response.text();if(!text3)return null;try{return JSON.parse(text3)}catch{return{message:text3}}}__name(responseBody,"responseBody");async function mapResponse(response){let body=await responseBody(response);if(!response.ok){let payload=body&&typeof body=="object"?body:null,code2=payload&&typeof payload.code=="string"?payload.code:`http_${response.status}`,message=payload&&typeof payload.message=="string"?payload.message:`Fimo API request failed with status ${response.status}.`;return toolError(code2,message)}return{content:[{type:"text",text:JSON.stringify(body)}]}}__name(mapResponse,"mapResponse");function resolveScope2(tool,input,host){if(tool.scope==="none")return{ok:!0,scope:{projectId:"",env:""}};let projectId=typeof input.projectId=="string"?input.projectId:host.defaults?.projectId;if(!projectId)return{ok:!1,error:toolError("missing_project","Pass projectId \u2014 this MCP server is not bound to a project.")};if(tool.scope==="project")return{ok:!0,scope:{projectId,env:""}};let env=typeof input.env=="string"?input.env:host.defaults?.env;return env?{ok:!0,scope:{projectId,env}}:{ok:!1,error:toolError("missing_env","Pass env (for example 'main') \u2014 this MCP server is not bound to an environment.")}}__name(resolveScope2,"resolveScope");async function runTool(host,name,tool,input){let resolution=resolveScope2(tool,input,host);if(!resolution.ok)return resolution.error;if(host.authorize)try{await host.authorize({tool:name,accessScope:tool.accessScope,operation:tool.operation,projectId:resolution.scope.projectId||void 0,env:resolution.scope.env||void 0})}catch(error){let code2=error&&typeof error=="object"&&typeof error.code=="string"?error.code:"authorization_denied";return toolError(code2,error instanceof Error?error.message:String(error))}if(!tool.buildRequest){let identity2=await host.identity();return toolResult(identity2)}let request=tool.buildRequest(input,resolution.scope),response;try{response=await host.dispatch(request)}catch(error){return toolError("dispatch_failed",error instanceof Error?error.message:String(error))}return mapResponse(response)}__name(runTool,"runTool");function createFimoMcpServer(host){let server=new McpServer({name:MCP_SERVER_NAME,version:MCP_SERVER_VERSION});for(let[name,definition]of Object.entries(mcpToolCatalog)){let tool=definition;server.registerTool(name,{description:tool.description,inputSchema:tool.inputSchema,annotations:tool.annotations},async input=>runTool(host,name,tool,input??{}))}return server}__name(createFimoMcpServer,"createFimoMcpServer");import process8 from"node:process";var ReadBuffer=class{static{__name(this,"ReadBuffer")}append(chunk){this._buffer=this._buffer?Buffer.concat([this._buffer,chunk]):chunk}readMessage(){if(!this._buffer)return null;let index2=this._buffer.indexOf(`
|
|
1357
|
+
]`;continue}pattern+=source[i],source[i]==="\\"?isEscaped2=!0:inCharGroup&&source[i]==="]"?inCharGroup=!1:!inCharGroup&&source[i]==="["&&(inCharGroup=!0)}try{new RegExp(pattern)}catch{return console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),regex.source}return pattern}__name(stringifyRegExpWithFlags,"stringifyRegExpWithFlags");function parseRecordDef(def,refs){if(refs.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),refs.target==="openApi3"&&def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodEnum)return{type:"object",required:def.keyType._def.values,properties:def.keyType._def.values.reduce((acc,key)=>({...acc,[key]:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"properties",key]})??parseAnyDef(refs)}),{}),additionalProperties:refs.rejectedAdditionalProperties};let schema={type:"object",additionalProperties:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]})??refs.allowedAdditionalProperties};if(refs.target==="openApi3")return schema;if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodString&&def.keyType._def.checks?.length){let{type,...keyType}=parseStringDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}else{if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodEnum)return{...schema,propertyNames:{enum:def.keyType._def.values}};if(def.keyType?._def.typeName===ZodFirstPartyTypeKind2.ZodBranded&&def.keyType._def.type._def.typeName===ZodFirstPartyTypeKind2.ZodString&&def.keyType._def.type._def.checks?.length){let{type,...keyType}=parseBrandedDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}}return schema}__name(parseRecordDef,"parseRecordDef");function parseMapDef(def,refs){if(refs.mapStrategy==="record")return parseRecordDef(def,refs);let keys=parseDef(def.keyType._def,{...refs,currentPath:[...refs.currentPath,"items","items","0"]})||parseAnyDef(refs),values=parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items","items","1"]})||parseAnyDef(refs);return{type:"array",maxItems:125,items:{type:"array",items:[keys,values],minItems:2,maxItems:2}}}__name(parseMapDef,"parseMapDef");function parseNativeEnumDef(def){let object4=def.values,actualValues=Object.keys(def.values).filter(key=>typeof object4[object4[key]]!="number").map(key=>object4[key]),parsedTypes=Array.from(new Set(actualValues.map(values=>typeof values)));return{type:parsedTypes.length===1?parsedTypes[0]==="string"?"string":"number":["string","number"],enum:actualValues}}__name(parseNativeEnumDef,"parseNativeEnumDef");function parseNeverDef(refs){return refs.target==="openAi"?void 0:{not:parseAnyDef({...refs,currentPath:[...refs.currentPath,"not"]})}}__name(parseNeverDef,"parseNeverDef");function parseNullDef(refs){return refs.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}__name(parseNullDef,"parseNullDef");var primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(def,refs){if(refs.target==="openApi3")return asAnyOf(def,refs);let options=def.options instanceof Map?Array.from(def.options.values()):def.options;if(options.every(x=>x._def.typeName in primitiveMappings&&(!x._def.checks||!x._def.checks.length))){let types=options.reduce((types2,x)=>{let type=primitiveMappings[x._def.typeName];return type&&!types2.includes(type)?[...types2,type]:types2},[]);return{type:types.length>1?types:types[0]}}else if(options.every(x=>x._def.typeName==="ZodLiteral"&&!x.description)){let types=options.reduce((acc,x)=>{let type=typeof x._def.value;switch(type){case"string":case"number":case"boolean":return[...acc,type];case"bigint":return[...acc,"integer"];case"object":if(x._def.value===null)return[...acc,"null"];default:return acc}},[]);if(types.length===options.length){let uniqueTypes=types.filter((x,i,a)=>a.indexOf(x)===i);return{type:uniqueTypes.length>1?uniqueTypes:uniqueTypes[0],enum:options.reduce((acc,x)=>acc.includes(x._def.value)?acc:[...acc,x._def.value],[])}}}else if(options.every(x=>x._def.typeName==="ZodEnum"))return{type:"string",enum:options.reduce((acc,x)=>[...acc,...x._def.values.filter(x2=>!acc.includes(x2))],[])};return asAnyOf(def,refs)}__name(parseUnionDef,"parseUnionDef");var asAnyOf=__name((def,refs)=>{let anyOf=(def.options instanceof Map?Array.from(def.options.values()):def.options).map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"anyOf",`${i}`]})).filter(x=>!!x&&(!refs.strictUnions||typeof x=="object"&&Object.keys(x).length>0));return anyOf.length?{anyOf}:void 0},"asAnyOf");function parseNullableDef(def,refs){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(def.innerType._def.typeName)&&(!def.innerType._def.checks||!def.innerType._def.checks.length))return refs.target==="openApi3"?{type:primitiveMappings[def.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[def.innerType._def.typeName],"null"]};if(refs.target==="openApi3"){let base2=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath]});return base2&&"$ref"in base2?{allOf:[base2],nullable:!0}:base2&&{...base2,nullable:!0}}let base=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","0"]});return base&&{anyOf:[base,{type:"null"}]}}__name(parseNullableDef,"parseNullableDef");function parseNumberDef(def,refs){let res={type:"number"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"int":res.type="integer",addErrorMessage(res,"type",check.message,refs);break;case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseNumberDef,"parseNumberDef");function parseObjectDef(def,refs){let forceOptionalIntoNullable=refs.target==="openAi",result={type:"object",properties:{}},required=[],shape=def.shape();for(let propName in shape){let propDef=shape[propName];if(propDef===void 0||propDef._def===void 0)continue;let propOptional=safeIsOptional(propDef);propOptional&&forceOptionalIntoNullable&&(propDef._def.typeName==="ZodOptional"&&(propDef=propDef._def.innerType),propDef.isNullable()||(propDef=propDef.nullable()),propOptional=!1);let parsedDef=parseDef(propDef._def,{...refs,currentPath:[...refs.currentPath,"properties",propName],propertyPath:[...refs.currentPath,"properties",propName]});parsedDef!==void 0&&(result.properties[propName]=parsedDef,propOptional||required.push(propName))}required.length&&(result.required=required);let additionalProperties=decideAdditionalProperties(def,refs);return additionalProperties!==void 0&&(result.additionalProperties=additionalProperties),result}__name(parseObjectDef,"parseObjectDef");function decideAdditionalProperties(def,refs){if(def.catchall._def.typeName!=="ZodNever")return parseDef(def.catchall._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]});switch(def.unknownKeys){case"passthrough":return refs.allowedAdditionalProperties;case"strict":return refs.rejectedAdditionalProperties;case"strip":return refs.removeAdditionalStrategy==="strict"?refs.allowedAdditionalProperties:refs.rejectedAdditionalProperties}}__name(decideAdditionalProperties,"decideAdditionalProperties");function safeIsOptional(schema){try{return schema.isOptional()}catch{return!0}}__name(safeIsOptional,"safeIsOptional");var parseOptionalDef=__name((def,refs)=>{if(refs.currentPath.toString()===refs.propertyPath?.toString())return parseDef(def.innerType._def,refs);let innerSchema=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","1"]});return innerSchema?{anyOf:[{not:parseAnyDef(refs)},innerSchema]}:parseAnyDef(refs)},"parseOptionalDef");var parsePipelineDef=__name((def,refs)=>{if(refs.pipeStrategy==="input")return parseDef(def.in._def,refs);if(refs.pipeStrategy==="output")return parseDef(def.out._def,refs);let a=parseDef(def.in._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),b=parseDef(def.out._def,{...refs,currentPath:[...refs.currentPath,"allOf",a?"1":"0"]});return{allOf:[a,b].filter(x=>x!==void 0)}},"parsePipelineDef");function parsePromiseDef(def,refs){return parseDef(def.type._def,refs)}__name(parsePromiseDef,"parsePromiseDef");function parseSetDef(def,refs){let schema={type:"array",uniqueItems:!0,items:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items"]})};return def.minSize&&setResponseValueAndErrors(schema,"minItems",def.minSize.value,def.minSize.message,refs),def.maxSize&&setResponseValueAndErrors(schema,"maxItems",def.maxSize.value,def.maxSize.message,refs),schema}__name(parseSetDef,"parseSetDef");function parseTupleDef(def,refs){return def.rest?{type:"array",minItems:def.items.length,items:def.items.map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"items",`${i}`]})).reduce((acc,x)=>x===void 0?acc:[...acc,x],[]),additionalItems:parseDef(def.rest._def,{...refs,currentPath:[...refs.currentPath,"additionalItems"]})}:{type:"array",minItems:def.items.length,maxItems:def.items.length,items:def.items.map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"items",`${i}`]})).reduce((acc,x)=>x===void 0?acc:[...acc,x],[])}}__name(parseTupleDef,"parseTupleDef");function parseUndefinedDef(refs){return{not:parseAnyDef(refs)}}__name(parseUndefinedDef,"parseUndefinedDef");function parseUnknownDef(refs){return parseAnyDef(refs)}__name(parseUnknownDef,"parseUnknownDef");var parseReadonlyDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseReadonlyDef");var selectParser=__name((def,typeName,refs)=>{switch(typeName){case ZodFirstPartyTypeKind3.ZodString:return parseStringDef(def,refs);case ZodFirstPartyTypeKind3.ZodNumber:return parseNumberDef(def,refs);case ZodFirstPartyTypeKind3.ZodObject:return parseObjectDef(def,refs);case ZodFirstPartyTypeKind3.ZodBigInt:return parseBigintDef(def,refs);case ZodFirstPartyTypeKind3.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind3.ZodDate:return parseDateDef(def,refs);case ZodFirstPartyTypeKind3.ZodUndefined:return parseUndefinedDef(refs);case ZodFirstPartyTypeKind3.ZodNull:return parseNullDef(refs);case ZodFirstPartyTypeKind3.ZodArray:return parseArrayDef(def,refs);case ZodFirstPartyTypeKind3.ZodUnion:case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:return parseUnionDef(def,refs);case ZodFirstPartyTypeKind3.ZodIntersection:return parseIntersectionDef(def,refs);case ZodFirstPartyTypeKind3.ZodTuple:return parseTupleDef(def,refs);case ZodFirstPartyTypeKind3.ZodRecord:return parseRecordDef(def,refs);case ZodFirstPartyTypeKind3.ZodLiteral:return parseLiteralDef(def,refs);case ZodFirstPartyTypeKind3.ZodEnum:return parseEnumDef(def);case ZodFirstPartyTypeKind3.ZodNativeEnum:return parseNativeEnumDef(def);case ZodFirstPartyTypeKind3.ZodNullable:return parseNullableDef(def,refs);case ZodFirstPartyTypeKind3.ZodOptional:return parseOptionalDef(def,refs);case ZodFirstPartyTypeKind3.ZodMap:return parseMapDef(def,refs);case ZodFirstPartyTypeKind3.ZodSet:return parseSetDef(def,refs);case ZodFirstPartyTypeKind3.ZodLazy:return()=>def.getter()._def;case ZodFirstPartyTypeKind3.ZodPromise:return parsePromiseDef(def,refs);case ZodFirstPartyTypeKind3.ZodNaN:case ZodFirstPartyTypeKind3.ZodNever:return parseNeverDef(refs);case ZodFirstPartyTypeKind3.ZodEffects:return parseEffectsDef(def,refs);case ZodFirstPartyTypeKind3.ZodAny:return parseAnyDef(refs);case ZodFirstPartyTypeKind3.ZodUnknown:return parseUnknownDef(refs);case ZodFirstPartyTypeKind3.ZodDefault:return parseDefaultDef(def,refs);case ZodFirstPartyTypeKind3.ZodBranded:return parseBrandedDef(def,refs);case ZodFirstPartyTypeKind3.ZodReadonly:return parseReadonlyDef(def,refs);case ZodFirstPartyTypeKind3.ZodCatch:return parseCatchDef(def,refs);case ZodFirstPartyTypeKind3.ZodPipeline:return parsePipelineDef(def,refs);case ZodFirstPartyTypeKind3.ZodFunction:case ZodFirstPartyTypeKind3.ZodVoid:case ZodFirstPartyTypeKind3.ZodSymbol:return;default:return(_=>{})(typeName)}},"selectParser");function parseDef(def,refs,forceResolution=!1){let seenItem=refs.seen.get(def);if(refs.override){let overrideResult=refs.override?.(def,refs,seenItem,forceResolution);if(overrideResult!==ignoreOverride)return overrideResult}if(seenItem&&!forceResolution){let seenSchema=get$ref(seenItem,refs);if(seenSchema!==void 0)return seenSchema}let newItem={def,path:refs.currentPath,jsonSchema:void 0};refs.seen.set(def,newItem);let jsonSchemaOrGetter=selectParser(def,def.typeName,refs),jsonSchema=typeof jsonSchemaOrGetter=="function"?parseDef(jsonSchemaOrGetter(),refs):jsonSchemaOrGetter;if(jsonSchema&&addMeta(def,refs,jsonSchema),refs.postProcess){let postProcessResult=refs.postProcess(jsonSchema,def,refs);return newItem.jsonSchema=jsonSchema,postProcessResult}return newItem.jsonSchema=jsonSchema,jsonSchema}__name(parseDef,"parseDef");var get$ref=__name((item,refs)=>{switch(refs.$refStrategy){case"root":return{$ref:item.path.join("/")};case"relative":return{$ref:getRelativePath(refs.currentPath,item.path)};case"none":case"seen":return item.path.length<refs.currentPath.length&&item.path.every((value,index2)=>refs.currentPath[index2]===value)?(console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`),parseAnyDef(refs)):refs.$refStrategy==="seen"?parseAnyDef(refs):void 0}},"get$ref"),addMeta=__name((def,refs,jsonSchema)=>(def.description&&(jsonSchema.description=def.description,refs.markdownDescription&&(jsonSchema.markdownDescription=def.description)),jsonSchema),"addMeta");var zodToJsonSchema=__name((schema,options)=>{let refs=getRefs(options),definitions=typeof options=="object"&&options.definitions?Object.entries(options.definitions).reduce((acc,[name2,schema2])=>({...acc,[name2]:parseDef(schema2._def,{...refs,currentPath:[...refs.basePath,refs.definitionPath,name2]},!0)??parseAnyDef(refs)}),{}):void 0,name=typeof options=="string"?options:options?.nameStrategy==="title"?void 0:options?.name,main=parseDef(schema._def,name===void 0?refs:{...refs,currentPath:[...refs.basePath,refs.definitionPath,name]},!1)??parseAnyDef(refs),title=typeof options=="object"&&options.name!==void 0&&options.nameStrategy==="title"?options.name:void 0;title!==void 0&&(main.title=title),refs.flags.hasReferencedOpenAiAnyType&&(definitions||(definitions={}),definitions[refs.openAiAnyTypeName]||(definitions[refs.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:refs.$refStrategy==="relative"?"1":[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName].join("/")}}));let combined=name===void 0?definitions?{...main,[refs.definitionPath]:definitions}:main:{$ref:[...refs.$refStrategy==="relative"?[]:refs.basePath,refs.definitionPath,name].join("/"),[refs.definitionPath]:{...definitions,[name]:main}};return refs.target==="jsonSchema7"?combined.$schema="http://json-schema.org/draft-07/schema#":(refs.target==="jsonSchema2019-09"||refs.target==="openAi")&&(combined.$schema="https://json-schema.org/draft/2019-09/schema#"),refs.target==="openAi"&&("anyOf"in combined||"oneOf"in combined||"allOf"in combined||"type"in combined&&Array.isArray(combined.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),combined},"zodToJsonSchema");function mapMiniTarget(t2){return!t2||t2==="jsonSchema7"||t2==="draft-7"?"draft-7":t2==="jsonSchema2019-09"||t2==="draft-2020-12"?"draft-2020-12":"draft-7"}__name(mapMiniTarget,"mapMiniTarget");function toJsonSchemaCompat(schema,opts){return isZ4Schema(schema)?z4mini2.toJSONSchema(schema,{target:mapMiniTarget(opts?.target),io:opts?.pipeStrategy??"input"}):zodToJsonSchema(schema,{strictUnions:opts?.strictUnions??!0,pipeStrategy:opts?.pipeStrategy??"input"})}__name(toJsonSchemaCompat,"toJsonSchemaCompat");function getMethodLiteral(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value!="string")throw new Error("Schema method literal must be a string");return value}__name(getMethodLiteral,"getMethodLiteral");function parseWithCompat(schema,data2){let result=safeParse3(schema,data2);if(!result.success)throw result.error;return result.data}__name(parseWithCompat,"parseWithCompat");var DEFAULT_REQUEST_TIMEOUT_MSEC=6e4,Protocol=class{static{__name(this,"Protocol")}constructor(_options){this._options=_options,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(CancelledNotificationSchema,notification=>{this._oncancel(notification)}),this.setNotificationHandler(ProgressNotificationSchema,notification=>{this._onprogress(notification)}),this.setRequestHandler(PingRequestSchema,_request=>({})),this._taskStore=_options?.taskStore,this._taskMessageQueue=_options?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(request,extra)=>{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return{...task}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(request,extra)=>{let handleTaskResult=__name(async()=>{let taskId=request.params.taskId;if(this._taskMessageQueue){let queuedMessage;for(;queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId);){if(queuedMessage.type==="response"||queuedMessage.type==="error"){let message=queuedMessage.message,requestId=message.id,resolver=this._requestResolvers.get(requestId);if(resolver)if(this._requestResolvers.delete(requestId),queuedMessage.type==="response")resolver(message);else{let errorMessage5=message,error=new McpError(errorMessage5.error.code,errorMessage5.error.message,errorMessage5.error.data);resolver(error)}else{let messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(new Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}let task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(!isTerminal(task.status))return await this._waitForTaskUpdate(taskId,extra.signal),await handleTaskResult();if(isTerminal(task.status)){let result=await this._taskStore.getTaskResult(taskId,extra.sessionId);return this._clearTaskQueue(taskId),{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()},"handleTaskResult");return await handleTaskResult()}),this.setRequestHandler(ListTasksRequestSchema,async(request,extra)=>{try{let{tasks,nextCursor}=await this._taskStore.listTasks(request.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error instanceof Error?error.message:String(error)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(request,extra)=>{try{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request.params.taskId}`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`);await this._taskStore.updateTaskStatus(request.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId),this._clearTaskQueue(request.params.taskId);let cancelledTask=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!cancelledTask)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request.params.taskId}`);return{_meta:{},...cancelledTask}}catch(error){throw error instanceof McpError?error:new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error instanceof Error?error.message:String(error)}`)}}))}async _oncancel(notification){if(!notification.params.requestId)return;this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);info&&(clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId))}async connect(transport){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.(),this._onclose()};let _onerror=this.transport?.onerror;this._transport.onerror=error=>{_onerror?.(error),this._onerror(error)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?this._onresponse(message):isJSONRPCRequest(message)?this._onrequest(message,extra):isJSONRPCNotification(message)?this._onnotification(message):this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))},await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let controller of this._requestHandlerAbortControllers.values())controller.abort();this._requestHandlerAbortControllers.clear();let error=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let handler of responseHandlers.values())handler(error)}_onerror(error){this.onerror?.(error)}_onnotification(notification){let handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;handler!==void 0&&Promise.resolve().then(()=>handler(notification)).catch(error=>this._onerror(new Error(`Uncaught error in notification handler: ${error}`)))}_onrequest(request,extra){let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler,capturedTransport=this._transport,relatedTaskId=request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(handler===void 0){let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};relatedTaskId&&this._taskMessageQueue?this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch(error=>this._onerror(new Error(`Failed to enqueue error response: ${error}`))):capturedTransport?.send(errorResponse).catch(error=>this._onerror(new Error(`Failed to send an error response: ${error}`)));return}let abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let taskCreationParams=isTaskAugmentedRequestParams(request.params)?request.params.task:void 0,taskStore=this._taskStore?this.requestTaskStore(request,capturedTransport?.sessionId):void 0,fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request.params?._meta,sendNotification:__name(async notification=>{if(abortController.signal.aborted)return;let notificationOptions={relatedRequestId:request.id};relatedTaskId&&(notificationOptions.relatedTask={taskId:relatedTaskId}),await this.notification(notification,notificationOptions)},"sendNotification"),sendRequest:__name(async(r,resultSchema,options)=>{if(abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");let requestOptions={...options,relatedRequestId:request.id};relatedTaskId&&!requestOptions.relatedTask&&(requestOptions.relatedTask={taskId:relatedTaskId});let effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;return effectiveTaskId&&taskStore&&await taskStore.updateTaskStatus(effectiveTaskId,"input_required"),await this.request(r,resultSchema,requestOptions)},"sendRequest"),authInfo:extra?.authInfo,requestId:request.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};Promise.resolve().then(()=>{taskCreationParams&&this.assertTaskHandlerCapability(request.method)}).then(()=>handler(request,fullExtra)).then(async result=>{if(abortController.signal.aborted)return;let response={result,jsonrpc:"2.0",id:request.id};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(response)},async error=>{if(abortController.signal.aborted)return;let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:Number.isSafeInteger(error.code)?error.code:ErrorCode.InternalError,message:error.message??"Internal error",...error.data!==void 0&&{data:error.data}}};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(errorResponse)}).catch(error=>this._onerror(new Error(`Failed to send response: ${error}`))).finally(()=>{this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error);return}handler(params)}_onresponse(response){let messageId=Number(response.id),resolver=this._requestResolvers.get(messageId);if(resolver){if(this._requestResolvers.delete(messageId),isJSONRPCResultResponse(response))resolver(response);else{let error=new McpError(response.error.code,response.error.message,response.error.data);resolver(error)}return}let handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId);let isTaskResponse=!1;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result=="object"){let result=response.result;if(result.task&&typeof result.task=="object"){let task=result.task;typeof task.taskId=="string"&&(isTaskResponse=!0,this._taskProgressTokens.set(task.taskId,messageId))}}if(isTaskResponse||this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response))handler(response);else{let error=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request,resultSchema,options){let{task}=options??{};if(!task){try{yield{type:"result",result:await this.request(request,resultSchema,options)}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}return}let taskId;try{let createResult=await this.request(request,CreateTaskResultSchema,options);if(createResult.task)taskId=createResult.task.taskId,yield{type:"taskCreated",task:createResult.task};else throw new McpError(ErrorCode.InternalError,"Task creation did not return a task");for(;;){let task2=await this.getTask({taskId},options);if(yield{type:"taskStatus",task:task2},isTerminal(task2.status)){task2.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)}:task2.status==="failed"?yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)}:task2.status==="cancelled"&&(yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)});return}if(task2.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)};return}let pollInterval=task2.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(resolve10=>setTimeout(resolve10,pollInterval)),options?.signal?.throwIfAborted()}}catch(error){yield{type:"error",error:error instanceof McpError?error:new McpError(ErrorCode.InternalError,String(error))}}}request(request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve10,reject)=>{let earlyReject=__name(error=>{reject(error)},"earlyReject");if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method),task&&this.assertTaskCapability(request.method)}catch(e){earlyReject(e);return}options?.signal?.throwIfAborted();let messageId=this._requestMessageId++,jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};options?.onprogress&&(this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta||{},progressToken:messageId}}),task&&(jsonrpcRequest.params={...jsonrpcRequest.params,task}),relatedTask&&(jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}});let cancel=__name(reason=>{this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error2=>this._onerror(new Error(`Failed to send cancellation: ${error2}`)));let error=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));reject(error)},"cancel");this._responseHandlers.set(messageId,response=>{if(!options?.signal?.aborted){if(response instanceof Error)return reject(response);try{let parseResult=safeParse3(resultSchema,response.result);parseResult.success?resolve10(parseResult.data):reject(parseResult.error)}catch(error){reject(error)}}}),options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=__name(()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout})),"timeoutHandler");this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1);let relatedTaskId=relatedTask?.taskId;if(relatedTaskId){let responseResolver=__name(response=>{let handler=this._responseHandlers.get(messageId);handler?handler(response):this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`))},"responseResolver");this._requestResolvers.set(messageId,responseResolver),this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch(error=>{this._cleanupTimeout(messageId),reject(error)})}else this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error=>{this._cleanupTimeout(messageId),reject(error)})})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(notification.method);let relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){let jsonrpcNotification2={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification2,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(notification.method),!this._transport)return;let jsonrpcNotification2={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification2={...jsonrpcNotification2,params:{...jsonrpcNotification2.params,_meta:{...jsonrpcNotification2.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),this._transport?.send(jsonrpcNotification2,options).catch(error=>this._onerror(error))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){let method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method),this._requestHandlers.set(method,(request,extra)=>{let parsed=parseWithCompat(requestSchema,request);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw new Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(notificationSchema,handler){let method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,notification=>{let parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){let progressToken=this._taskProgressTokens.get(taskId);progressToken!==void 0&&(this._progressHandlers.delete(progressToken),this._taskProgressTokens.delete(taskId))}async _enqueueTaskMessage(taskId,message,sessionId){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message,sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){let messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(let message of messages)if(message.type==="request"&&isJSONRPCRequest(message.message)){let requestId=message.message.id,resolver=this._requestResolvers.get(requestId);resolver?(resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(requestId)):this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}async _waitForTaskUpdate(taskId,signal){let interval=this._options?.defaultTaskPollInterval??1e3;try{let task=await this._taskStore?.getTask(taskId);task?.pollInterval&&(interval=task.pollInterval)}catch{}return new Promise((resolve10,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}let timeoutId=setTimeout(resolve10,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId),reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(request,sessionId){let taskStore=this._taskStore;if(!taskStore)throw new Error("No task store configured");return{createTask:__name(async taskParams=>{if(!request)throw new Error("No request provided");return await taskStore.createTask(taskParams,request.id,{method:request.method,params:request.params},sessionId)},"createTask"),getTask:__name(async taskId=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return task},"getTask"),storeTaskResult:__name(async(taskId,status,result)=>{await taskStore.storeTaskResult(taskId,status,result,sessionId);let task=await taskStore.getTask(taskId,sessionId);if(task){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});await this.notification(notification),isTerminal(task.status)&&this._cleanupTaskProgressHandler(taskId)}},"storeTaskResult"),getTaskResult:__name(taskId=>taskStore.getTaskResult(taskId,sessionId),"getTaskResult"),updateTaskStatus:__name(async(taskId,status,statusMessage)=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await taskStore.updateTaskStatus(taskId,status,statusMessage,sessionId);let updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});await this.notification(notification),isTerminal(updatedTask.status)&&this._cleanupTaskProgressHandler(taskId)}},"updateTaskStatus"),listTasks:__name(cursor=>taskStore.listTasks(cursor,sessionId),"listTasks")}}};function isPlainObject2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}__name(isPlainObject2,"isPlainObject");function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];isPlainObject2(baseValue)&&isPlainObject2(addValue)?result[k]={...baseValue,...addValue}:result[k]=addValue}return result}__name(mergeCapabilities,"mergeCapabilities");var import_ajv=__toESM(require_ajv(),1),import_ajv_formats=__toESM(require_dist4(),1);function createDefaultAjvInstance(){let ajv=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_ajv_formats.default)(ajv),ajv}__name(createDefaultAjvInstance,"createDefaultAjvInstance");var AjvJsonSchemaValidator=class{static{__name(this,"AjvJsonSchemaValidator")}constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){let ajvValidator="$id"in schema&&typeof schema.$id=="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return input=>ajvValidator(input)?{valid:!0,data:input,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}};var ExperimentalServerTasks=class{static{__name(this,"ExperimentalServerTasks")}constructor(_server){this._server=_server}requestStream(request,resultSchema,options){return this._server.requestStream(request,resultSchema,options)}createMessageStream(params,options){let clientCapabilities=this._server.getClientCapabilities();if((params.tools||params.toolChoice)&&!clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c2=>c2.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c2=>c2.type==="tool_use");if(hasToolResults){if(lastContent.some(c2=>c2.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c2=>c2.type==="tool_use").map(c2=>c2.id)),toolResultIds=new Set(lastContent.filter(c2=>c2.type==="tool_result").map(c2=>c2.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}elicitInputStream(params,options){let clientCapabilities=this._server.getClientCapabilities(),mode2=params.mode??"form";switch(mode2){case"url":{if(!clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let normalizedParams=mode2==="form"&¶ms.mode===void 0?{...params,mode:"form"}:params;return this.requestStream({method:"elicitation/create",params:normalizedParams},ElicitResultSchema,options)}async getTask(taskId,options){return this._server.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._server.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._server.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._server.cancelTask({taskId},options)}};function assertToolsCallTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"tools/call":if(!requests.tools?.call)throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);break;default:break}}__name(assertToolsCallTaskCapability,"assertToolsCallTaskCapability");function assertClientRequestTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage)throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);break;case"elicitation/create":if(!requests.elicitation?.create)throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);break;default:break}}__name(assertClientRequestTaskCapability,"assertClientRequestTaskCapability");var Server=class extends Protocol{static{__name(this,"Server")}constructor(_serverInfo,options){super(options),this._serverInfo=_serverInfo,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index2)=>[level,index2])),this.isMessageIgnored=(level,sessionId)=>{let currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):!1},this._capabilities=options?.capabilities??{},this._instructions=options?.instructions,this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,request=>this._oninitialize(request)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(request,extra)=>{let transportSessionId=extra.sessionId||extra.requestInfo?.headers["mcp-session-id"]||void 0,{level}=request.params,parseResult=LoggingLevelSchema.safeParse(level);return parseResult.success&&this._loggingLevels.set(transportSessionId,parseResult.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalServerTasks(this)}),this._experimental}registerCapabilities(capabilities){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){let methodSchema=getObjectShape(requestSchema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let methodValue;if(isZ4Schema(methodSchema)){let v4Schema=methodSchema;methodValue=v4Schema._zod?.def?.value??v4Schema.value}else{let v3Schema=methodSchema;methodValue=v3Schema._def?.value??v3Schema.value}if(typeof methodValue!="string")throw new Error("Schema method literal must be a string");if(methodValue==="tools/call"){let wrappedHandler=__name(async(request,extra)=>{let validatedRequest=safeParse3(CallToolRequestSchema,request);if(!validatedRequest.success){let errorMessage5=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${errorMessage5}`)}let{params}=validatedRequest.data,result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse3(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage5=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage5}`)}return taskValidationResult.data}let validationResult=safeParse3(CallToolResultSchema,result);if(!validationResult.success){let errorMessage5=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${errorMessage5}`)}return validationResult.data},"wrappedHandler");return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${method})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${method})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${method})`);break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${method})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${method})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(this._capabilities)switch(method){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${method})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${method})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${method})`);break;case"ping":case"initialize":break}}assertTaskCapability(method){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,method,"Client")}assertTaskHandlerCapability(method){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,method,"Server")}async _oninitialize(request){let requestedVersion=request.params.protocolVersion;return this._clientCapabilities=request.params.capabilities,this._clientVersion=request.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},EmptyResultSchema)}async createMessage(params,options){if((params.tools||params.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c2=>c2.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c2=>c2.type==="tool_use");if(hasToolResults){if(lastContent.some(c2=>c2.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c2=>c2.type==="tool_use").map(c2=>c2.id)),toolResultIds=new Set(lastContent.filter(c2=>c2.type==="tool_result").map(c2=>c2.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return params.tools?this.request({method:"sampling/createMessage",params},CreateMessageResultWithToolsSchema,options):this.request({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}async elicitInput(params,options){switch(params.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let urlParams=params;return this.request({method:"elicitation/create",params:urlParams},ElicitResultSchema,options)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let formParams=params.mode==="form"?params:{...params,mode:"form"},result=await this.request({method:"elicitation/create",params:formParams},ElicitResultSchema,options);if(result.action==="accept"&&result.content&&formParams.requestedSchema)try{let validationResult=this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);if(!validationResult.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}catch(error){throw error instanceof McpError?error:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${error instanceof Error?error.message:String(error)}`)}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this.request({method:"roots/list",params},ListRootsResultSchema,options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging&&!this.isMessageIgnored(params.level,sessionId))return this.notification({method:"notifications/message",params})}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");function isCompletable(schema){return!!schema&&typeof schema=="object"&&COMPLETABLE_SYMBOL in schema}__name(isCompletable,"isCompletable");function getCompleter(schema){return schema[COMPLETABLE_SYMBOL]?.complete}__name(getCompleter,"getCompleter");var McpZodTypeKind;(function(McpZodTypeKind2){McpZodTypeKind2.Completable="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));var TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(name){let warnings=[];if(name.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(name.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]};if(name.includes(" ")&&warnings.push("Tool name contains spaces, which may cause parsing issues"),name.includes(",")&&warnings.push("Tool name contains commas, which may cause parsing issues"),(name.startsWith("-")||name.endsWith("-"))&&warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(name.startsWith(".")||name.endsWith("."))&&warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!TOOL_NAME_REGEX.test(name)){let invalidChars=name.split("").filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index2,arr)=>arr.indexOf(char)===index2);return warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c2=>`"${c2}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings}}return{isValid:!0,warnings}}__name(validateToolName,"validateToolName");function issueToolNameWarning(name,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name}":`);for(let warning of warnings)console.warn(` - ${warning}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}__name(issueToolNameWarning,"issueToolNameWarning");function validateAndWarnToolName(name){let result=validateToolName(name);return issueToolNameWarning(name,result.warnings),result.isValid}__name(validateAndWarnToolName,"validateAndWarnToolName");var ExperimentalMcpServerTasks=class{static{__name(this,"ExperimentalMcpServerTasks")}constructor(_mcpServer){this._mcpServer=_mcpServer}registerToolTask(name,config,handler){let execution={taskSupport:"required",...config.execution};if(execution.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(name,config.title,config.description,config.inputSchema,config.outputSchema,config.annotations,execution,config._meta,handler)}};import{ZodOptional}from"zod";var McpServer=class{static{__name(this,"McpServer")}constructor(serverInfo,options){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(serverInfo,options)}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalMcpServerTasks(this)}),this._experimental}async connect(transport){return await this.server.connect(transport)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,tool])=>tool.enabled).map(([name,tool])=>{let toolDefinition={name,title:tool.title,description:tool.description,inputSchema:(()=>{let obj=normalizeObjectSchema(tool.inputSchema);return obj?toJsonSchemaCompat(obj,{strictUnions:!0,pipeStrategy:"input"}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:tool.annotations,execution:tool.execution,_meta:tool._meta};if(tool.outputSchema){let obj=normalizeObjectSchema(tool.outputSchema);obj&&(toolDefinition.outputSchema=toJsonSchemaCompat(obj,{strictUnions:!0,pipeStrategy:"output"}))}return toolDefinition})})),this.server.setRequestHandler(CallToolRequestSchema,async(request,extra)=>{try{let tool=this._registeredTools[request.params.name];if(!tool)throw new McpError(ErrorCode.InvalidParams,`Tool ${request.params.name} not found`);if(!tool.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${request.params.name} disabled`);let isTaskRequest=!!request.params.task,taskSupport=tool.execution?.taskSupport,isTaskHandler="createTask"in tool.handler;if((taskSupport==="required"||taskSupport==="optional")&&!isTaskHandler)throw new McpError(ErrorCode.InternalError,`Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);if(taskSupport==="required"&&!isTaskRequest)throw new McpError(ErrorCode.MethodNotFound,`Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);if(taskSupport==="optional"&&!isTaskRequest&&isTaskHandler)return await this.handleAutomaticTaskPolling(tool,request,extra);let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),result=await this.executeToolHandler(tool,args,extra);return isTaskRequest||await this.validateToolOutput(tool,result,request.params.name),result}catch(error){if(error instanceof McpError&&error.code===ErrorCode.UrlElicitationRequired)throw error;return this.createToolError(error instanceof Error?error.message:String(error))}}),this._toolHandlersInitialized=!0)}createToolError(errorMessage5){return{content:[{type:"text",text:errorMessage5}],isError:!0}}async validateToolInput(tool,args,toolName){if(!tool.inputSchema)return;let schemaToParse=normalizeObjectSchema(tool.inputSchema)??tool.inputSchema,parseResult=await safeParseAsync2(schemaToParse,args);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage5=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage5}`)}return parseResult.data}async validateToolOutput(tool,result,toolName){if(!tool.outputSchema||!("content"in result)||result.isError)return;if(!result.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);let outputObj=normalizeObjectSchema(tool.outputSchema),parseResult=await safeParseAsync2(outputObj,result.structuredContent);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage5=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage5}`)}}async executeToolHandler(tool,args,extra){let handler=tool.handler;if("createTask"in handler){if(!extra.taskStore)throw new Error("No task store provided.");let taskExtra={...extra,taskStore:extra.taskStore};if(tool.inputSchema){let typedHandler=handler;return await Promise.resolve(typedHandler.createTask(args,taskExtra))}else{let typedHandler=handler;return await Promise.resolve(typedHandler.createTask(taskExtra))}}if(tool.inputSchema){let typedHandler=handler;return await Promise.resolve(typedHandler(args,extra))}else{let typedHandler=handler;return await Promise.resolve(typedHandler(extra))}}async handleAutomaticTaskPolling(tool,request,extra){if(!extra.taskStore)throw new Error("No task store provided for task-capable tool.");let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),handler=tool.handler,taskExtra={...extra,taskStore:extra.taskStore},createTaskResult=args?await Promise.resolve(handler.createTask(args,taskExtra)):await Promise.resolve(handler.createTask(taskExtra)),taskId=createTaskResult.task.taskId,task=createTaskResult.task,pollInterval=task.pollInterval??5e3;for(;task.status!=="completed"&&task.status!=="failed"&&task.status!=="cancelled";){await new Promise(resolve10=>setTimeout(resolve10,pollInterval));let updatedTask=await extra.taskStore.getTask(taskId);if(!updatedTask)throw new McpError(ErrorCode.InternalError,`Task ${taskId} not found during polling`);task=updatedTask}return await extra.taskStore.getTaskResult(taskId)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async request=>{switch(request.params.ref.type){case"ref/prompt":return assertCompleteRequestPrompt(request),this.handlePromptCompletion(request,request.params.ref);case"ref/resource":return assertCompleteRequestResourceTemplate(request),this.handleResourceCompletion(request,request.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${request.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(request,ref){let prompt=this._registeredPrompts[ref.name];if(!prompt)throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} not found`);if(!prompt.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} disabled`);if(!prompt.argsSchema)return EMPTY_COMPLETION_RESULT;let field=getObjectShape(prompt.argsSchema)?.[request.params.argument.name];if(!isCompletable(field))return EMPTY_COMPLETION_RESULT;let completer=getCompleter(field);if(!completer)return EMPTY_COMPLETION_RESULT;let suggestions=await completer(request.params.argument.value,request.params.context);return createCompletionResult(suggestions)}async handleResourceCompletion(request,ref){let template=Object.values(this._registeredResourceTemplates).find(t2=>t2.resourceTemplate.uriTemplate.toString()===ref.uri);if(!template){if(this._registeredResources[ref.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${request.params.ref.uri} not found`)}let completer=template.resourceTemplate.completeCallback(request.params.argument.name);if(!completer)return EMPTY_COMPLETION_RESULT;let suggestions=await completer(request.params.argument.value,request.params.context);return createCompletionResult(suggestions)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(request,extra)=>{let resources=Object.entries(this._registeredResources).filter(([_,resource])=>resource.enabled).map(([uri,resource])=>({uri,name:resource.name,...resource.metadata})),templateResources=[];for(let template of Object.values(this._registeredResourceTemplates)){if(!template.resourceTemplate.listCallback)continue;let result=await template.resourceTemplate.listCallback(extra);for(let resource of result.resources)templateResources.push({...template.metadata,...resource})}return{resources:[...resources,...templateResources]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([name,template])=>({name,uriTemplate:template.resourceTemplate.uriTemplate.toString(),...template.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(request,extra)=>{let uri=new URL(request.params.uri),resource=this._registeredResources[uri.toString()];if(resource){if(!resource.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} disabled`);return resource.readCallback(uri,extra)}for(let template of Object.values(this._registeredResourceTemplates)){let variables=template.resourceTemplate.uriTemplate.match(uri.toString());if(variables)return template.readCallback(uri,variables,extra)}throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,prompt])=>prompt.enabled).map(([name,prompt])=>({name,title:prompt.title,description:prompt.description,arguments:prompt.argsSchema?promptArgumentsFromSchema(prompt.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(request,extra)=>{let prompt=this._registeredPrompts[request.params.name];if(!prompt)throw new McpError(ErrorCode.InvalidParams,`Prompt ${request.params.name} not found`);if(!prompt.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${request.params.name} disabled`);if(prompt.argsSchema){let argsObj=normalizeObjectSchema(prompt.argsSchema),parseResult=await safeParseAsync2(argsObj,request.params.arguments);if(!parseResult.success){let error="error"in parseResult?parseResult.error:"Unknown error",errorMessage5=getParseErrorMessage(error);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${request.params.name}: ${errorMessage5}`)}let args=parseResult.data,cb=prompt.callback;return await Promise.resolve(cb(args,extra))}else{let cb=prompt.callback;return await Promise.resolve(cb(extra))}}),this._promptHandlersInitialized=!0)}resource(name,uriOrTemplate,...rest){let metadata;typeof rest[0]=="object"&&(metadata=rest.shift());let readCallback=rest[0];if(typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,void 0,uriOrTemplate,metadata,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,void 0,uriOrTemplate,metadata,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}registerResource(name,uriOrTemplate,config,readCallback){if(typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,config.title,uriOrTemplate,config,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,config.title,uriOrTemplate,config,readCallback);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}_createRegisteredResource(name,title,uri,metadata,readCallback){let registeredResource={name,title,metadata,readCallback,enabled:!0,disable:__name(()=>registeredResource.update({enabled:!1}),"disable"),enable:__name(()=>registeredResource.update({enabled:!0}),"enable"),remove:__name(()=>registeredResource.update({uri:null}),"remove"),update:__name(updates=>{typeof updates.uri<"u"&&updates.uri!==uri&&(delete this._registeredResources[uri],updates.uri&&(this._registeredResources[updates.uri]=registeredResource)),typeof updates.name<"u"&&(registeredResource.name=updates.name),typeof updates.title<"u"&&(registeredResource.title=updates.title),typeof updates.metadata<"u"&&(registeredResource.metadata=updates.metadata),typeof updates.callback<"u"&&(registeredResource.readCallback=updates.callback),typeof updates.enabled<"u"&&(registeredResource.enabled=updates.enabled),this.sendResourceListChanged()},"update")};return this._registeredResources[uri]=registeredResource,registeredResource}_createRegisteredResourceTemplate(name,title,template,metadata,readCallback){let registeredResourceTemplate={resourceTemplate:template,title,metadata,readCallback,enabled:!0,disable:__name(()=>registeredResourceTemplate.update({enabled:!1}),"disable"),enable:__name(()=>registeredResourceTemplate.update({enabled:!0}),"enable"),remove:__name(()=>registeredResourceTemplate.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(delete this._registeredResourceTemplates[name],updates.name&&(this._registeredResourceTemplates[updates.name]=registeredResourceTemplate)),typeof updates.title<"u"&&(registeredResourceTemplate.title=updates.title),typeof updates.template<"u"&&(registeredResourceTemplate.resourceTemplate=updates.template),typeof updates.metadata<"u"&&(registeredResourceTemplate.metadata=updates.metadata),typeof updates.callback<"u"&&(registeredResourceTemplate.readCallback=updates.callback),typeof updates.enabled<"u"&&(registeredResourceTemplate.enabled=updates.enabled),this.sendResourceListChanged()},"update")};this._registeredResourceTemplates[name]=registeredResourceTemplate;let variableNames=template.uriTemplate.variableNames;return Array.isArray(variableNames)&&variableNames.some(v=>!!template.completeCallback(v))&&this.setCompletionRequestHandler(),registeredResourceTemplate}_createRegisteredPrompt(name,title,description,argsSchema,callback){let registeredPrompt={title,description,argsSchema:argsSchema===void 0?void 0:objectFromShape(argsSchema),callback,enabled:!0,disable:__name(()=>registeredPrompt.update({enabled:!1}),"disable"),enable:__name(()=>registeredPrompt.update({enabled:!0}),"enable"),remove:__name(()=>registeredPrompt.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(delete this._registeredPrompts[name],updates.name&&(this._registeredPrompts[updates.name]=registeredPrompt)),typeof updates.title<"u"&&(registeredPrompt.title=updates.title),typeof updates.description<"u"&&(registeredPrompt.description=updates.description),typeof updates.argsSchema<"u"&&(registeredPrompt.argsSchema=objectFromShape(updates.argsSchema)),typeof updates.callback<"u"&&(registeredPrompt.callback=updates.callback),typeof updates.enabled<"u"&&(registeredPrompt.enabled=updates.enabled),this.sendPromptListChanged()},"update")};return this._registeredPrompts[name]=registeredPrompt,argsSchema&&Object.values(argsSchema).some(field=>{let inner=field instanceof ZodOptional?field._def?.innerType:field;return isCompletable(inner)})&&this.setCompletionRequestHandler(),registeredPrompt}_createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations2,execution,_meta,handler){validateAndWarnToolName(name);let registeredTool={title,description,inputSchema:getZodSchemaObject(inputSchema),outputSchema:getZodSchemaObject(outputSchema),annotations:annotations2,execution,_meta,handler,enabled:!0,disable:__name(()=>registeredTool.update({enabled:!1}),"disable"),enable:__name(()=>registeredTool.update({enabled:!0}),"enable"),remove:__name(()=>registeredTool.update({name:null}),"remove"),update:__name(updates=>{typeof updates.name<"u"&&updates.name!==name&&(typeof updates.name=="string"&&validateAndWarnToolName(updates.name),delete this._registeredTools[name],updates.name&&(this._registeredTools[updates.name]=registeredTool)),typeof updates.title<"u"&&(registeredTool.title=updates.title),typeof updates.description<"u"&&(registeredTool.description=updates.description),typeof updates.paramsSchema<"u"&&(registeredTool.inputSchema=objectFromShape(updates.paramsSchema)),typeof updates.outputSchema<"u"&&(registeredTool.outputSchema=objectFromShape(updates.outputSchema)),typeof updates.callback<"u"&&(registeredTool.handler=updates.callback),typeof updates.annotations<"u"&&(registeredTool.annotations=updates.annotations),typeof updates._meta<"u"&&(registeredTool._meta=updates._meta),typeof updates.enabled<"u"&&(registeredTool.enabled=updates.enabled),this.sendToolListChanged()},"update")};return this._registeredTools[name]=registeredTool,this.setToolRequestHandlers(),this.sendToolListChanged(),registeredTool}tool(name,...rest){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let description,inputSchema,outputSchema,annotations2;if(typeof rest[0]=="string"&&(description=rest.shift()),rest.length>1){let firstArg=rest[0];isZodRawShapeCompat(firstArg)?(inputSchema=rest.shift(),rest.length>1&&typeof rest[0]=="object"&&rest[0]!==null&&!isZodRawShapeCompat(rest[0])&&(annotations2=rest.shift())):typeof firstArg=="object"&&firstArg!==null&&(annotations2=rest.shift())}let callback=rest[0];return this._createRegisteredTool(name,void 0,description,inputSchema,outputSchema,annotations2,{taskSupport:"forbidden"},void 0,callback)}registerTool(name,config,cb){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let{title,description,inputSchema,outputSchema,annotations:annotations2,_meta}=config;return this._createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations2,{taskSupport:"forbidden"},_meta,cb)}prompt(name,...rest){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let description;typeof rest[0]=="string"&&(description=rest.shift());let argsSchema;rest.length>1&&(argsSchema=rest.shift());let cb=rest[0],registeredPrompt=this._createRegisteredPrompt(name,void 0,description,argsSchema,cb);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}registerPrompt(name,config,cb){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let{title,description,argsSchema}=config,registeredPrompt=this._createRegisteredPrompt(name,title,description,argsSchema,cb);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(params,sessionId){return this.server.sendLoggingMessage(params,sessionId)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};function isZodTypeLike(value){return value!==null&&typeof value=="object"&&"parse"in value&&typeof value.parse=="function"&&"safeParse"in value&&typeof value.safeParse=="function"}__name(isZodTypeLike,"isZodTypeLike");function isZodSchemaInstance(obj){return"_def"in obj||"_zod"in obj||isZodTypeLike(obj)}__name(isZodSchemaInstance,"isZodSchemaInstance");function isZodRawShapeCompat(obj){return typeof obj!="object"||obj===null||isZodSchemaInstance(obj)?!1:Object.keys(obj).length===0?!0:Object.values(obj).some(isZodTypeLike)}__name(isZodRawShapeCompat,"isZodRawShapeCompat");function getZodSchemaObject(schema){if(schema)return isZodRawShapeCompat(schema)?objectFromShape(schema):schema}__name(getZodSchemaObject,"getZodSchemaObject");function promptArgumentsFromSchema(schema){let shape=getObjectShape(schema);return shape?Object.entries(shape).map(([name,field])=>{let description=getSchemaDescription(field),isOptional=isSchemaOptional(field);return{name,description,required:!isOptional}}):[]}__name(promptArgumentsFromSchema,"promptArgumentsFromSchema");function getMethodValue(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value=="string")return value;throw new Error("Schema method literal must be a string")}__name(getMethodValue,"getMethodValue");function createCompletionResult(suggestions){return{completion:{values:suggestions.slice(0,100),total:suggestions.length,hasMore:suggestions.length>100}}}__name(createCompletionResult,"createCompletionResult");var EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var MCP_SERVER_NAME="fimo",MCP_SERVER_VERSION="0.2.0";function toolError(code2,message){return{content:[{type:"text",text:JSON.stringify({code:code2,message})}],isError:!0}}__name(toolError,"toolError");function toolResult(payload){return{content:[{type:"text",text:JSON.stringify(payload)}]}}__name(toolResult,"toolResult");async function responseBody(response){let text3=await response.text();if(!text3)return null;try{return JSON.parse(text3)}catch{return{message:text3}}}__name(responseBody,"responseBody");async function mapResponse(response){let body=await responseBody(response);if(!response.ok){let payload=body&&typeof body=="object"?body:null,code2=payload&&typeof payload.code=="string"?payload.code:`http_${response.status}`,message=payload&&typeof payload.message=="string"?payload.message:`Fimo API request failed with status ${response.status}.`;return toolError(code2,message)}return{content:[{type:"text",text:JSON.stringify(body)}]}}__name(mapResponse,"mapResponse");function resolveScope2(tool,input,host){if(tool.scope==="none")return{ok:!0,scope:{projectId:"",env:""}};let projectId=typeof input.projectId=="string"?input.projectId:host.defaults?.projectId;if(!projectId)return{ok:!1,error:toolError("missing_project","Pass projectId \u2014 this MCP server is not bound to a project.")};if(tool.scope==="project")return{ok:!0,scope:{projectId,env:""}};let env=typeof input.env=="string"?input.env:host.defaults?.env;return env?{ok:!0,scope:{projectId,env}}:{ok:!1,error:toolError("missing_env","Pass env (for example 'main') \u2014 this MCP server is not bound to an environment.")}}__name(resolveScope2,"resolveScope");async function runTool(host,name,tool,input){let resolution=resolveScope2(tool,input,host);if(!resolution.ok)return resolution.error;if(host.authorize)try{await host.authorize({tool:name,accessScope:tool.accessScope,operation:tool.operation,projectId:resolution.scope.projectId||void 0,env:resolution.scope.env||void 0})}catch(error){let code2=error&&typeof error=="object"&&typeof error.code=="string"?error.code:"authorization_denied";return toolError(code2,error instanceof Error?error.message:String(error))}if(!tool.buildRequest){let identity2=await host.identity();return toolResult(identity2)}let request=tool.buildRequest(input,resolution.scope),response;try{response=await host.dispatch(request)}catch(error){return toolError("dispatch_failed",error instanceof Error?error.message:String(error))}return mapResponse(response)}__name(runTool,"runTool");function createFimoMcpServer(host){let server=new McpServer({name:MCP_SERVER_NAME,version:MCP_SERVER_VERSION});for(let[name,definition]of Object.entries(mcpToolCatalog)){let tool=definition;server.registerTool(name,{description:tool.description,inputSchema:tool.inputSchema,annotations:tool.annotations},async input=>runTool(host,name,tool,input??{}))}return server}__name(createFimoMcpServer,"createFimoMcpServer");import process8 from"node:process";var ReadBuffer=class{static{__name(this,"ReadBuffer")}append(chunk){this._buffer=this._buffer?Buffer.concat([this._buffer,chunk]):chunk}readMessage(){if(!this._buffer)return null;let index2=this._buffer.indexOf(`
|
|
1358
1358
|
`);if(index2===-1)return null;let line=this._buffer.toString("utf8",0,index2).replace(/\r$/,"");return this._buffer=this._buffer.subarray(index2+1),deserializeMessage(line)}clear(){this._buffer=void 0}};function deserializeMessage(line){return JSONRPCMessageSchema.parse(JSON.parse(line))}__name(deserializeMessage,"deserializeMessage");function serializeMessage(message){return JSON.stringify(message)+`
|
|
1359
1359
|
`}__name(serializeMessage,"serializeMessage");var StdioServerTransport=class{static{__name(this,"StdioServerTransport")}constructor(_stdin=process8.stdin,_stdout=process8.stdout){this._stdin=_stdin,this._stdout=_stdout,this._readBuffer=new ReadBuffer,this._started=!1,this._ondata=chunk=>{this._readBuffer.append(chunk),this.processReadBuffer()},this._onerror=error=>{this.onerror?.(error)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let message=this._readBuffer.readMessage();if(message===null)break;this.onmessage?.(message)}catch(error){this.onerror?.(error)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(message){return new Promise(resolve10=>{let json=serializeMessage(message);this._stdout.write(json)?resolve10():this._stdout.once("drain",resolve10)})}};init_api();init_config();init_project_context();function createCliMcpHost(client,defaults={}){return{identity:__name(async()=>{let session=await client.getCurrentSession();if(!session)throw new Error("Not signed in. Run `fimo login` or set FIMO_API_TOKEN.");return{id:session.user.id,email:session.user.email??null,name:session.user.name??null}},"identity"),dispatch:__name(request=>client.fetchRaw(`/api${request.path}`,{method:request.method,body:request.body!==void 0?JSON.stringify(request.body):void 0}),"dispatch"),authorize:__name(async({operation,projectId,env})=>{if(operation)try{await requireOperation(operation,{projectId,env})}catch(error){throw error instanceof CapabilityDenied?Object.assign(error,{code:"capability_denied"}):error}},"authorize"),defaults}}__name(createCliMcpHost,"createCliMcpHost");async function resolveDefaults(cmd){try{let ctx=await getProjectContext({envOverride:envOverrideFromCommand(cmd)});return ctx.readOnly?{projectId:ctx.projectId}:{projectId:ctx.projectId,env:ctx.env}}catch(error){if(error instanceof NotInProjectError||error instanceof GitBranchUndetectedError)return{};throw error}}__name(resolveDefaults,"resolveDefaults");async function mcpCommand(_options,cmd){let client=new FimoApiClient(loadConfig()),defaults=await resolveDefaults(cmd),server=createFimoMcpServer(createCliMcpHost(client,defaults)),transport=new StdioServerTransport,closed=new Promise(resolve10=>{server.server.onclose=()=>resolve10()});await server.connect(transport),process.stderr.write(`fimo mcp: serving over stdio${defaults.projectId?` (project ${defaults.projectId}${defaults.env?`, env ${defaults.env}`:""})`:""}
|
|
1360
1360
|
`),await closed}__name(mcpCommand,"mcpCommand");init_esm();init_dist();init_project_context();function taskTokens(task){let argv=process.argv.slice(2),namespaceIndex=argv.indexOf(task.modality);if(namespaceIndex===-1)return[];let verbIndex=argv.indexOf(task.operation,namespaceIndex+1);return verbIndex===-1?[]:argv.slice(verbIndex+1)}__name(taskTokens,"taskTokens");function renderTaskHelp(task){return renderGenerationHelp({usage:`fimo ${task.modality} ${task.operation} [flags]`,description:task.description,flags:task.flags})}__name(renderTaskHelp,"renderTaskHelp");async function runTask(task,command){let tokens=taskTokens(task),wantsHelp=tokens.includes("--help")||tokens.includes("-h"),commandName2=`${task.modality} ${task.operation}`;if(wantsHelp){ui.result({command:commandName2,data:{task},render:__name(()=>renderTaskHelp(task),"render")});return}let{values,bools,options}=parseGenerationFlags({commandName:commandName2,subject:task.id,helpCommand:`fimo ${commandName2} --help`,flags:task.flags,tokens}),body={task:task.id,options,name:values.get("name")?.[0],parentId:values.get("parent")?.[0]??null},isJson=currentMode().format==="json",{ctx,api}=await bootstrapProjectCommand({cwd:values.get("cwd")?.[0]},command,{refuseReadOnly:!0,quiet:isJson});if(bools.get("dry-run")===!0){let estimate=await api.estimateGenerationTask(ctx.projectId,task.id,options),data2={...body,estimate};ui.result({command:commandName2,data:data2,render:__name(()=>JSON.stringify(data2,null,2),"render")});return}await submitGeneration({commandName:commandName2,ctx,api,body})}__name(runTask,"runTask");function registerTaskCommand(parent2,task){parent2.command(task.operation).description(task.description).allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(_options,command)=>{await runTask(task,command)})}__name(registerTaskCommand,"registerTaskCommand");function registerMediaTaskCommands(program2){let image=program2.command("image").description("Generate and transform images"),video=program2.command("video").description("Generate and transform videos");for(let task of GENERATION_TASK_MANIFESTS)registerTaskCommand(task.modality==="image"?image:video,task)}__name(registerMediaTaskCommands,"registerMediaTaskCommands");init_dist5();init_dist();init_api();init_auth_errors();init_color();import{execSync,spawnSync as spawnSync3}from"node:child_process";import{mkdtempSync,readFileSync as readFileSync10,writeFileSync as writeFileSync5}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path41 from"node:path";function renderMergeSuccess(result,p2){let lines=[];if(lines.push(p2.green(`\u2713 Merged ${result.fromEnv} \u2192 ${result.toEnv}`)),result.summary&&lines.push(p2.dim(` ${result.summary}`)),result.applied.length>0){lines.push(""),lines.push(p2.bold("Applied:"));for(let a of result.applied)lines.push(p2.dim(` ${a.surface.padEnd(14)} ${a.count} item${a.count===1?"":"s"}`))}return lines.join(`
|
|
@@ -1380,7 +1380,10 @@ Remote config and local checkout are synchronized.`}__name(renderMutationResult,
|
|
|
1380
1380
|
`;return{content:content3,changed:content3!==existing,created:!1}}return{content:`${[...lines,"",...block].join(`
|
|
1381
1381
|
`)}
|
|
1382
1382
|
`,changed:!0,created:!0}}__name(mergeManagedEnvBlock,"mergeManagedEnvBlock");function renderBlock(entries2,spec){return[spec.start,...spec.header,...Object.entries(entries2).map(([key,value])=>`${key}=${quoteEnvValue(value)}`),spec.end]}__name(renderBlock,"renderBlock");function quoteEnvValue(value){return/^[A-Za-z0-9_./:@-]*$/.test(value)?value:JSON.stringify(value)}__name(quoteEnvValue,"quoteEnvValue");init_project_context();init_project();function registerProjectSecretsCommands(program2){let vars=program2.command("vars").description("Manage project variables");vars.command("list").description("List project variables").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((opts,command)=>listCommand3("variable",opts,command)),vars.command("add <key> [value]").description("Add a project variable").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Variable value").action((key,value,opts,command)=>writeCommand("variable","add",key,opts.value??value,opts,command)),vars.command("update <key> [value]").description("Update an existing project variable").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Variable value").action((key,value,opts,command)=>writeCommand("variable","update",key,opts.value??value,opts,command)),vars.command("unset <key>").alias("remove").description("Delete a project variable").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((key,opts,command)=>unsetCommand("variable",key,opts,command)),vars.command("pull [file]").description("Write public project variables to a local env file").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((file,opts,command)=>pullVarsCommand(file,opts,command));let secrets=program2.command("secrets").description("Manage project secrets");secrets.command("list").description("List project secrets without revealing values").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((opts,command)=>listCommand3("secret",opts,command)),secrets.command("add <key> [value]").description("Add a project secret").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Secret value (prefer --stdin in shells that record history)").action((key,value,opts,command)=>writeCommand("secret","add",key,opts.value??value,opts,command)),secrets.command("update <key> [value]").description("Update an existing project secret").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Secret value (prefer --stdin in shells that record history)").action((key,value,opts,command)=>writeCommand("secret","update",key,opts.value??value,opts,command)),secrets.command("unset <key>").alias("remove").description("Delete a project secret").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((key,opts,command)=>unsetCommand("secret",key,opts,command))}__name(registerProjectSecretsCommands,"registerProjectSecretsCommands");function commandName(kind,verb){return`${kind==="secret"?"secrets":"vars"} ${verb}`}__name(commandName,"commandName");async function listCommand3(kind,opts,command){let{api,environment,projectId}=await resolveScope3(opts,command),rows=await api.listProjectSecretEntries(projectId,{kind,environment});if(rows.length===0){ui.info({command:commandName(kind,"list"),message:kind==="secret"?"No project secrets set.":"No project variables set."});return}ui.table({command:commandName(kind,"list"),columns:[{key:"key",label:"KEY"},{key:"value",label:kind==="secret"?"VALUE (masked)":"VALUE"}],rows:rows.map(row2=>({key:row2.key,value:row2.value??row2.maskedValue??""}))})}__name(listCommand3,"listCommand");async function writeCommand(kind,operation,key,valueArg,opts,command){let{api,environment,projectId}=await resolveScope3(opts,command),value=opts.stdin||valueArg===void 0?await readStdinValue3(kind):valueArg,input={projectId,key,kind,value,environment};operation==="add"?await api.createProjectSecretEntry(input):await api.updateProjectSecretEntry(input);let envLocal=kind==="variable"?await syncDefaultLocalVars(api,projectId,environment,opts):null,action=operation==="add"?"Added":"Updated";ui.ok({command:commandName(kind,operation),headline:`${action} project ${kind==="secret"?"secret":"variable"} ${key}`,details:{project_id:projectId,key,kind,environment,...envLocal&&{env_local:envLocal}}})}__name(writeCommand,"writeCommand");async function unsetCommand(kind,key,opts,command){let{api,environment,projectId}=await resolveScope3(opts,command);await api.deleteProjectSecretEntry(projectId,key,kind,environment);let envLocal=kind==="variable"?await syncDefaultLocalVars(api,projectId,environment,opts):null;ui.ok({command:commandName(kind,"unset"),headline:`Removed project ${kind==="secret"?"secret":"variable"} ${key}`,details:{project_id:projectId,key,kind,environment,...envLocal&&{env_local:envLocal}}})}__name(unsetCommand,"unsetCommand");async function pullVarsCommand(file,opts,command){let projectRoot=resolveProjectCwd(opts.cwd),{api,environment,projectId}=await resolveScope3(opts,command),result=await writePulledVars(api,projectRoot,projectId,environment,file??".env.local");ui.ok({command:"vars pull",headline:`Wrote ${result.written} variable${result.written===1?"":"s"} to ${result.path}`,details:{project_id:projectId,file:result.path,written:result.written}})}__name(pullVarsCommand,"pullVarsCommand");async function syncDefaultLocalVars(api,projectId,environment,opts){let projectRoot=resolveProjectCwd(opts.cwd);try{if(loadProjectSettings(projectRoot).projectId!==projectId)return null}catch{return null}return writePulledVars(api,projectRoot,projectId,environment,".env.local")}__name(syncDefaultLocalVars,"syncDefaultLocalVars");async function writePulledVars(api,projectRoot,projectId,environment,file){let rows=(await api.listProjectSecretEntries(projectId,{kind:"variable",environment})).filter(row2=>row2.exposure==="public"),target=path45.resolve(projectRoot,file),existing=fs44.existsSync(target)?fs44.readFileSync(target,"utf8"):"",body=mergeEnvFile(existing,rows);return fs44.writeFileSync(target,body),{path:target,written:rows.length}}__name(writePulledVars,"writePulledVars");function resolveProjectId5(opts){if(opts.project)return opts.project;let cwd=resolveProjectCwd(opts.cwd);return loadProjectSettings(cwd).projectId}__name(resolveProjectId5,"resolveProjectId");async function resolveScope3(opts,command){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId5(opts),branch=DEFAULT_ENV;try{branch=(await getProjectContext({cwd:opts.cwd,envOverride:envOverrideFromCommand(command)})).env}catch(error){if(!opts.project)throw error}let environment=await api.resolveProjectEnvironmentKey(projectId,branch);return{api,environment,projectId}}__name(resolveScope3,"resolveScope");async function readStdinValue3(kind){if(process.stdin.isTTY)throw new Error(`Pass a ${kind} value or pipe one with --stdin.`);let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/,"")}__name(readStdinValue3,"readStdinValue");var VARS_BLOCK={start:"# fimo:vars:start",end:"# fimo:vars:end",header:["# Generated by fimo vars pull. Do not put secrets in this block."]};function mergeEnvFile(existing,rows){let entries2=Object.fromEntries(rows.map(row2=>[row2.key,row2.value??""]));return mergeManagedEnvBlock(existing,entries2,VARS_BLOCK).content}__name(mergeEnvFile,"mergeEnvFile");init_dist5();init_dist();init_api();init_auth();init_config();init_auth_errors();init_interactive();init_project();import fs45 from"node:fs";function resolveCwd2(options){return resolveProjectCwd(options.cwd)}__name(resolveCwd2,"resolveCwd");function readLocalConfig(options){let cwd=resolveCwd2(options);try{return loadProjectSettings(cwd)}catch{return null}}__name(readLocalConfig,"readLocalConfig");function resolveProjectId6(argv,options,command){if(argv)return argv;let local=readLocalConfig(options);return local?local.projectId:(ui.error({command,code:"NOT_IN_PROJECT",message:"No project ID and no Fimo project link found in the current directory.",hint:"Pass a project ID explicitly, or cd into a linked project."}),null)}__name(resolveProjectId6,"resolveProjectId");async function projectsListCommand(options){let cfg=loadConfig(),api=new FimoApiClient(cfg),creds=requireCredentials(cfg),organizationId=options.org??creds?.activeOrganization?.id;if(!organizationId){ui.error({command:"projects list",code:"NO_ORGANIZATION_SPECIFIED",message:"No organization specified and no active organization set.",hint:"Run `fimo switch` or pass --org <id>."});return}let projects2=await api.listProjects(organizationId);if(projects2.length===0){ui.info({command:"projects list",message:"No projects in this organization yet."});return}ui.table({command:"projects list",columns:[{key:"published",label:"PUB"},{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"displayName",label:"DISPLAY NAME"}],rows:projects2.map(p2=>({published:p2.appUrl?"\u{1F7E2}":"\u26AA",id:p2.id,name:p2.name,displayName:p2.displayName??""}))})}__name(projectsListCommand,"projectsListCommand");async function projectsDeleteCommand(projectIdArg,options){let cfg=loadConfig(),api=new FimoApiClient(cfg),projectId=resolveProjectId6(projectIdArg,options,"projects delete");if(projectId){if(!options.yes){assertInteractive("Pass --yes to skip confirmation.","projects delete");let confirmed=await ot2({message:`Delete project ${projectId}? This cannot be undone.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"projects delete",message:"Cancelled."});return}}await api.deleteProject(projectId),ui.ok({command:"projects delete",headline:`Deleted project ${projectId}.`,details:{project_id:projectId}})}}__name(projectsDeleteCommand,"projectsDeleteCommand");async function projectsRenameCommand(nameArg,projectIdArg,options){let cwd=resolveCwd2(options),local=readLocalConfig(options);if(!local){ui.error({command:"projects rename",code:"NOT_IN_PROJECT",message:"No Fimo project link found in the current directory.",hint:"`fimo rename` only operates on a local project. cd into the project root."});return}if(projectIdArg&&projectIdArg!==local.projectId){ui.error({command:"projects rename",code:"PROJECT_ID_MISMATCH",message:`Project ID ${projectIdArg} does not match this directory's project (${local.projectId}).`,hint:"cd into the project you want to rename."});return}let name=nameArg.trim();if(!name){ui.error({command:"projects rename",code:"EMPTY_DISPLAY_NAME",message:"Display name cannot be empty."});return}let configPath=resolveProjectConfigPath(cwd),config={};if(fs45.existsSync(configPath))try{config=JSON.parse(fs45.readFileSync(configPath,"utf-8"))}catch(error){ui.error({command:"projects rename",code:"CONFIG_PARSE_FAILED",message:`Could not parse ${configPath}: ${error instanceof Error?error.message:String(error)}`});return}let seo=config.seo??{};config.seo={...seo,siteName:name},fs45.writeFileSync(configPath,JSON.stringify(config,null,2)+`
|
|
1383
|
-
`),ui.ok({command:"projects rename",headline:`Renamed to "${name}".`,details:{project_id:local.projectId,display_name:name},hint:"Commit and `fimo deploy` to sync."})}__name(projectsRenameCommand,"projectsRenameCommand");async function projectsPublishCommand(projectIdArg,options){let cfg=loadConfig(),api=new FimoApiClient(cfg),projectId=resolveProjectId6(projectIdArg,options,"projects publish");if(!projectId)return;let sp=spinner(`Publishing ${projectId}`);try{await api.publishProject(projectId),sp.succeed("Published")}catch(error){rethrowCliAuthError(error,()=>sp.fail("Authentication required")),sp.fail()
|
|
1383
|
+
`),ui.ok({command:"projects rename",headline:`Renamed to "${name}".`,details:{project_id:local.projectId,display_name:name},hint:"Commit and `fimo deploy` to sync."})}__name(projectsRenameCommand,"projectsRenameCommand");async function projectsPublishCommand(projectIdArg,options){let cfg=loadConfig(),api=new FimoApiClient(cfg),projectId=resolveProjectId6(projectIdArg,options,"projects publish");if(!projectId)return;let sp=spinner(`Publishing ${projectId}`),publicationId;try{publicationId=await api.publishProject(projectId),sp.succeed("Published")}catch(error){rethrowCliAuthError(error,()=>sp.fail("Authentication required")),sp.fail();let failedPublicationId=publicationIdFromError(error);ui.error({command:"projects publish",code:"PROJECT_PUBLISH_FAILED",message:`Publish failed: ${error instanceof Error?error.message:String(error)}`,...failedPublicationId?{details:{publication_id:failedPublicationId},hint:`Run \`fimo publish inspect ${failedPublicationId}\` for the recorded attempt.`}:{}});return}let appUrl=null;try{appUrl=(await api.getProject(projectId)).appUrl??null}catch{}ui.ok({command:"projects publish",headline:appUrl?`Live at ${appUrl}`:`Published ${projectId}.`,details:{project_id:projectId,app_url:appUrl,publication_id:publicationId}})}__name(projectsPublishCommand,"projectsPublishCommand");async function projectsUnpublishCommand(projectIdArg,options){let cfg=loadConfig(),api=new FimoApiClient(cfg),projectId=resolveProjectId6(projectIdArg,options,"projects unpublish");if(!projectId)return;let sp=spinner(`Unpublishing ${projectId}`);try{await api.unpublishProject(projectId),sp.succeed("Unpublished"),ui.ok({command:"projects unpublish",headline:`Unpublished ${projectId}.`,details:{project_id:projectId}})}catch(error){rethrowCliAuthError(error,()=>sp.fail("Authentication required")),sp.fail(),ui.error({command:"projects unpublish",code:"PROJECT_UNPUBLISH_FAILED",message:`Unpublish failed: ${error instanceof Error?error.message:String(error)}`})}}__name(projectsUnpublishCommand,"projectsUnpublishCommand");init_dist();init_api();init_config();init_auth_errors();init_project();var MAX_LIMIT2=100,MAX_LOG_LIMIT=1e3;async function publishListCommand(options){let projectId=resolveProjectId7(options,"publish list");if(!projectId)return;let limit;try{limit=parseLimit3(options.limit)}catch(error){ui.error({command:"publish list",code:"PUBLICATION_INVALID_LIMIT",message:errorMessage4(error)});return}let api=new FimoApiClient(loadConfig()),page;try{page=await api.listPublications(projectId,{limit,before:options.before})}catch(error){rethrowCliAuthError(error),ui.error({command:"publish list",code:"PUBLICATION_REQUEST_FAILED",message:`Could not read publication history: ${errorMessage4(error)}`});return}let hint=page.nextCursor?buildOlderHint2(page.nextCursor,options):void 0;ui.result({command:"publish list",data:{project_id:projectId,...page},render:__name(()=>renderPublicationList(page),"render"),...hint?{hint}:{}})}__name(publishListCommand,"publishListCommand");async function publishInspectCommand(publicationId,options){let projectId=resolveProjectId7(options,"publish inspect");if(!projectId)return;let api=new FimoApiClient(loadConfig()),publication;try{publication=await api.getPublication(projectId,publicationId)}catch(error){rethrowCliAuthError(error),ui.error({command:"publish inspect",code:"PUBLICATION_NOT_FOUND",message:`Could not read publication ${publicationId}: ${errorMessage4(error)}`,hint:"Run `fimo publish list` to see this project's publications."});return}ui.result({command:"publish inspect",data:{project_id:projectId,...publication},render:__name(()=>renderPublication(publication),"render")})}__name(publishInspectCommand,"publishInspectCommand");async function publishLogsCommand(publicationId,options){let projectId=resolveProjectId7(options,"publish logs");if(!projectId)return;await requireOperation("fimo.logs.read",{projectId});let limit;try{limit=parseLimit3(options.limit,MAX_LOG_LIMIT)}catch(error){ui.error({command:"publish logs",code:"PUBLICATION_INVALID_LIMIT",message:errorMessage4(error)});return}let api=new FimoApiClient(loadConfig()),result;try{result=await api.getPublicationLogs(projectId,publicationId,{limit})}catch(error){if(rethrowCliAuthError(error),error instanceof ApiRequestError&&error.status===404){ui.error({command:"publish logs",code:"PUBLICATION_NOT_FOUND",message:`Publication ${publicationId} does not exist in this project.`,hint:"Run `fimo publish list` to see this project's publications."});return}ui.error({command:"publish logs",code:"PUBLICATION_REQUEST_FAILED",message:`Could not read publication logs: ${errorMessage4(error)}`});return}let data2={project_id:projectId,...result};if(result.status==="unavailable"){let{message}=result;ui.result({command:"publish logs",data:data2,render:__name(()=>message,"render")});return}ui.result({command:"publish logs",data:data2,render:__name(()=>renderPublicationLogs(result),"render")})}__name(publishLogsCommand,"publishLogsCommand");function resolveProjectId7(options,command){try{return loadProjectSettings(resolveProjectCwd(options.cwd)).projectId}catch{return ui.error({command,code:"NOT_IN_PROJECT",message:"You are not in a Fimo project.",hint:"cd into a linked project first."}),null}}__name(resolveProjectId7,"resolveProjectId");function parseLimit3(value,max=MAX_LIMIT2){if(value===void 0)return;let limit=Number(value);if(!Number.isInteger(limit)||limit<1||limit>max)throw new Error(`--limit must be an integer between 1 and ${max}.`);return limit}__name(parseLimit3,"parseLimit");function renderPublicationList(page){if(page.items.length===0)return"No publications yet. Run `fimo deploy --publish` to publish this project.";let lines=page.items.map(item=>{let parts=[item.createdAt,item.status.padEnd(9),item.id];return item.failureCode?parts.push(item.failureCode):item.url&&parts.push(item.url),parts.join(" ")});return lines.push(""),lines.push("Publications are kept for the life of the project."),lines.join(`
|
|
1384
|
+
`)}__name(renderPublicationList,"renderPublicationList");function renderPublication(publication){let lines=[`Publication: ${publication.id}`,`Status: ${publication.status}`,`Source: ${publication.source.env} -> ${publication.source.targetEnv}`,`Started: ${publication.createdAt}`,`Finished: ${publication.finishedAt??"still running"}`];return(publication.source.framework||publication.source.configVersion)&&lines.push(`Project: ${publication.source.framework??"unknown framework"}, config v${publication.source.configVersion??"?"}`),publication.url&&lines.push(`URL: ${publication.url}`),publication.failureCode&&lines.push(`Failure: ${publication.failureCode}`),lines.join(`
|
|
1385
|
+
`)}__name(renderPublication,"renderPublication");function renderPublicationLogs(page){let count=page.events.length,lines=[`Publication ${page.publicationId}: ${count} ${count===1?"event":"events"}`];lines.push("");for(let event of page.events)lines.push(`${logMarker(event)}${event.message}`);return lines.join(`
|
|
1386
|
+
`)}__name(renderPublicationLogs,"renderPublicationLogs");function logMarker(event){switch(event.stream){case"command":return"$ ";case"stderr":case"error":return"! ";case"status":return"# ";default:return" "}}__name(logMarker,"logMarker");function buildOlderHint2(cursor,options){let args=["fimo","publish","list","--before",cursor];return options.limit&&args.push("--limit",options.limit),options.cwd&&args.push("--cwd",options.cwd),`Older: ${args.join(" ")}`}__name(buildOlderHint2,"buildOlderHint");function errorMessage4(error){return error instanceof Error?error.message:String(error)}__name(errorMessage4,"errorMessage");init_esm();init_dist();init_api();init_auth_errors();init_project_context();init_project();async function publishCommand(options,cmd){if(process.env.FIMO_MIGRATION_NO_DEPLOY==="1"){ui.error({command:"publish",code:"MIGRATION_DEPLOY_BLOCKED",message:"Publishing is disabled while a migration is running.",hint:"Finish local migration and QA first, then request deployment separately."});return}let program2=cmd?.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),cwd=resolveProjectCwd(options.cwd);if(ctx.env!==DEFAULT_ENV){ui.error({command:"publish",code:"PUBLISH_REQUIRES_DEFAULT_ENV",message:`Refusing to publish from env '${ctx.env}'. Publish only runs from '${DEFAULT_ENV}'.`,hint:"Switch to main first: `fimo checkout main`."});return}if(!options.skipValidate){let sp=spinner("Running lint + codegen + smoke checks"),report=await runValidate({cwd,envOverride:envOverride2});if(!report.ok){sp.fail("Validation failed"),ui.result({command:"publish",data:{stage:"validate",report},render:__name(()=>formatReportHuman(report),"render")}),process.exitCode=report.exitCode;return}sp.succeed("Validation passed")}if(!options.version){ui.error({command:"publish",code:"PUBLISH_VERSION_REQUIRED",message:"--version is required (e.g. --version 1.4.2)."});return}let api=new FimoApiClient().withEnv(ctx.env),body={version:options.version,notes:options.notes},tagSp=spinner(`Tagging release/${options.version} and triggering prod swap`),result;try{result=await api.publishRelease(ctx.projectId,body)}catch(err){rethrowCliAuthError(err,()=>tagSp.fail("Authentication required")),tagSp.fail(),ui.error({command:"publish",code:"PUBLISH_FAILED",message:`Publish failed: ${err.message}`});return}tagSp.succeed(`Released ${result.releaseTag} @ ${result.sha.slice(0,8)}`),ui.ok({command:"publish",headline:"Release published \u2014 prod-swap detector will pick it up shortly.",details:{release_tag:result.releaseTag,sha:result.sha,version:options.version}})}__name(publishCommand,"publishCommand");init_dist();init_api();init_auth();init_config();async function referralLinkCommand(){let currentUser=await resolveCurrentCliUser("referral link");if(!currentUser)return;let cfg=loadConfig(),referralLink=new URL(`/invite/${encodeURIComponent(currentUser.id)}`,cfg.webUrl).toString();ui.raw({command:"referral link",value:referralLink,field:"url"})}__name(referralLinkCommand,"referralLinkCommand");async function referralStatsCommand(){let currentUser=await resolveCurrentCliUser("referral stats");if(!currentUser)return;let cfg=loadConfig(),summary2=await new FimoApiClient(cfg).getReferralSummary(currentUser.id),totalReferrals=summary2.counts.signed_up+summary2.counts.activated;ui.kv({command:"referral stats",headline:`Referral stats for ${currentUser.name||currentUser.email}`,fields:{total_referrals:totalReferrals,signed_up:summary2.counts.signed_up,activated:summary2.counts.activated,ai_credits_earned:summary2.credits.total}})}__name(referralStatsCommand,"referralStatsCommand");async function resolveCurrentCliUser(command){let cfg=loadConfig(),creds=requireCredentials(cfg);if(creds.user?.id)return creds.user;let session=await new FimoApiClient(cfg).getCurrentSession();return session?.user?.id?(writeCredentials({...creds,user:{id:session.user.id,email:session.user.email,name:session.user.name??""}},cfg),{id:session.user.id,email:session.user.email,name:session.user.name??""}):(ui.error({command,code:"SESSION_USER_MISSING",message:"Could not resolve the current user.",hint:"Run `fimo login` again."}),null)}__name(resolveCurrentCliUser,"resolveCurrentCliUser");init_dist();init_agents();init_scaffold();import fs46 from"node:fs";import path46 from"node:path";async function rulesSyncCommand(options={}){let cwd=path46.resolve(options.cwd??process.cwd()),agentsMdPath=path46.join(cwd,"AGENTS.md");if(!fs46.existsSync(agentsMdPath)){ui.error({command:"rules sync",code:"NO_AGENTS_MD",message:`No AGENTS.md found in ${cwd}.`,hint:"Run `fimo create` to scaffold a project, or create AGENTS.md manually before running `fimo rules sync`."});return}let selectedAgents;try{selectedAgents=await selectAgents(options,{promptMessage:"Which agents do you want to sync rules for?",detectFn:__name(()=>Promise.resolve(detectAgentsInProject(cwd)),"detectFn")})}catch(err){ui.error({command:"rules sync",code:"AGENT_SELECTION_FAILED",message:err instanceof Error?err.message:String(err)});return}if(selectedAgents.length===0){ui.result({command:"rules sync",data:{synced:[]},render:__name(()=>"Nothing to sync.","render")});return}let result=syncPerAgentVariants(cwd,selectedAgents),agentsWithVariants=new Set(["claude-code","cursor","windsurf","gemini-cli"]),noVariantAgents=selectedAgents.filter(a=>!agentsWithVariants.has(a)),data2={synced:result.perAgentVariants,skipped:result.perAgentVariantsSkipped,nativeAgentsMd:noVariantAgents};ui.result({command:"rules sync",data:data2,render:__name(()=>{let lines=[];return result.perAgentVariants.length>0&&lines.push(`Wrote: ${result.perAgentVariants.join(", ")}`),result.perAgentVariantsSkipped.length>0&&lines.push(`Skipped (already exist, preserved): ${result.perAgentVariantsSkipped.join(", ")}`),noVariantAgents.length>0&&lines.push(`${noVariantAgents.join(", ")}: read AGENTS.md natively \u2014 no extra file needed.`),lines.length===0?"Nothing to do.":(result.perAgentVariantsSkipped.length>0&&(lines.push(""),lines.push("Note: existing files are preserved. To regenerate a stale variant, delete it first then re-run `fimo rules sync`.")),lines.join(`
|
|
1384
1387
|
`))},"render")})}__name(rulesSyncCommand,"rulesSyncCommand");init_esm();init_dist();init_api();init_config();init_project_context();init_project();var UUID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,RUN_POLL_INTERVAL_MS=2e3,RUN_POLL_TIMEOUT_MS=1800*1e3,TERMINAL_RUN_STATUSES=["succeeded","failed","skipped"],ScheduleCommandError=class extends Error{static{__name(this,"ScheduleCommandError")}code;constructor(code2,message){super(message),this.name="ScheduleCommandError",this.code=code2}};function collect2(value,previous){return[...previous??[],value]}__name(collect2,"collect");function addScopeOptions3(command){return command.option("--branch <branch>","Target a specific Fimo Branch (defaults to the current git branch)").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions3,"addScopeOptions");function registerSchedulesCommands(program2){let schedules=program2.command("schedules").description("Manage recurring project commands").addHelpText("after",`
|
|
1385
1388
|
Examples:
|
|
1386
1389
|
fimo schedules create nightly --cron "0 2 * * *" --do "fimo validate" --secret CMS_TOKEN
|
|
@@ -1434,13 +1437,13 @@ Examples:
|
|
|
1434
1437
|
fimo webhooks deliveries <webhook-id>
|
|
1435
1438
|
|
|
1436
1439
|
Header values use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value. There are no CLI presets: pass the provider request explicitly.
|
|
1437
|
-
`);addScopeOptions4(webhooks.command("events [eventType]").description("List events or describe one event and its example payload")).action((eventType,opts,command)=>eventsCommand(eventType,opts,command)),addScopeOptions4(webhooks.command("list").description("List project webhooks")).action((opts,command)=>listCommand5(opts,command)),addScopeOptions4(webhooks.command("get <webhookId>").description("Show a webhook configuration")).action((webhookId,opts,command)=>getCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("create <name>").description("Create an outbound webhook").requiredOption("--event <event>","Event type, for example form.submitted").requiredOption("--url <url>","HTTPS destination URL").option("--header <name=source:value>","Add a literal or secret-backed header; repeat for multiple headers",collect3).option("--body <json|@file|->","Custom JSON payload inline, from @file, or stdin with -").option("--form <id>","Only form.submitted events for this form id").option("--agent <name>","Only agent events for this agent name").option("--media-type <type>","Only media events for image, video, audio, document, or other").option("--action <action>","Only entry.changed events with created, updated, or deleted entries").option("--content-type <name>","Only entry.changed events for this content type").option("--locale <locale>","Only entry.changed events for this locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id","main").option("--debounce-changes <immediate|5s|30s|1m>","Combine rapid entry.changed events into one delivery").option("--disabled","Create the webhook disabled").option("--no-signing","Do not add X-Fimo-Signature headers")).action((name,opts,command)=>createCommand4(name,opts,command)),addScopeOptions4(webhooks.command("update <webhookId>").description("Update an outbound webhook").option("--name <name>","Change the webhook name").option("--event <event>","Change the event type").option("--url <url>","Change the HTTPS destination URL").option("--header <name=source:value>","Replace headers; repeat for multiple headers",collect3).option("--clear-headers","Remove all configured destination headers").option("--body <json|@file|->","Replace the custom payload inline, from @file, or stdin with -").option("--default-body","Send the full event envelope instead of a custom template").option("--form <id>","Filter form.submitted by form id").option("--agent <name>","Filter agent events by agent name").option("--media-type <type>","Filter media events by media type").option("--action <action>","Filter entry.changed by created, updated, or deleted").option("--content-type <name>","Filter entry.changed by content type").option("--locale <locale>","Filter entry.changed by locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id").option("--debounce-changes <immediate|5s|30s|1m>","Change the entry.changed debounce window").option("--clear-filter","Remove all event filters").option("--enabled <on|off>","Enable or disable delivery").option("--signing <on|off>","Enable or disable X-Fimo-Signature headers")).action((webhookId,opts,command)=>updateCommand3(webhookId,opts,command)),addScopeOptions4(webhooks.command("delete <webhookId>").description("Delete an outbound webhook")).action((webhookId,opts,command)=>deleteCommand3(webhookId,opts,command)),addScopeOptions4(webhooks.command("test <webhookId>").description("Queue a test delivery using example event data").option("--data <json>","Override the event data with a JSON object").option("--wait","Wait up to 60 seconds for the delivery to succeed or fail")).action((webhookId,opts,command)=>testCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("deliveries <webhookId>").description("List recent webhook deliveries").option("--limit <count>","Maximum deliveries to return (1-100)")).action((webhookId,opts,command)=>deliveriesCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("delivery <webhookId> <deliveryId>").description("Show a delivery and all attempts")).action((webhookId,deliveryId,opts,command)=>deliveryCommand(webhookId,deliveryId,opts,command)),addScopeOptions4(webhooks.command("retry <webhookId> <deliveryId>").description("Retry an exhausted failed delivery now")).action((webhookId,deliveryId,opts,command)=>retryCommand2(webhookId,deliveryId,opts,command)),addScopeOptions4(webhooks.command("rotate-secret <webhookId>").description("Rotate and reveal a new signing secret once")).action((webhookId,opts,command)=>rotateSecretCommand(webhookId,opts,command))}__name(registerWebhooksCommands,"registerWebhooksCommands");async function resolveScope5(op,opts,_command){let scope;if(opts.project)scope={projectId:opts.project};else{let ctx=await getProjectContext({cwd:opts.cwd});scope={projectId:ctx.projectId,env:ctx.env}}return await requireOperation(op,scope),{...scope,api:new FimoApiClient(loadConfig())}}__name(resolveScope5,"resolveScope");async function eventsCommand(eventType,opts,command){let{api,projectId}=await resolveScope5("webhooks.events",opts,command),events=await api.listWebhookEvents(projectId);if(eventType){let event=events.find(candidate=>candidate.type===eventType);if(!event)throw new WebhookCommandError("WEBHOOK_EVENT_NOT_FOUND",`Unknown webhook event '${eventType}'.`);renderJson("webhooks events",event);return}ui.table({command:"webhooks events",columns:[{key:"event",label:"EVENT"},{key:"family",label:"FAMILY"},{key:"description",label:"DESCRIPTION"},{key:"variables",label:"VARIABLES"}],rows:events.map(event=>({event:event.type,family:event.family,description:event.description,variables:event.variables.join(", ")}))})}__name(eventsCommand,"eventsCommand");async function listCommand5(opts,command){let{api,projectId}=await resolveScope5("webhooks.list",opts,command),webhooks=await api.listProjectWebhooks(projectId);ui.table({command:"webhooks list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"event",label:"EVENT"},{key:"destination",label:"DESTINATION"},{key:"enabled",label:"ENABLED"},{key:"last",label:"LAST DELIVERY"}],rows:webhooks.map(webhook=>({id:webhook.id,name:webhook.name,event:webhook.eventType,destination:webhook.destination.maskedUrl,enabled:webhook.enabled?"yes":"no",last:webhook.lastDeliveryStatus??""}))})}__name(listCommand5,"listCommand");async function getCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.get",opts,command);renderJson("webhooks get",await api.getProjectWebhook(projectId,webhookId))}__name(getCommand,"getCommand");async function createCommand4(name,opts,command){let{api,projectId}=await resolveScope5("webhooks.create",opts,command),parsed=CreateProjectWebhookRequestSchema.safeParse({name,eventType:opts.event,url:opts.url,enabled:!opts.disabled,filter:createFilter(opts),headers:parseHeaders(opts.header),bodyTemplate:opts.body===void 0?null:await parseJsonInput(opts.body,"--body",opts.cwd),signingEnabled:opts.signing!==!1,entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges??(opts.event==="entry.changed"?"5s":"immediate"))});if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");let result=await api.createProjectWebhook(projectId,parsed.data);renderJson("webhooks create",{webhook:result.webhook,signingSecret:result.signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(createCommand4,"createCommand");async function updateCommand3(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.update",opts,command);if(opts.header&&opts.clearHeaders)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --header or --clear-headers, not both.");if(opts.body!==void 0&&opts.defaultBody)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --body or --default-body, not both.");let current=await api.getProjectWebhook(projectId,webhookId),filter4=createUpdateFilter(current,opts),request={...opts.name!==void 0?{name:opts.name}:{},...opts.event!==void 0?{eventType:opts.event}:{},...opts.url!==void 0?{url:opts.url}:{},...opts.header!==void 0||opts.clearHeaders?{headers:parseHeaders(opts.header)}:{},...opts.body!==void 0?{bodyTemplate:await parseJsonInput(opts.body,"--body",opts.cwd)}:{},...opts.defaultBody?{bodyTemplate:null}:{},...filter4?{filter:filter4}:{},...opts.enabled!==void 0?{enabled:parseOnOff(opts.enabled,"--enabled")}:{},...opts.signing!==void 0?{signingEnabled:parseOnOff(opts.signing,"--signing")}:{},...opts.debounceChanges!==void 0?{entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges)}:opts.event==="entry.changed"&¤t.eventType!=="entry.changed"?{entryBatchWindowSeconds:5}:{}},parsed=UpdateProjectWebhookRequestSchema.safeParse(request);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");if(Object.keys(parsed.data).length===0)throw new WebhookCommandError("WEBHOOK_UPDATE_EMPTY","Pass at least one field to update.");renderJson("webhooks update",await api.updateProjectWebhook(projectId,webhookId,parsed.data))}__name(updateCommand3,"updateCommand");async function deleteCommand3(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.delete",opts,command);await api.deleteProjectWebhook(projectId,webhookId),ui.ok({command:"webhooks delete",headline:`Deleted webhook ${webhookId}`,details:{project_id:projectId,webhook_id:webhookId}})}__name(deleteCommand3,"deleteCommand");async function testCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.test",opts,command),data2=opts.data===void 0?void 0:parseJsonObject3(opts.data,"--data"),delivery=await api.testProjectWebhook(projectId,webhookId,{data:data2});if(opts.wait){let deadline=Date.now()+6e4;for(;!["succeeded","failed"].includes(delivery.status)&&Date.now()<deadline;)await new Promise(resolveWait=>setTimeout(resolveWait,500)),delivery=(await api.getProjectWebhookDelivery(projectId,webhookId,delivery.id)).delivery;if(!["succeeded","failed"].includes(delivery.status))throw new WebhookCommandError("WEBHOOK_DELIVERY_TIMEOUT",`Delivery ${delivery.id} did not finish within 60 seconds.`)}renderJson("webhooks test",delivery)}__name(testCommand,"testCommand");async function deliveriesCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.list",opts,command),limit=opts.limit===void 0?void 0:parseLimit3(opts.limit),deliveries=await api.listProjectWebhookDeliveries(projectId,webhookId,limit);ui.table({command:"webhooks deliveries",columns:[{key:"id",label:"DELIVERY"},{key:"event",label:"EVENT"},{key:"status",label:"STATUS"},{key:"attempts",label:"ATTEMPTS"},{key:"response",label:"RESPONSE"},{key:"created",label:"CREATED"}],rows:deliveries.map(delivery=>({id:delivery.id,event:delivery.eventType,status:delivery.status,attempts:delivery.attemptCount,response:delivery.responseStatus??"",created:String(delivery.createdAt)}))})}__name(deliveriesCommand,"deliveriesCommand");async function deliveryCommand(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.get",opts,command);renderJson("webhooks delivery",await api.getProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(deliveryCommand,"deliveryCommand");async function retryCommand2(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.retry",opts,command);renderJson("webhooks retry",await api.retryProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(retryCommand2,"retryCommand");async function rotateSecretCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.rotate_secret",opts,command),signingSecret=await api.rotateProjectWebhookSecret(projectId,webhookId);renderJson("webhooks rotate-secret",{webhookId,signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(rotateSecretCommand,"rotateSecretCommand");function createFilter(opts){return parseFilter({...opts.environments?{environment:opts.environments}:{},...opts.form?{formId:opts.form}:{},...opts.agent?{agentName:opts.agent}:{},...opts.mediaType?{mediaType:opts.mediaType}:{},...opts.action?{action:opts.action}:{},...opts.contentType?{contentType:opts.contentType}:{},...opts.locale?{locale:opts.locale}:{}})}__name(createFilter,"createFilter");function parseFilter(value){let parsed=WebhookFilterSchema.safeParse(value);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook filter.");return parsed.data}__name(parseFilter,"parseFilter");function parseEntryBatchWindow(value){let parsed={immediate:0,"5s":5,"30s":30,"1m":60}[value.toLowerCase()];if(parsed===void 0)throw new WebhookCommandError("WEBHOOK_GROUPING_INVALID",`Invalid grouping window '${value}'. Use immediate, 5s, 30s, or 1m.`);return parsed}__name(parseEntryBatchWindow,"parseEntryBatchWindow");function hasFilterOptions(opts){return!!(opts.clearFilter||opts.environments||opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)}__name(hasFilterOptions,"hasFilterOptions");function createUpdateFilter(current,opts){if(!hasFilterOptions(opts))return;if(opts.clearFilter)return createFilter({environments:opts.environments??"main"});let environment=opts.environments??current.filter.environment??"main";return!(opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)?parseFilter({...current.filter,environment}):createFilter({...opts,environments:environment})}__name(createUpdateFilter,"createUpdateFilter");function parseHeaders(values){return(values??[]).map(entry=>{let separator=entry.indexOf("=");if(separator<=0)throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`);let name=entry.slice(0,separator).trim(),encoded=entry.slice(separator+1);if(encoded.startsWith("secret:"))return{name,value:{source:"secret",key:encoded.slice(7)}};if(encoded.startsWith("bearer:"))return{name,value:{source:"secret",key:encoded.slice(7),prefix:"Bearer "}};if(encoded.startsWith("token:"))return{name,value:{source:"secret",key:encoded.slice(6),prefix:"token "}};if(encoded.startsWith("literal:"))return{name,value:{source:"literal",value:encoded.slice(8)}};throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`)})}__name(parseHeaders,"parseHeaders");function parseJson(value,flag2){try{return JSON.parse(value)}catch{throw new WebhookCommandError("WEBHOOK_JSON_INVALID",`${flag2} must be valid JSON. Quote the value so your shell passes it as one argument.`)}}__name(parseJson,"parseJson");async function parseJsonInput(value,flag2,cwd){let input=value;if(value==="-")input=await readStdin2();else if(value.startsWith("@")){let path50=resolve9(resolveProjectCwd(cwd),value.slice(1));try{input=await readFile5(path50,"utf8")}catch{throw new WebhookCommandError("WEBHOOK_INPUT_READ_FAILED",`Could not read ${flag2} input from '${path50}'.`)}}return parseJson(input,flag2)}__name(parseJsonInput,"parseJsonInput");async function readStdin2(){let input="";process.stdin.setEncoding("utf8");for await(let chunk of process.stdin)input+=chunk;return input}__name(readStdin2,"readStdin");function parseJsonObject3(value,flag2){let parsed=parseJson(value,flag2);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new WebhookCommandError("WEBHOOK_DATA_INVALID",`${flag2} must be a JSON object.`);return parsed}__name(parseJsonObject3,"parseJsonObject");function parseOnOff(value,flag2){if(value==="on")return!0;if(value==="off")return!1;throw new WebhookCommandError("WEBHOOK_TOGGLE_INVALID",`${flag2} must be 'on' or 'off'.`)}__name(parseOnOff,"parseOnOff");function parseLimit3(value){let limit=Number(value);if(!Number.isInteger(limit)||limit<1||limit>100)throw new WebhookCommandError("WEBHOOK_LIMIT_INVALID","--limit must be an integer from 1 to 100.");return limit}__name(parseLimit3,"parseLimit");function renderJson(command,data2){ui.result({command,data:data2,render:__name(()=>JSON.stringify(data2,null,2),"render")})}__name(renderJson,"renderJson");init_dist();init_auth();async function whoamiCommand(){let creds=requireCredentials();if(!creds.user){ui.error({command:"whoami",code:"NOT_AUTHENTICATED",message:"Could not resolve the current user from local credentials.",hint:"Run `fimo login` again."});return}let displayName=creds.user.name||creds.user.email,activeOrganization=creds.activeOrganization?.name??null;ui.kv({command:"whoami",headline:`Signed in as ${displayName} (${creds.user.email})`,fields:{user:displayName,email:creds.user.email,active_organization:activeOrganization},hint:activeOrganization===null?"Run `fimo orgs switch` to pick an active organization.":void 0})}__name(whoamiCommand,"whoamiCommand");init_config();var TOP_LEVEL_HELP_GROUPS=[{title:"Account",commands:["login","logout","whoami"]},{title:"Project lifecycle",commands:["create","migrate","deploy","logs","validate","describe"]},{title:"Projects & teams",commands:["projects","orgs","invite","credits","referral","rename","delete","unpublish"]},{title:"Environments & releases",commands:["environments","status","branch","checkout","switch","pull","diff","merge","publish","preview"]},{title:"Content & media",commands:["schemas","entries","forms","translations","assets","generate","models"]},{title:"Domains & analytics",commands:["domains","analytics"]},{title:"Agents & integrations",commands:["agents","skills","rules","integrations","channels","mcp"]},{title:"Configuration",commands:["vars","secrets"]},{title:"Help",commands:["support","help"]}];function configureGroupedHelp(program2){program2.configureHelp({...program2.configureHelp(),formatHelp:__name((cmd,helper)=>formatHelpWithGroupedCommands(cmd,helper,TOP_LEVEL_HELP_GROUPS),"formatHelp")})}__name(configureGroupedHelp,"configureGroupedHelp");function formatHelpWithGroupedCommands(cmd,helper,groups){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80,formatItem=__name((term,description)=>helper.formatItem(term,termWidth,description,helper),"formatItem"),output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>formatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));argumentList.length>0&&(output=output.concat([helper.styleTitle("Arguments:"),...argumentList,""]));let optionList=helper.visibleOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));if(optionList.length>0&&(output=output.concat([helper.styleTitle("Options:"),...optionList,""])),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));globalOptionList.length>0&&(output=output.concat([helper.styleTitle("Global Options:"),...globalOptionList,""]))}let commandSections=formatGroupedCommandSections(cmd,helper,groups,termWidth);return commandSections.length>0&&(output=output.concat([helper.styleTitle("Commands:"),...commandSections,""])),output.join(`
|
|
1440
|
+
`);addScopeOptions4(webhooks.command("events [eventType]").description("List events or describe one event and its example payload")).action((eventType,opts,command)=>eventsCommand(eventType,opts,command)),addScopeOptions4(webhooks.command("list").description("List project webhooks")).action((opts,command)=>listCommand5(opts,command)),addScopeOptions4(webhooks.command("get <webhookId>").description("Show a webhook configuration")).action((webhookId,opts,command)=>getCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("create <name>").description("Create an outbound webhook").requiredOption("--event <event>","Event type, for example form.submitted").requiredOption("--url <url>","HTTPS destination URL").option("--header <name=source:value>","Add a literal or secret-backed header; repeat for multiple headers",collect3).option("--body <json|@file|->","Custom JSON payload inline, from @file, or stdin with -").option("--form <id>","Only form.submitted events for this form id").option("--agent <name>","Only agent events for this agent name").option("--media-type <type>","Only media events for image, video, audio, document, or other").option("--action <action>","Only entry.changed events with created, updated, or deleted entries").option("--content-type <name>","Only entry.changed events for this content type").option("--locale <locale>","Only entry.changed events for this locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id","main").option("--debounce-changes <immediate|5s|30s|1m>","Combine rapid entry.changed events into one delivery").option("--disabled","Create the webhook disabled").option("--no-signing","Do not add X-Fimo-Signature headers")).action((name,opts,command)=>createCommand4(name,opts,command)),addScopeOptions4(webhooks.command("update <webhookId>").description("Update an outbound webhook").option("--name <name>","Change the webhook name").option("--event <event>","Change the event type").option("--url <url>","Change the HTTPS destination URL").option("--header <name=source:value>","Replace headers; repeat for multiple headers",collect3).option("--clear-headers","Remove all configured destination headers").option("--body <json|@file|->","Replace the custom payload inline, from @file, or stdin with -").option("--default-body","Send the full event envelope instead of a custom template").option("--form <id>","Filter form.submitted by form id").option("--agent <name>","Filter agent events by agent name").option("--media-type <type>","Filter media events by media type").option("--action <action>","Filter entry.changed by created, updated, or deleted").option("--content-type <name>","Filter entry.changed by content type").option("--locale <locale>","Filter entry.changed by locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id").option("--debounce-changes <immediate|5s|30s|1m>","Change the entry.changed debounce window").option("--clear-filter","Remove all event filters").option("--enabled <on|off>","Enable or disable delivery").option("--signing <on|off>","Enable or disable X-Fimo-Signature headers")).action((webhookId,opts,command)=>updateCommand3(webhookId,opts,command)),addScopeOptions4(webhooks.command("delete <webhookId>").description("Delete an outbound webhook")).action((webhookId,opts,command)=>deleteCommand3(webhookId,opts,command)),addScopeOptions4(webhooks.command("test <webhookId>").description("Queue a test delivery using example event data").option("--data <json>","Override the event data with a JSON object").option("--wait","Wait up to 60 seconds for the delivery to succeed or fail")).action((webhookId,opts,command)=>testCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("deliveries <webhookId>").description("List recent webhook deliveries").option("--limit <count>","Maximum deliveries to return (1-100)")).action((webhookId,opts,command)=>deliveriesCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("delivery <webhookId> <deliveryId>").description("Show a delivery and all attempts")).action((webhookId,deliveryId,opts,command)=>deliveryCommand(webhookId,deliveryId,opts,command)),addScopeOptions4(webhooks.command("retry <webhookId> <deliveryId>").description("Retry an exhausted failed delivery now")).action((webhookId,deliveryId,opts,command)=>retryCommand2(webhookId,deliveryId,opts,command)),addScopeOptions4(webhooks.command("rotate-secret <webhookId>").description("Rotate and reveal a new signing secret once")).action((webhookId,opts,command)=>rotateSecretCommand(webhookId,opts,command))}__name(registerWebhooksCommands,"registerWebhooksCommands");async function resolveScope5(op,opts,_command){let scope;if(opts.project)scope={projectId:opts.project};else{let ctx=await getProjectContext({cwd:opts.cwd});scope={projectId:ctx.projectId,env:ctx.env}}return await requireOperation(op,scope),{...scope,api:new FimoApiClient(loadConfig())}}__name(resolveScope5,"resolveScope");async function eventsCommand(eventType,opts,command){let{api,projectId}=await resolveScope5("webhooks.events",opts,command),events=await api.listWebhookEvents(projectId);if(eventType){let event=events.find(candidate=>candidate.type===eventType);if(!event)throw new WebhookCommandError("WEBHOOK_EVENT_NOT_FOUND",`Unknown webhook event '${eventType}'.`);renderJson("webhooks events",event);return}ui.table({command:"webhooks events",columns:[{key:"event",label:"EVENT"},{key:"family",label:"FAMILY"},{key:"description",label:"DESCRIPTION"},{key:"variables",label:"VARIABLES"}],rows:events.map(event=>({event:event.type,family:event.family,description:event.description,variables:event.variables.join(", ")}))})}__name(eventsCommand,"eventsCommand");async function listCommand5(opts,command){let{api,projectId}=await resolveScope5("webhooks.list",opts,command),webhooks=await api.listProjectWebhooks(projectId);ui.table({command:"webhooks list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"event",label:"EVENT"},{key:"destination",label:"DESTINATION"},{key:"enabled",label:"ENABLED"},{key:"last",label:"LAST DELIVERY"}],rows:webhooks.map(webhook=>({id:webhook.id,name:webhook.name,event:webhook.eventType,destination:webhook.destination.maskedUrl,enabled:webhook.enabled?"yes":"no",last:webhook.lastDeliveryStatus??""}))})}__name(listCommand5,"listCommand");async function getCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.get",opts,command);renderJson("webhooks get",await api.getProjectWebhook(projectId,webhookId))}__name(getCommand,"getCommand");async function createCommand4(name,opts,command){let{api,projectId}=await resolveScope5("webhooks.create",opts,command),parsed=CreateProjectWebhookRequestSchema.safeParse({name,eventType:opts.event,url:opts.url,enabled:!opts.disabled,filter:createFilter(opts),headers:parseHeaders(opts.header),bodyTemplate:opts.body===void 0?null:await parseJsonInput(opts.body,"--body",opts.cwd),signingEnabled:opts.signing!==!1,entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges??(opts.event==="entry.changed"?"5s":"immediate"))});if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");let result=await api.createProjectWebhook(projectId,parsed.data);renderJson("webhooks create",{webhook:result.webhook,signingSecret:result.signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(createCommand4,"createCommand");async function updateCommand3(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.update",opts,command);if(opts.header&&opts.clearHeaders)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --header or --clear-headers, not both.");if(opts.body!==void 0&&opts.defaultBody)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --body or --default-body, not both.");let current=await api.getProjectWebhook(projectId,webhookId),filter4=createUpdateFilter(current,opts),request={...opts.name!==void 0?{name:opts.name}:{},...opts.event!==void 0?{eventType:opts.event}:{},...opts.url!==void 0?{url:opts.url}:{},...opts.header!==void 0||opts.clearHeaders?{headers:parseHeaders(opts.header)}:{},...opts.body!==void 0?{bodyTemplate:await parseJsonInput(opts.body,"--body",opts.cwd)}:{},...opts.defaultBody?{bodyTemplate:null}:{},...filter4?{filter:filter4}:{},...opts.enabled!==void 0?{enabled:parseOnOff(opts.enabled,"--enabled")}:{},...opts.signing!==void 0?{signingEnabled:parseOnOff(opts.signing,"--signing")}:{},...opts.debounceChanges!==void 0?{entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges)}:opts.event==="entry.changed"&¤t.eventType!=="entry.changed"?{entryBatchWindowSeconds:5}:{}},parsed=UpdateProjectWebhookRequestSchema.safeParse(request);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");if(Object.keys(parsed.data).length===0)throw new WebhookCommandError("WEBHOOK_UPDATE_EMPTY","Pass at least one field to update.");renderJson("webhooks update",await api.updateProjectWebhook(projectId,webhookId,parsed.data))}__name(updateCommand3,"updateCommand");async function deleteCommand3(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.delete",opts,command);await api.deleteProjectWebhook(projectId,webhookId),ui.ok({command:"webhooks delete",headline:`Deleted webhook ${webhookId}`,details:{project_id:projectId,webhook_id:webhookId}})}__name(deleteCommand3,"deleteCommand");async function testCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.test",opts,command),data2=opts.data===void 0?void 0:parseJsonObject3(opts.data,"--data"),delivery=await api.testProjectWebhook(projectId,webhookId,{data:data2});if(opts.wait){let deadline=Date.now()+6e4;for(;!["succeeded","failed"].includes(delivery.status)&&Date.now()<deadline;)await new Promise(resolveWait=>setTimeout(resolveWait,500)),delivery=(await api.getProjectWebhookDelivery(projectId,webhookId,delivery.id)).delivery;if(!["succeeded","failed"].includes(delivery.status))throw new WebhookCommandError("WEBHOOK_DELIVERY_TIMEOUT",`Delivery ${delivery.id} did not finish within 60 seconds.`)}renderJson("webhooks test",delivery)}__name(testCommand,"testCommand");async function deliveriesCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.list",opts,command),limit=opts.limit===void 0?void 0:parseLimit4(opts.limit),deliveries=await api.listProjectWebhookDeliveries(projectId,webhookId,limit);ui.table({command:"webhooks deliveries",columns:[{key:"id",label:"DELIVERY"},{key:"event",label:"EVENT"},{key:"status",label:"STATUS"},{key:"attempts",label:"ATTEMPTS"},{key:"response",label:"RESPONSE"},{key:"created",label:"CREATED"}],rows:deliveries.map(delivery=>({id:delivery.id,event:delivery.eventType,status:delivery.status,attempts:delivery.attemptCount,response:delivery.responseStatus??"",created:String(delivery.createdAt)}))})}__name(deliveriesCommand,"deliveriesCommand");async function deliveryCommand(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.get",opts,command);renderJson("webhooks delivery",await api.getProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(deliveryCommand,"deliveryCommand");async function retryCommand2(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.retry",opts,command);renderJson("webhooks retry",await api.retryProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(retryCommand2,"retryCommand");async function rotateSecretCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.rotate_secret",opts,command),signingSecret=await api.rotateProjectWebhookSecret(projectId,webhookId);renderJson("webhooks rotate-secret",{webhookId,signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(rotateSecretCommand,"rotateSecretCommand");function createFilter(opts){return parseFilter({...opts.environments?{environment:opts.environments}:{},...opts.form?{formId:opts.form}:{},...opts.agent?{agentName:opts.agent}:{},...opts.mediaType?{mediaType:opts.mediaType}:{},...opts.action?{action:opts.action}:{},...opts.contentType?{contentType:opts.contentType}:{},...opts.locale?{locale:opts.locale}:{}})}__name(createFilter,"createFilter");function parseFilter(value){let parsed=WebhookFilterSchema.safeParse(value);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook filter.");return parsed.data}__name(parseFilter,"parseFilter");function parseEntryBatchWindow(value){let parsed={immediate:0,"5s":5,"30s":30,"1m":60}[value.toLowerCase()];if(parsed===void 0)throw new WebhookCommandError("WEBHOOK_GROUPING_INVALID",`Invalid grouping window '${value}'. Use immediate, 5s, 30s, or 1m.`);return parsed}__name(parseEntryBatchWindow,"parseEntryBatchWindow");function hasFilterOptions(opts){return!!(opts.clearFilter||opts.environments||opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)}__name(hasFilterOptions,"hasFilterOptions");function createUpdateFilter(current,opts){if(!hasFilterOptions(opts))return;if(opts.clearFilter)return createFilter({environments:opts.environments??"main"});let environment=opts.environments??current.filter.environment??"main";return!(opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)?parseFilter({...current.filter,environment}):createFilter({...opts,environments:environment})}__name(createUpdateFilter,"createUpdateFilter");function parseHeaders(values){return(values??[]).map(entry=>{let separator=entry.indexOf("=");if(separator<=0)throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`);let name=entry.slice(0,separator).trim(),encoded=entry.slice(separator+1);if(encoded.startsWith("secret:"))return{name,value:{source:"secret",key:encoded.slice(7)}};if(encoded.startsWith("bearer:"))return{name,value:{source:"secret",key:encoded.slice(7),prefix:"Bearer "}};if(encoded.startsWith("token:"))return{name,value:{source:"secret",key:encoded.slice(6),prefix:"token "}};if(encoded.startsWith("literal:"))return{name,value:{source:"literal",value:encoded.slice(8)}};throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`)})}__name(parseHeaders,"parseHeaders");function parseJson(value,flag2){try{return JSON.parse(value)}catch{throw new WebhookCommandError("WEBHOOK_JSON_INVALID",`${flag2} must be valid JSON. Quote the value so your shell passes it as one argument.`)}}__name(parseJson,"parseJson");async function parseJsonInput(value,flag2,cwd){let input=value;if(value==="-")input=await readStdin2();else if(value.startsWith("@")){let path50=resolve9(resolveProjectCwd(cwd),value.slice(1));try{input=await readFile5(path50,"utf8")}catch{throw new WebhookCommandError("WEBHOOK_INPUT_READ_FAILED",`Could not read ${flag2} input from '${path50}'.`)}}return parseJson(input,flag2)}__name(parseJsonInput,"parseJsonInput");async function readStdin2(){let input="";process.stdin.setEncoding("utf8");for await(let chunk of process.stdin)input+=chunk;return input}__name(readStdin2,"readStdin");function parseJsonObject3(value,flag2){let parsed=parseJson(value,flag2);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new WebhookCommandError("WEBHOOK_DATA_INVALID",`${flag2} must be a JSON object.`);return parsed}__name(parseJsonObject3,"parseJsonObject");function parseOnOff(value,flag2){if(value==="on")return!0;if(value==="off")return!1;throw new WebhookCommandError("WEBHOOK_TOGGLE_INVALID",`${flag2} must be 'on' or 'off'.`)}__name(parseOnOff,"parseOnOff");function parseLimit4(value){let limit=Number(value);if(!Number.isInteger(limit)||limit<1||limit>100)throw new WebhookCommandError("WEBHOOK_LIMIT_INVALID","--limit must be an integer from 1 to 100.");return limit}__name(parseLimit4,"parseLimit");function renderJson(command,data2){ui.result({command,data:data2,render:__name(()=>JSON.stringify(data2,null,2),"render")})}__name(renderJson,"renderJson");init_dist();init_auth();async function whoamiCommand(){let creds=requireCredentials();if(!creds.user){ui.error({command:"whoami",code:"NOT_AUTHENTICATED",message:"Could not resolve the current user from local credentials.",hint:"Run `fimo login` again."});return}let displayName=creds.user.name||creds.user.email,activeOrganization=creds.activeOrganization?.name??null;ui.kv({command:"whoami",headline:`Signed in as ${displayName} (${creds.user.email})`,fields:{user:displayName,email:creds.user.email,active_organization:activeOrganization},hint:activeOrganization===null?"Run `fimo orgs switch` to pick an active organization.":void 0})}__name(whoamiCommand,"whoamiCommand");init_config();var TOP_LEVEL_HELP_GROUPS=[{title:"Account",commands:["login","logout","whoami"]},{title:"Project lifecycle",commands:["create","migrate","deploy","logs","validate","describe"]},{title:"Projects & teams",commands:["projects","orgs","invite","credits","referral","rename","delete","unpublish"]},{title:"Environments & releases",commands:["environments","status","branch","checkout","switch","pull","diff","merge","publish","preview"]},{title:"Content & media",commands:["schemas","entries","forms","translations","assets","generate","models"]},{title:"Domains & analytics",commands:["domains","analytics"]},{title:"Agents & integrations",commands:["agents","skills","rules","integrations","channels","mcp"]},{title:"Configuration",commands:["vars","secrets"]},{title:"Help",commands:["support","help"]}];function configureGroupedHelp(program2){program2.configureHelp({...program2.configureHelp(),formatHelp:__name((cmd,helper)=>formatHelpWithGroupedCommands(cmd,helper,TOP_LEVEL_HELP_GROUPS),"formatHelp")})}__name(configureGroupedHelp,"configureGroupedHelp");function formatHelpWithGroupedCommands(cmd,helper,groups){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80,formatItem=__name((term,description)=>helper.formatItem(term,termWidth,description,helper),"formatItem"),output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>formatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));argumentList.length>0&&(output=output.concat([helper.styleTitle("Arguments:"),...argumentList,""]));let optionList=helper.visibleOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));if(optionList.length>0&&(output=output.concat([helper.styleTitle("Options:"),...optionList,""])),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));globalOptionList.length>0&&(output=output.concat([helper.styleTitle("Global Options:"),...globalOptionList,""]))}let commandSections=formatGroupedCommandSections(cmd,helper,groups,termWidth);return commandSections.length>0&&(output=output.concat([helper.styleTitle("Commands:"),...commandSections,""])),output.join(`
|
|
1438
1441
|
`)}__name(formatHelpWithGroupedCommands,"formatHelpWithGroupedCommands");function formatGroupedCommandSections(cmd,helper,groups,termWidth){let visibleCommands=helper.visibleCommands(cmd);if(visibleCommands.length===0)return[];let commandByName=new Map(visibleCommands.map(command=>[command.name(),command])),renderedNames=new Set,sections=[];for(let group of groups){let rows=group.commands.map(name=>commandByName.get(name)).filter(command=>command!==void 0).map(command=>(renderedNames.add(command.name()),indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper))));rows.length>0&&(sections.length>0&§ions.push(""),sections.push(` ${group.title}:`,...rows))}let ungroupedRows=visibleCommands.filter(command=>!renderedNames.has(command.name())).map(command=>indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper)));return ungroupedRows.length>0&&(sections.length>0&§ions.push(""),sections.push(" Other commands:",...ungroupedRows)),sections}__name(formatGroupedCommandSections,"formatGroupedCommandSections");function indentBlock(value){return value.split(`
|
|
1439
1442
|
`).map(line=>` ${line}`).join(`
|
|
1440
1443
|
`)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs48.readFileSync(path49.join(CLI_ROOT,"package.json"),"utf8"));typeof pkg.version=="string"&&pkg.version.length>0&&(pkgVersion=pkg.version)}catch{}let releaseId;try{let release=JSON.parse(fs48.readFileSync(path49.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--env <name>","Override the env this command targets (defaults to the current git branch, falling back to `main`)").option("--branch <name>","Override the Fimo Branch this command targets (legacy alias: `--env`)").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",thisCommand=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"})});program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);registerEnvironmentsCommands(program);program.command("invite").description("Invite a user to an organization or project").option("--target <target>","Invite target: organization or project").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Project ID (defaults to the current project when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Project directory used to resolve the current project").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("mcp").description("Serve the Fimo MCP server over stdio (for MCP clients such as Claude Code or Cursor)").action(mcpCommand);program.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);program.command("link").description("Link the current application to a Fimo project, in place (repairs an existing link)").argument("[projectId]","Project ID to link (defaults to the linked project, else prompts)").option("--env <name>","Env to link (defaults to the current git branch, else main)").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo project locally: sign in, create or link a project, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing project instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--env <name>","Env to check out when linking an existing project (defaults to main)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);var migrate=program.command("migrate").description("Prepare agent-ready migrations from existing websites into Fimo").argument("[url]","Published source site URL for the agent-ready migration draft").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').action((url,dir,options)=>{if(!url){migrate.help();return}return migrateRunCommand(url,dir,options)});migrate.command("init").description("Set up the migration target: crawl a live site into draft artifacts, or link/create the Fimo project for a source-backed migration").argument("[target]","Published source site URL to crawl, or a target project directory for a source-backed migration").argument("[dir]","Target Fimo project directory for a URL migration (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--project-id <projectId>","Link an owner-supplied existing project (source-backed migration; delegates to `fimo init`)").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the resulting manifest as JSON").action(migrateInitCommand);migrate.command("pull").description("Refresh the current migration artifacts from the source URL stored in manifest.json").option("-C, --cwd <dir>","Project directory").option("--max-pages <n>","Maximum number of HTML pages to crawl (default uses previous manifest)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the refreshed manifest as JSON").action(migratePullCommand);migrate.command("inspect").description("Print a summary of the URL migration manifest, or of the canonical .fimo/migration ledger").option("-C, --cwd <dir>","Project directory").option("--json","Output the manifest as JSON").action(migrateInspectCommand);migrate.command("apply").description("Generate an agent-ready Fimo scaffold from the URL-crawl draft manifest (URL migrations only)").option("-C, --cwd <dir>","Project directory").option("--json","Output the apply result as JSON").action(migrateApplyCommand);migrate.command("refine").description("Prepare a high-context agent handoff to refine the URL-crawl draft toward the source site (URL migrations only)").option("-C, --cwd <dir>","Project directory").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').option("--json","Output the refine result as JSON").action(migrateRefineCommand);migrate.command("import").description("Print the import plan as regular Fimo CLI commands; writes no data").option("-C, --cwd <dir>","Project directory").option("--json","Output suggested commands as JSON").action(migrateImportCommand);migrate.command("manifest").description("Build or refresh the canonical migration manifest at .fimo/migration/manifest.json").option("-C, --cwd <dir>","Project directory").option("--output <path>","Manifest output path relative to the project directory").option("--fresh","Discard previous canonical manifest progress while rebuilding").action(migrateManifestCommand);migrate.command("report").description("Write the migration QA report from the canonical manifest").option("-C, --cwd <dir>","Project directory").option("--manifest <path>","Canonical manifest path relative to the project directory").option("--output <path>","Report output path relative to the project directory").option("--no-update-manifest","Do not write qa.status and qa.checks back to the manifest").action(migrateReportCommand);program.command("deploy").description("Push main to Fimo and deploy to preview (use --publish to also go live)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--no-wait","Don't wait for the deployed preview to serve a page. Validation, push, and sandbox sync are still waited for; the result reports readiness as skipped. Not a substitute for --no-restart.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);program.command("logs").description("Show the current env sandbox's dependency-install and dev-server output (newest first)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--limit <n>","Maximum events to return (1-1000, default 200)").option("--before <cursor>","Opaque cursor from a previous page, to fetch older events").addHelpText("after",`
|
|
1441
1444
|
Logs come from the sandbox's own process buffers, so they end when the sandbox does.
|
|
1442
1445
|
There is no --follow; re-run the command instead.
|
|
1443
|
-
`).action(logsCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (Premium plan required)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: clean dist/server and *.data files (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete envs (multi-surface env = git branch + per-env Neon DB + sandbox)").argument("[name]","Env name (omit to list)").option("-v, --verbose","Include deleted envs").option("--all","Also list Fimo's own agent envs (task/*), normally hidden").option("-d, --delete","Delete the named env (drops sandbox + Neon branch + R2 prefix)").option("--from <env>","Parent env to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to an env (or create + switch with -b)").argument("<name>","Env name").option("-b, --create","Create the env if it does not exist").option("--from <env>","Parent env (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch envs)").argument("<name>","Env name").action(checkoutCommand);program.command("pull").description("Sync the current env's data plane from its parent").option("--from <env>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-env diff across all surfaces").argument("[from]","From env (defaults to current env)").argument("[to]","To env (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another env into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source env").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);program.command("publish").description("Tag main@HEAD as release/<version> + trigger prod swap").option("-C, --cwd <dir>","Project directory").option("--version <ver>","Semver version for the release (e.g. 1.4.2)").option("--notes <text>","Optional release notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);program.command("status").description("Multi-surface env status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <env>","Comparison target (defaults to the parent env or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");entries.command("list").description("List entries of a content type").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Max entries to return").option("--offset <n>","Offset for pagination").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference fields to populate, e.g. author,contributors").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").option("--upsert-by <field>","Update or create by a stable data field (migration imports prefer slug)").option("--chunk-size <count>","Entries per request (default 100, maximum 1000)").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");assets2.command("list").description("List assets").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").option("--limit <n>","Max results").option("--offset <n>","Offset").action(assetsListCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("delete").description("Delete an asset").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsDeleteCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
1446
|
+
`).action(logsCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (Premium plan required)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: clean dist/server and *.data files (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete envs (multi-surface env = git branch + per-env Neon DB + sandbox)").argument("[name]","Env name (omit to list)").option("-v, --verbose","Include deleted envs").option("--all","Also list Fimo's own agent envs (task/*), normally hidden").option("-d, --delete","Delete the named env (drops sandbox + Neon branch + R2 prefix)").option("--from <env>","Parent env to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to an env (or create + switch with -b)").argument("<name>","Env name").option("-b, --create","Create the env if it does not exist").option("--from <env>","Parent env (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch envs)").argument("<name>","Env name").action(checkoutCommand);program.command("pull").description("Sync the current env's data plane from its parent").option("--from <env>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-env diff across all surfaces").argument("[from]","From env (defaults to current env)").argument("[to]","To env (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another env into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source env").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);var publish=program.command("publish").description("Tag main@HEAD as release/<version> + trigger prod swap").option("-C, --cwd <dir>","Project directory").option("--version <ver>","Semver version for the release (e.g. 1.4.2)").option("--notes <text>","Optional release notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);publish.command("list").description("Publication attempts for the current project, newest first").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Attempts to return (1-100, default 20)").option("--before <cursor>","Opaque cursor from a previous page").action(publishListCommand);publish.command("inspect").description("One publication attempt in full, including why it failed").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Project directory").action(publishInspectCommand);publish.command("logs").description("Read a publication's build log from its hosting provider").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Events to return (1-1000, default 200)").action(publishLogsCommand);program.command("status").description("Multi-surface env status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <env>","Comparison target (defaults to the parent env or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");entries.command("list").description("List entries of a content type").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Max entries to return").option("--offset <n>","Offset for pagination").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference fields to populate, e.g. author,contributors").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").option("--upsert-by <field>","Update or create by a stable data field (migration imports prefer slug)").option("--chunk-size <count>","Entries per request (default 100, maximum 1000)").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");assets2.command("list").description("List assets").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").option("--limit <n>","Max results").option("--offset <n>","Offset").action(assetsListCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("delete").description("Delete an asset").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsDeleteCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
1444
1447
|
Supported agents:
|
|
1445
1448
|
Universal (always covered via AGENTS.md, no per-agent file needed):
|
|
1446
1449
|
Codex, OpenCode, Aider, and other AGENTS.md-native tools
|