fimo 0.10.0 → 0.10.1-staging.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/skills/fimo-cli/SKILL.md +3 -1
- package/assets/skills/fimo-cli/references/history.md +40 -0
- package/assets/skills/fimo-cli/references/schedules.md +45 -22
- package/assets/skills/fimo-studio/SKILL.md +4 -2
- package/assets/skills/fimo-studio/references/schedules.md +43 -0
- package/assets/skills/fimo-studio/references/version-history.md +9 -9
- package/dist/build/vite/plugins/translations.js +174 -57
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +36 -14
- package/package.json +1 -1
- package/release.json +2 -2
- package/templates/react-router/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -3,12 +3,12 @@ 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)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __commonJS=(cb,mod)=>function(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};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));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 string=""+input,index2=string.indexOf(close,open2.length);return~index2?open2+replaceClose(string,close,replace,index2)+close:open2+string+close},"formatter"),replaceClose=__name((string,close,replace,index2)=>{let result="",cursor=0;do result+=string.substring(cursor,index2)+replace,cursor=index2+close.length,index2=string.indexOf(close,cursor);while(~index2);return result+string.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
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(ANSI_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 ANSI_PATTERN,init_width=__esm({"../../packages/cli-kit/dist/width.js"(){"use strict";ANSI_PATTERN=/\x1B\[[0-9;]*[A-Za-z]/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
|
-
`)}__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
|
|
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}
|
|
9
9
|
`)}__name(renderRaw,"renderRaw");function renderResult(event){let body=event.render(context);if(stdout.write(body.endsWith(`
|
|
10
10
|
`)?body:`${body}
|
|
11
|
-
`),event.warnings)for(let w3 of event.warnings)write(stdout,` ${palette2.warn(symbols.warn)} ${w3}`);maybeHint(event.hint)}__name(renderResult,"renderResult");function renderError(event){write(stderr,`${palette2.error(symbols.fail)} ${palette2.error(event.message)}`),event.hint&&write(stderr,` ${palette2.hint(symbols.hint)} ${event.hint}`)}__name(renderError,"renderError");function renderWarn(event){write(stderr,`${palette2.warn(symbols.warn)} ${event.message}`)}__name(renderWarn,"renderWarn");function renderInfo2(event){write(stdout,event.message),maybeHint(event.hint)}__name(renderInfo2,"renderInfo");function maybeHint(hint){hint&&(write(stdout,""),write(stdout,`${palette2.hint(symbols.hint)} ${palette2.hint(hint)}`))}return __name(maybeHint,"maybeHint"),{ok(event){switch(event.kind){case"message":renderMessage(event);return;case"table":
|
|
11
|
+
`),event.warnings)for(let w3 of event.warnings)write(stdout,` ${palette2.warn(symbols.warn)} ${w3}`);maybeHint(event.hint)}__name(renderResult,"renderResult");function renderError(event){write(stderr,`${palette2.error(symbols.fail)} ${palette2.error(event.message)}`),event.hint&&write(stderr,` ${palette2.hint(symbols.hint)} ${event.hint}`)}__name(renderError,"renderError");function renderWarn(event){write(stderr,`${palette2.warn(symbols.warn)} ${event.message}`)}__name(renderWarn,"renderWarn");function renderInfo2(event){write(stdout,event.message),maybeHint(event.hint)}__name(renderInfo2,"renderInfo");function maybeHint(hint){hint&&(write(stdout,""),write(stdout,`${palette2.hint(symbols.hint)} ${palette2.hint(hint)}`))}return __name(maybeHint,"maybeHint"),{ok(event){switch(event.kind){case"message":renderMessage(event);return;case"table":renderTable2(event);return;case"kv":renderKv(event);return;case"script":renderScript(event);return;case"raw":renderRaw(event);return;case"result":renderResult(event);return}},error:renderError,warn:renderWarn,info:renderInfo2}}function formatScalar(value){return typeof value=="string"?value:typeof value=="number"||typeof value=="boolean"?String(value):JSON.stringify(value)}var init_renderer_pretty=__esm({"../../packages/cli-kit/dist/renderer-pretty.js"(){"use strict";init_width();__name(makePrettyRenderer,"makePrettyRenderer");__name(formatScalar,"formatScalar")}});function makeSymbols(ascii){return ascii?{...ASCII}:{...UNICODE}}var UNICODE,ASCII,init_symbols=__esm({"../../packages/cli-kit/dist/symbols.js"(){"use strict";UNICODE={ok:"\u2713",warn:"\u26A0",fail:"\u2717",hint:"\u2192",info:"\u2139",active:"*"},ASCII={ok:"[ok]",warn:"[warn]",fail:"[fail]",hint:">",info:"[info]",active:"*"};__name(makeSymbols,"makeSymbols")}});function resolveMode(opts={}){let format2=pickFormat(opts),color=format2==="pretty"&&supportsColor(opts.noColor),ascii=opts.ascii===!0||opts.asciiEnvVar!==void 0&&process.env[opts.asciiEnvVar]==="1";return{format:format2,color,ascii,stdout:opts.stdout??process.stdout,stderr:opts.stderr??process.stderr}}function pickFormat(opts){return opts.json||opts.jsonEnvVar!==void 0&&process.env[opts.jsonEnvVar]==="json"?"json":"pretty"}function isTtyStream(stream){return stream.isTTY===!0}function supportsColor(noColor){return noColor||process.env.NO_COLOR&&process.env.NO_COLOR.length>0||process.env.TERM==="dumb"?!1:process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0"?!0:process.stdout&&process.stdout.isTTY===!0}var init_tty=__esm({"../../packages/cli-kit/dist/tty.js"(){"use strict";__name(resolveMode,"resolveMode");__name(pickFormat,"pickFormat");__name(isTtyStream,"isTtyStream");__name(supportsColor,"supportsColor")}});function isStrictMode(){return process.env.VITEST==="true"||process.env.CLI_KIT_STRICT==="true"}function trackTerminalEmit(command,kind){if(terminalEmitCount+=1,terminalEmitCount===1)return;let msg=`[cli-kit] command '${command}' emitted ${terminalEmitCount} envelopes (kind=${kind}). One envelope per command \u2014 fold side-effects into the parent envelope's details. See packages/cli-kit/CLAUDE.md.`;if(isStrictMode())throw new Error(msg);process.stderr.write(`${msg}
|
|
12
12
|
`)}function initUi(opts={}){let resolved=resolveMode(opts),palette2=makePalette(resolved.color),symbols=makeSymbols(resolved.ascii);return renderer=resolved.format==="json"?makeJsonRenderer({stdout:resolved.stdout,stderr:resolved.stderr}):makePrettyRenderer({palette:palette2,symbols,context:{color:resolved.color,ascii:resolved.ascii},stdout:resolved.stdout,stderr:resolved.stderr}),mode=resolved,terminalEmitCount=0,resolved}function activeRenderer(){return renderer||initUi(),renderer}function currentMode(){return mode||initUi(),mode}function _resetUiForTest(){renderer=null,mode=null,terminalEmitCount=0}var renderer,mode,terminalEmitCount,ui,init_emitter=__esm({"../../packages/cli-kit/dist/emitter.js"(){"use strict";init_colors();init_renderer_json();init_renderer_pretty();init_symbols();init_tty();renderer=null,mode=null,terminalEmitCount=0;__name(isStrictMode,"isStrictMode");__name(trackTerminalEmit,"trackTerminalEmit");__name(initUi,"initUi");__name(activeRenderer,"activeRenderer");__name(currentMode,"currentMode");ui={ok(event){trackTerminalEmit(event.command,"ok"),activeRenderer().ok({kind:"message",...event})},table(event){trackTerminalEmit(event.command,"table"),activeRenderer().ok({kind:"table",...event})},kv(event){trackTerminalEmit(event.command,"kv"),activeRenderer().ok({kind:"kv",...event})},script(event){trackTerminalEmit(event.command,"script"),activeRenderer().ok({kind:"script",...event})},raw(event){trackTerminalEmit(event.command,"raw"),activeRenderer().ok({kind:"raw",...event})},result(event){trackTerminalEmit(event.command,"result"),activeRenderer().ok({kind:"result",...event})},error(event){trackTerminalEmit(event.command,"error"),activeRenderer().error(event),(process.exitCode===void 0||process.exitCode===0)&&(process.exitCode=1)},warn(event){activeRenderer().warn(event)},info(event){trackTerminalEmit(event.command,"info"),activeRenderer().info(event)}};__name(_resetUiForTest,"_resetUiForTest")}});function spinner(label){let mode2=currentMode();return mode2.format==="json"?NOOP:isTtyStream(mode2.stderr)?animatedSpinner(label,mode2.stderr):staticSpinner(label,mode2.stderr,mode2.ascii)}function animatedSpinner(initial,stream){let label=initial,frame=0,stopped=!1,interval=setInterval(()=>{stopped||(clearLine(stream),stream.write(`${FRAMES[frame%FRAMES.length]} ${label}`),frame++)},FRAME_MS);return interval.unref(),{update(next2){label=next2},succeed(message){finish(message??label,"\u2713")},fail(message){finish(message??label,"\u2717")},stop(){stopped=!0,clearInterval(interval),clearLine(stream)}};function finish(message,glyph){stopped=!0,clearInterval(interval),clearLine(stream),message!==null&&stream.write(`${glyph} ${message}
|
|
13
13
|
`)}__name(finish,"finish")}function staticSpinner(initial,stream,ascii){let startGlyph=ascii?"...":"\u2026",okGlyph=ascii?"[ok]":"\u2713",failGlyph=ascii?"[fail]":"\u2717";stream.write(`${startGlyph} ${initial}
|
|
14
14
|
`);let label=initial,stopped=!1;return{update(next2){label=next2,stream.write(`${startGlyph} ${next2}
|
|
@@ -39,7 +39,7 @@ 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 process8.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()}`,process8.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=path47.basename(filename,path47.extname(filename)),this}executableDir(path48){return path48===void 0?this._executableDir:(this._executableDir=path48,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(process8.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(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.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{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 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)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(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:path47,message}=issue;return`${Array.isArray(path47)&&path47.length>0?`${path47.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}var 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_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path47,status,detail,code2,body){super(`API ${method} ${path47} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path47,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");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.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(path47,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}${path47}`,{...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",path47,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async rawRequest(path47,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}${path47}`,{...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"} ${path47} 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/${encodeURIComponent(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/${encodeURIComponent(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 listProjectSecretEntries(projectId,opts={}){let qs=opts.kind?`?kind=${encodeURIComponent(opts.kind)}`:"";return(await this.request(`/api/management/projects/${projectId}/secrets${qs}`)).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})})).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})})).data}async deleteProjectSecretEntry(projectId,key,kind){let qs=`?kind=${encodeURIComponent(kind)}`;await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}${qs}`,{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 runSchedule(projectId,name){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(name)}/run`,{method:"POST"})).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 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,name){await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(name)}`,{method:"DELETE"})}async listEnvs(projectId,opts={}){let qs=opts.includeDeleted?"?includeDeleted=true":"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}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,path47,opts={}){let qs=lazyFetchQs(opts.against,{path:path47});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),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getActivationDiff(projectId,env,agentName,triggerIndex,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/activations/${encodeURIComponent(agentName)}/${triggerIndex}`;return(await this.request(qs?`${path47}?${qs}`:path47)).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 activateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"POST",body:JSON.stringify(body)})).data}async deactivateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"DELETE",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){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).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/${encodeURIComponent(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",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="",errorMessage3=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(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.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{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 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)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(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:path47,message}=issue;return`${Array.isArray(path47)&&path47.length>0?`${path47.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}var 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_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path47,status,detail,code2,body){super(`API ${method} ${path47} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path47,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");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.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(path47,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}${path47}`,{...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",path47,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async rawRequest(path47,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}${path47}`,{...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"} ${path47} 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/${encodeURIComponent(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/${encodeURIComponent(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 qs=opts.kind?`?kind=${encodeURIComponent(opts.kind)}`:"";return(await this.request(`/api/management/projects/${projectId}/secrets${qs}`)).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})})).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})})).data}async deleteProjectSecretEntry(projectId,key,kind){let qs=`?kind=${encodeURIComponent(kind)}`;await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}${qs}`,{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 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 qs=opts.includeDeleted?"?includeDeleted=true":"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}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,path47,opts={}){let qs=lazyFetchQs(opts.against,{path:path47});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),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getActivationDiff(projectId,env,agentName,triggerIndex,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/activations/${encodeURIComponent(agentName)}/${triggerIndex}`;return(await this.request(qs?`${path47}?${qs}`:path47)).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 activateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"POST",body:JSON.stringify(body)})).data}async deactivateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"DELETE",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){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).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/${encodeURIComponent(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",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="",errorMessage3=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
|
|
|
@@ -192,7 +192,7 @@ description: Fimo project rules
|
|
|
192
192
|
alwaysApply: true
|
|
193
193
|
---
|
|
194
194
|
|
|
195
|
-
${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}return selected.has("windsurf")&&writeIfMissing(".windsurfrules",agentsMdContent),selected.has("gemini-cli")&&writeIfMissing("GEMINI.md",agentsMdContent),result}function syncPerAgentVariants(targetDir,agents){let agentsMdPath=path9.join(targetDir,"AGENTS.md");if(!fs9.existsSync(agentsMdPath))throw new Error(`No AGENTS.md found in ${targetDir}. Run \`fimo create\` first, or create AGENTS.md manually before running \`fimo rules sync\`.`);let agentsMdContent=fs9.readFileSync(agentsMdPath,"utf8");return writePerAgentVariants(targetDir,agents,agentsMdContent)}function detectAgentsInProject(cwd){let detected=[];return fs9.existsSync(path9.join(cwd,"CLAUDE.md"))&&detected.push("claude-code"),fs9.existsSync(path9.join(cwd,".cursor","rules","fimo.mdc"))&&detected.push("cursor"),fs9.existsSync(path9.join(cwd,".windsurfrules"))&&detected.push("windsurf"),fs9.existsSync(path9.join(cwd,"GEMINI.md"))&&detected.push("gemini-cli"),detected}var TEMPLATE_ROOT,AGENT_TEMPLATES_ROOT,EXCLUDED_DIRS,init_scaffold=__esm({"src/cli/utils/scaffold.ts"(){init_templates();init_config();init_templates();TEMPLATE_ROOT=getTemplatePath("react-router"),AGENT_TEMPLATES_ROOT=path9.resolve(CLI_ROOT,"assets","agent-templates"),EXCLUDED_DIRS=new Set(["node_modules","dist","build",".turbo",".git"]);__name(resolveTemplateRoot,"resolveTemplateRoot");__name(resolveAgentTemplatesRoot,"resolveAgentTemplatesRoot");__name(resolveAgentTemplate,"resolveAgentTemplate");__name(listAgentTemplates,"listAgentTemplates");__name(copyAgentTemplate,"copyAgentTemplate");__name(copyTemplate,"copyTemplate");__name(pinFimoDependency,"pinFimoDependency");__name(copyTree,"copyTree");__name(writePerAgentVariants,"writePerAgentVariants");__name(syncPerAgentVariants,"syncPerAgentVariants");__name(detectAgentsInProject,"detectAgentsInProject")}});import{z as z5}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z5.ZodOptional||schema instanceof z5.ZodNullable||schema instanceof z5.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z5.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z5.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 z5.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z5.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],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z5.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 z5.ZodObject)return createObjectDTO(schema);if(schema instanceof z5.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 z6}from"zod";var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z6.object({data:dataSchema}),"createResponseSchema")}});import{z as z7}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z7.object({page:z7.coerce.number().int().positive().default(1),limit:z7.coerce.number().int().positive().max(100).default(20)})}});import{z as z8}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectVisibilitySchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,RESERVED_CONTENT_FIELD_NAMES,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:z8.coerce.date(),positiveInt:z8.number().int().positive(),nonNegativeInt:z8.number().int().nonnegative()},BaseEntitySchema=z8.object({id:z8.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z8.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z8.enum(["full","edit","comment","view","agent"]),ProjectPrincipalTypeSchema=z8.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z8.enum(["public","private"]),ProjectStatusSchema=z8.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z8.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z8.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z8.enum(["owner","admin","member"]),AssetTypeSchema=z8.enum(["file","folder"]),TemplateCodeSchema=z8.enum(["Free","Premium"]),FieldTypeSchema=z8.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],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_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],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_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]))}});import{z as z9}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function isProductionEnv(env){return env===PRODUCTION_ENV}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");EnvSchema=z9.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")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z10}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=z10.preprocess(referenceValuePreprocess,z10.object({documentId:z10.uuid()})),ReferenceInputValueSchema=z10.preprocess(referenceValuePreprocess,z10.union([z10.object({documentId:z10.uuid()}),z10.object({slug:z10.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=z10.preprocess(polymorphicReferenceValuePreprocess,z10.object({contentType:z10.string().min(1),documentId:z10.uuid()})),PolymorphicReferenceInputValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.union([z10.object({contentType:z10.string().min(1),documentId:z10.uuid()}),z10.object({contentType:z10.string().min(1),slug:z10.string().min(1)})]))}});import{z as z11}from"zod";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,path47){let conditionPath=[...path47,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,path47)=>{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,path47));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path47,fieldName,variant.uid]);else walk(field.schema.fields,[...path47,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path47,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path47,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,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"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=3,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z11.union([z11.object({field:z11.string().min(1),equals:z11.union([z11.string(),z11.number(),z11.boolean()])}).strict(),z11.object({field:z11.string().min(1),in:z11.array(z11.union([z11.string(),z11.number(),z11.boolean()])).min(1)}).strict()]),commonFieldShape={label:z11.string().min(1).optional(),description:z11.string().optional(),editable:z11.boolean().optional(),required:z11.boolean().optional(),default:z11.unknown().optional(),showIf:z11.union([showIfClauseSchema,z11.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z11.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=z11.object({...commonFieldShape,type:z11.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z11.number().optional(),max:z11.number().optional(),minLength:z11.number().int().nonnegative().optional(),maxLength:z11.number().int().nonnegative().optional(),regex:z11.string().optional(),multiple:z11.boolean().optional(),allowedMimeTypes:z11.array(z11.string()).optional(),options:z11.array(z11.string().min(1)).min(1).optional(),unique:z11.boolean().optional(),i18n:z11.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!=="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=z11.object({...commonFieldShape,type:z11.literal("reference"),target:z11.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z11.array(z11.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z11.boolean().optional(),i18n:z11.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=z11.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z11.record(z11.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=z11.object({uid:z11.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z11.string().min(1),description:z11.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z11.object({fields:blockFieldsSchema}).strict(),blocksSchema=z11.object({oneOf:z11.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=z11.object({...commonFieldShape,type:z11.literal("blocks"),min:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z11.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=z11.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z12}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","cutover_step","agent_delegate","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send"],AuditActionSchema=z12.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z12.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z12.enum(AUDIT_ACTOR_KINDS)}});import{z as z13}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,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers: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=z13.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","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:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers: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=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.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=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.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=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.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=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)})}});import{z as z14}from"zod";var ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,QuestionAnswerMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionListResponseSchema,ProjectVersionResponseSchema,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_common();init_create_dto();init_response();ProjectDTOSchema=BaseEntitySchema.extend({name:z14.string(),displayName:z14.string().nullable(),subdomain:z14.string().nullable().optional(),subdomainUpdatedAt:z14.date().nullable().optional(),organizationId:z14.string().nullable(),createdBy:z14.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z14.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z14.string(),thumbnailUrl:z14.string().nullable(),publishedThumbnailUrl:z14.string().nullable(),category:z14.string().nullable(),appUrl:z14.string().nullable(),lastPublishedAt:z14.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z14.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z14.object({id:z14.uuid(),name:z14.string(),displayName:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),visibility:ProjectVisibilitySchema,category:z14.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z14.object({id:z14.string(),name:z14.string(),avatar:z14.string().nullable(),color:z14.object({bg:z14.string(),text:z14.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z14.object({path:z14.string(),content:z14.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z14.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z14.object({id:z14.string(),messageId:z14.string(),versionId:z14.string().nullable(),role:ProjectChatMessageRole,parts:z14.array(z14.any()),createdAt:z14.coerce.date()}),MessageUserMetadataSchema=z14.object({id:z14.string(),name:z14.string().nullable().optional(),image:z14.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z14.object({shortTitle:z14.string().optional(),questions:z14.array(z14.object({header:z14.string(),question:z14.string(),answer:z14.string(),selectedLabels:z14.array(z14.string()),freeText:z14.string(),skipped:z14.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z14.number(),metadata:z14.object({user:MessageUserMetadataSchema,changeManifest:z14.array(z14.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z14.object({id:z14.uuid(),versionId:z14.string(),projectId:z14.uuid(),commitHash:z14.string(),name:z14.string(),description:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),createdAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectDocumentContentDTOSchema=z14.object({content:z14.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z14.array(ProjectDTOSchema)),ProjectVersionListResponseSchema=createResponseSchema(z14.array(ProjectVersionDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),VersionMutationResponseSchema=createResponseSchema(z14.object({success:z14.boolean(),message:z14.string().optional()})),ProjectPublicationStateDTOSchema=z14.object({isPublished:z14.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z14.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z14.object({success:z14.boolean(),message:z14.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z15}from"zod";var ProjectEnvStatusSchema,ProjectEnvDTOSchema,ProjectEnvDTO,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_create_dto();init_response();ProjectEnvStatusSchema=z15.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z15.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z15.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z15.string().nullable(),deletedAt:z15.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z15.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z15.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z15.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z15.object({surface:z15.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z15.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z15.number().int().nonnegative(),conflictCount:z15.number().int().nonnegative()}),EnvDiffResultSchema=z15.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z15.coerce.date(),surfaces:z15.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z16}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=z16.object({success:z16.literal(!0),downloadUrl:z16.string(),expiresAt:z16.string(),fileSize:z16.number(),duration:z16.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z16.object({success:z16.literal(!0),projectId:z16.string(),projectName:z16.string(),displayName:z16.string(),projectUrl:z16.string(),duration:z16.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z16.object({contentTypes:z16.number(),entries:z16.number(),assets:z16.number(),translations:z16.number(),forms:z16.number(),codeFiles:z16.number(),assetFiles:z16.number()}),ImportPreviewSurfaceDTOSchema=z16.object({name:z16.string(),included:z16.boolean(),count:z16.number().optional(),note:z16.string().optional()}),ImportPreviewDTOSchema=z16.object({projectName:z16.string(),displayName:z16.string().nullable(),visibility:z16.string().nullable(),category:z16.string().nullable(),exportedAt:z16.string(),version:z16.string(),envScope:z16.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z16.array(ImportPreviewSurfaceDTOSchema),fileSize:z16.number(),fileName:z16.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z16.object({success:z16.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z17}from"zod";var TriggerKindSchema,ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2,TriggerSchema2,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z17.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z17.object({type:z17.literal("manual")}),ScheduleTriggerSchema=z17.object({type:z17.literal("schedule"),cron:z17.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:z17.string().optional()}),WebhookTriggerSchema2=z17.object({type:z17.literal("webhook"),path:z17.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z17.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z18}from"zod";var ActivateRequestSchema,DeactivateRequestSchema,AgentActivationDTOSchema,AgentActivationDTO,AgentActivationsListResponseSchema,AgentActivationResponseSchema,WebhookPathTakenErrorSchema,ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_activation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-activation.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();ActivateRequestSchema=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z18.object({projectId:z18.uuid(),env:EnvSchema,agentName:z18.string().min(1),triggerIndex:z18.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema2,enabled:z18.boolean(),lastFiredAt:z18.coerce.date().nullable(),webhookPath:z18.string().nullable(),createdAt:z18.coerce.date(),updatedAt:z18.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z18.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z18.object({error:z18.literal("webhook_path_taken"),conflictAgent:z18.string(),path:z18.string()}),ManualRunRequestSchema=z18.object({args:z18.unknown().optional(),requestId:z18.string().min(1).max(128).optional()}),DispatchSkippedSchema=z18.object({skipped:z18.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z18.object({sessionId:z18.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z18.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});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,AgentListItemActivationSchema,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()}),AgentListItemActivationSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z20.string().min(1),active:z20.boolean()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),activations:z20.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,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();AgentSessionStatusSchema=z21.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z21.object({cpuMs:z21.number().nonnegative().default(0),netBytes:z21.number().nonnegative().default(0),walltimeMs:z21.number().nonnegative().default(0),llmTokensIn:z21.number().nonnegative().optional(),llmTokensOut:z21.number().nonnegative().optional()}),AgentSessionDTOSchema=z21.object({id:z21.uuid(),projectId:z21.uuid(),env:EnvSchema,agentName:z21.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z21.unknown().optional(),capabilities:z21.array(z21.string()).optional(),dataSources:z21.array(z21.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z21.string().nullable(),startedAt:z21.coerce.date().nullable(),finishedAt:z21.coerce.date().nullable(),cancelledAt:z21.coerce.date().nullable(),costUsd:z21.number().nonnegative(),costCeilingUsd:z21.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z21.boolean(),lastCheckpointId:z21.uuid().nullable(),branchEnvId:z21.uuid().nullable(),parentSessionId:z21.uuid().nullable(),terminalReason:z21.string().nullable(),errorMessage:z21.string().nullable(),report:z21.string().nullable(),createdAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z21.object({id:z21.uuid(),sessionId:z21.uuid(),checkpointIdx:z21.number().int().nonnegative(),payloadRef:z21.string(),payloadSizeBytes:z21.number().int().nonnegative(),checksum:z21.string().length(64),createdAt:z21.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z21.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z21.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z21.object({session:AgentSessionDTOSchema,checkpoints:z21.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z21.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z21.object({reason:z21.string().min(1).max(120).optional()})}});import{z as z22}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=z22.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z22.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z22.object({id:z22.uuid(),envId:z22.uuid(),sessionId:z22.uuid().nullable(),skillName:z22.string().min(1),classification:AgentBranchClassificationSchema,rationale:z22.string().nullable(),summary:z22.string().nullable(),surfaceDeltas:z22.record(z22.string(),z22.unknown()),createdAt:z22.coerce.date(),decidedAt:z22.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z22.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z22.object({path:z22.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z22.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z22.object({code:z22.literal("merge_conflict"),message:z22.string(),conflicts:z22.record(z22.string(),z22.number().int().nonnegative())})}});import{z as z23}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,BindProjectChannelRequestSchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolOptionsSchema,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,ProjectChannelBindingResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z23.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z23.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z23.enum(["secret_text"]),IntegrationCredentialUsageSchema=z23.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z23.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z23.object({mode:IntegrationAuthModeSchema,label:z23.string().min(1),description:z23.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z23.object({id:z23.string().min(1),label:z23.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z23.boolean()}),IntegrationToolDefinitionDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),description:z23.string().min(1)}),IntegrationRecipeDTOSchema=z23.object({title:z23.string().min(1),description:z23.string().min(1),command:z23.string().min(1).optional()}),IntegrationInfoDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),summary:z23.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z23.array(IntegrationAuthModeDTOSchema),credentials:z23.array(IntegrationCredentialDefinitionDTOSchema),tools:z23.array(IntegrationToolDefinitionDTOSchema),recipes:z23.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),installed:z23.boolean(),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z23.string().nullable(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),installedAt:z23.coerce.date().nullable(),updatedAt:z23.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z23.string(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z23.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z23.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z23.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z23.object({value:z23.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z23.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z23.object({id:z23.uuid(),organizationId:z23.string().min(1),integrationKey:z23.string().min(1),alias:z23.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z23.string().min(1),externalAccountName:z23.string().nullable(),externalBotUserId:z23.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z23.array(z23.string()),connectedAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z23.object({alias:z23.string().min(1).max(120).optional(),token:z23.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z23.object({integrationKey:z23.string().min(1),connectUrl:z23.string().url(),expiresAt:z23.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z23.object({ref:z23.string().min(1),connectionAlias:z23.string().min(1).optional(),agentName:z23.string().min(1).max(160).nullable().optional(),force:z23.boolean().optional()}),ProjectChannelBindingDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),connectionId:z23.uuid(),externalWorkspaceId:z23.string().min(1),externalChannelId:z23.string().min(1),externalChannelName:z23.string().nullable(),agentName:z23.string().nullable(),enabled:z23.boolean(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z23.object({markdown:z23.boolean().optional(),summary:z23.boolean().optional(),links:z23.boolean().optional(),images:z23.boolean().optional(),html:z23.union([z23.literal("cleaned"),z23.literal("raw"),z23.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z23.object({url:z23.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z23.object({query:z23.string().min(1),maxResults:z23.number().int().positive().max(20).optional(),sources:z23.array(z23.enum(["web","news","images"])).min(1).max(3).optional(),categories:z23.array(z23.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z23.enum(["hour","day","week","month","year"]).optional(),location:z23.string().min(1).max(160).optional(),country:z23.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z23.object({url:z23.string().url(),search:z23.string().min(1).optional(),limit:z23.number().int().positive().max(200).optional(),includeSubdomains:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z23.object({url:z23.string().url(),limit:z23.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z23.object({text:z23.string().min(1).max(200).optional(),cron:z23.string().min(1).max(120).optional(),timezone:z23.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z23.object({type:z23.enum(["scrape","crawl"]).default("scrape"),urls:z23.array(z23.string().url()).min(1).max(50),scrapeOptions:z23.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z23.object({name:z23.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z23.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z23.string().min(1).max(2e3).optional(),judgeEnabled:z23.boolean().optional(),retentionDays:z23.number().int().min(1).max(365).optional(),notification:z23.object({email:z23.object({enabled:z23.boolean().default(!0),recipients:z23.array(z23.string().email()).min(1).max(20),includeDiffs:z23.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z23.object({monitorId:z23.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z23.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z23.object({connectionAlias:z23.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z23.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.list"),input:z23.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z23.object({provider:z23.string().min(1),providerCredits:z23.number().nonnegative().optional(),providerCostUsd:z23.number().nonnegative().optional(),requests:z23.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z23.object({credits:z23.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()}),FirecrawlSearchToolOutputSchema=z23.object({query:z23.string(),provider:z23.literal("firecrawl"),warning:z23.string().optional(),results:z23.array(z23.object({title:z23.string(),url:z23.string(),snippet:z23.string().optional(),content:z23.string().optional(),score:z23.number().optional(),publishedAt:z23.string().optional()}))}),FirecrawlMapToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),count:z23.number(),links:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),description:z23.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),total:z23.number(),pages:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()})),warning:z23.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z23.object({cron:z23.string().optional(),text:z23.string().optional(),timezone:z23.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z23.object({id:z23.string().optional(),urls:z23.array(z23.string()).optional(),scrapeOptions:z23.record(z23.string(),z23.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z23.object({id:z23.string(),name:z23.string(),status:z23.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z23.string().nullable().optional(),lastRunAt:z23.string().nullable().optional(),currentCheckId:z23.string().nullable().optional(),targets:z23.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z23.string().nullable().optional(),judgeEnabled:z23.boolean().optional(),estimatedCreditsPerMonth:z23.number().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z23.object({id:z23.string(),monitorId:z23.string(),scheduledFor:z23.string().nullable().optional(),startedAt:z23.string().nullable().optional(),finishedAt:z23.string().nullable().optional(),estimatedCredits:z23.number().optional(),reservedCredits:z23.number().optional(),actualCredits:z23.number().optional(),billingStatus:z23.string().nullable().optional(),summary:z23.object({totalPages:z23.number().optional(),same:z23.number().optional(),changed:z23.number().optional(),new:z23.number().optional(),removed:z23.number().optional(),error:z23.number().optional()}).passthrough().optional(),error:z23.string().nullable().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitors:z23.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),deleted:z23.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),checks:z23.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),check:FirecrawlMonitorCheckOutputSchema,next:z23.string().optional()}),FirecrawlToolKeySchema=z23.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z23.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z23.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z23.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z23.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z23.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema)}});import{z as z24}from"zod";var ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,ProjectScheduleResponseSchema,ProjectSchedulesListResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_create_dto();init_response();ProjectScheduleStatusSchema=z24.enum(["ok","failed"]),ProjectScheduleDTOSchema=z24.object({id:z24.uuid(),projectId:z24.uuid(),env:z24.string().min(1),name:z24.string().min(1),cron:z24.string().min(1),command:z24.string().min(1),enabled:z24.boolean(),lastRunAt:z24.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z24.string().nullable(),createdAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z24.object({name:z24.string().min(1).max(120),cron:z24.string().min(1).max(120),command:z24.string().min(1).max(500)}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListResponseSchema=createResponseSchema(z24.array(ProjectScheduleDTOSchema))}});import{z as z25}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=z25.object({id:z25.uuid(),occurredAt:z25.coerce.date(),projectId:z25.uuid().nullable(),env:z25.string().nullable(),actor:z25.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z25.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z25.unknown().optional(),ipAddress:z25.string().nullable().optional(),userAgent:z25.string().nullable().optional(),error:z25.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z25.object({rows:z25.array(AuditLogRowDTOSchema),nextCursor:z25.string().nullable()})),AuditLogQuerySchema=z25.object({env:z25.string().optional(),action:AuditActionSchema.optional(),actor:z25.string().optional(),from:z25.coerce.date().optional(),to:z25.coerce.date().optional(),limit:z25.coerce.number().int().min(1).max(200).optional(),cursor:z25.string().optional()})}});import{z as z26}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,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,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=z26.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z26.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z26.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z26.object({verb:SurfaceDeltaVerbSchema,key:z26.string(),detail:z26.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z26.record(z26.string(),z26.unknown()).optional()}),PerSurfaceDeltaSchema=z26.object({surface:SurfaceNameSchema,status:z26.enum(["ok","timed_out","failed","unchanged"]),durationMs:z26.number().int().nonnegative().optional(),changedCount:z26.number().int().nonnegative(),conflictCount:z26.number().int().nonnegative(),items:z26.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z26.boolean().optional(),error:z26.string().optional()}),CrossSurfaceFindingSchema=z26.object({id:z26.string(),kind:z26.string(),description:z26.string(),severity:z26.enum(["warning","error"]),source:z26.object({surface:SurfaceNameSchema,key:z26.string()}),target:z26.object({surface:SurfaceNameSchema,key:z26.string()}),actions:z26.array(z26.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z26.object({env:EnvSchema,vs:EnvSchema,syncState:z26.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),agents:z26.array(z26.object({id:z26.string(),name:z26.string(),status:z26.enum(["active","paused","failed"]),lastRunAt:z26.coerce.date().nullable()})).optional(),crossSurface:z26.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z26.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),crossSurface:z26.array(CrossSurfaceFindingSchema).optional(),fingerprint:z26.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z26.object({path:z26.string(),state:z26.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z26.string(),additions:z26.number().int().nonnegative(),deletions:z26.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z26.object({oid:z26.string().optional(),content:z26.string().optional(),truncated:z26.boolean(),binary:z26.boolean()}),CodeConflictDetailSchema=z26.object({path:z26.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z26.string(),targetTipSha:z26.string(),mergeBaseSha:z26.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z26.object({id:z26.string(),slug:z26.string(),contentType:z26.string(),data:z26.record(z26.string(),z26.unknown()),updatedAt:z26.coerce.date()}),ContentRowDiffSchema=z26.object({collection:z26.string(),rowId:z26.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z26.object({name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),fields:z26.record(z26.string(),z26.unknown())}),SchemaTypeDiffSchema=z26.object({typeName:z26.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z26.object({id:z26.string(),name:z26.string(),type:z26.enum(["file","folder"]),mimeType:z26.string().nullable(),storageKey:z26.string().nullable(),url:z26.string().nullable(),fileSize:z26.number().nullable(),width:z26.number().nullable(),height:z26.number().nullable(),altText:z26.string().nullable(),caption:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AssetDiffSchema=z26.object({assetId:z26.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z26.object({locale:z26.string(),key:z26.string(),parent:z26.string().nullable(),child:z26.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z26.object({formName:z26.string(),label:z26.string().nullable(),schemaFingerprint:z26.string(),fields:z26.record(z26.string(),z26.unknown()),settings:z26.record(z26.string(),z26.unknown()).optional()}),FormSchemaDiffSchema=z26.object({formName:z26.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),triggerKind:z26.string(),triggerSpec:z26.record(z26.string(),z26.unknown()),enabled:z26.boolean(),emailRecipients:z26.array(z26.string()).nullable(),qstashScheduleId:z26.string().nullable()}),ActivationDiffSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z26.enum(CONFLICT_KINDS),ConflictSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),kind:ConflictKindSchema.optional(),description:z26.string(),parentValue:z26.unknown().optional(),childValue:z26.unknown().optional(),conflictingFields:z26.array(z26.string()).optional(),code:z26.object({path:z26.string(),unresolvable:z26.boolean().optional(),reason:z26.string().optional()}).optional()}),FieldPickSchema=z26.object({field:z26.string(),choice:z26.enum(["parent","child","pick","ai-pick"]),pickedValue:z26.unknown().optional(),aiSessionId:z26.string().optional()}),ConflictResolutionSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),choice:z26.enum(["parent","child","pick"]),pickedValue:z26.unknown().optional(),fieldPicks:z26.array(FieldPickSchema).optional()}),MergeResultSchema=z26.object({ok:z26.boolean(),mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z26.array(z26.object({surface:SurfaceNameSchema,count:z26.number().int().nonnegative()})),conflicts:z26.array(ConflictSchema).optional(),summary:z26.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z26.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z26.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z26.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z26.boolean().optional()}),ResolvedStrategySchema=z26.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z26.boolean()}),MergeRequestSchema=z26.object({from:EnvSchema,allowDirectMerge:z26.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z26.object({mergeId:z26.string().uuid(),streamUrl:z26.string(),strategy:ResolvedStrategySchema,acceptedAt:z26.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z26.object({mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z26.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z26.array(ConflictSchema),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedBy:z26.string().nullable(),lastEditedAt:z26.coerce.date().nullable(),initiator:z26.object({userId:z26.string().nullable(),role:z26.string().nullable(),agentName:z26.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z26.object({resolutions:z26.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z26.object({mergeId:z26.string().uuid(),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedAt:z26.coerce.date(),lastEditedBy:z26.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z26.object({mergeId:z26.string().uuid(),resolutions:z26.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z26.object({mergeId:z26.string().uuid()}),PublishReleaseRequestSchema=z26.object({version:z26.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z26.string().max(2e4).optional()}),PublishReleaseResultSchema=z26.object({releaseTag:z26.string(),sha:z26.string(),publishedAt:z26.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z27}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=z27.object({surface:SurfaceNameSchema,key:z27.string(),label:z27.string()}),InlineSchema=z27.object({text:z27.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z27.discriminatedUnion("type",[z27.object({type:z27.literal("paragraph"),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("preview"),ref:DiffRefSchema,caption:z27.string().optional()}),z27.object({type:z27.literal("code"),code:z27.string(),lang:z27.string().optional(),caption:z27.string().optional()}),z27.object({type:z27.literal("risk"),level:z27.enum(["warning","error"]),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("list"),items:z27.array(z27.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z27.object({headline:z27.string(),blocks:z27.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z27.object({summary:EnvDiffSummarySchema,fingerprint:z27.string(),generatedAt:z27.coerce.date(),cached:z27.boolean().optional(),credits:z27.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z28}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=z28.object({date:z28.string(),visitors:z28.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z28.object({key:z28.string(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z28.object({path:z28.string(),pageName:z28.string().nullable().optional(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z28.object({preset:z28.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z28.string(),requestedTo:z28.string(),effectiveFrom:z28.string(),effectiveTo:z28.string(),isRetentionLimited:z28.boolean(),groupBy:z28.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z28.object({date:z28.string(),content:z28.string(),updatedAt:z28.string(),updatedByUserId:z28.string()}),ProjectPageviewAnalyticsDTOSchema=z28.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative(),bounceRate:z28.number().min(0).max(100),viewsPerVisit:z28.number().nonnegative(),averageVisitDurationSeconds:z28.number().nonnegative(),visitorsSeries:z28.array(ProjectDailyVisitorsDTOSchema),topPages:z28.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z28.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z29}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=z29.object({id:z29.string(),email:z29.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z29.coerce.date(),createdAt:z29.coerce.date(),inviterUserId:z29.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z29.object({id:z29.string(),token:z29.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z29.object({success:z29.boolean(),projectId:z29.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z30}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=z30.object({id:z30.string(),name:z30.string(),image:z30.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z30.object({count:z30.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z30.object({counts:z30.object({signed_up:z30.int(),activated:z30.int()}),credits:z30.object({total:z30.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z30.email(),emailVerified:z30.boolean(),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z31}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,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=z31.object({id:z31.string(),principalType:ProjectPrincipalTypeSchema,principalId:z31.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z31.coerce.date(),expiresAt:z31.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z31.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z31.record(z31.string(),z31.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z31.object({access:z31.array(ProjectAccessItemDTOSchema),invites:z31.array(ProjectInviteDTOSchema),organization:z31.object({name:z31.string().nullable(),logo:z31.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z31.object({success:z31.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z31.object({success:z31.boolean(),projectId:z31.uuid()}))}});import{z as z32}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=z32.object({publicationStatus:PublicationStatusSchema,appUrl:z32.string().nullable(),lastPublishedAt:z32.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z33}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewBootstrapDTOSchema,PreviewBootstrapDTO,PreviewBootstrapResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z33.object({url:z33.url(),expiresAt:z33.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewBootstrapDTOSchema=z33.discriminatedUnion("source",[z33.object({source:z33.literal("artifact"),artifact:SandboxSessionDTOSchema,dev:z33.null()}),z33.object({source:z33.literal("dev"),artifact:z33.null(),dev:SandboxSessionDTOSchema})]),PreviewBootstrapDTO=createDTO(PreviewBootstrapDTOSchema),PreviewBootstrapResponseSchema=createResponseSchema(PreviewBootstrapDTOSchema)}});import{z as z34}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:z34.string(),slug:z34.string().nullable(),logo:z34.string().nullable(),metadata:z34.record(z34.string(),z34.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z34.object({id:z34.string(),name:z34.string(),email:z34.email(),image:z34.string().nullable()}),OrganizationMemberDTOSchema=z34.object({id:z34.string(),userId:z34.string(),organizationId:z34.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z34.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z35}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,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=z35.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z35.object({reason:CancellationReasonCodeSchema,details:z35.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z35.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z35.object({included:z35.number().optional(),unitPrice:z35.number().optional(),dailyCap:z35.number().nullable().optional()}),EntitlementsDTOSchema=z35.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z35.object({retentionDays:z35.number().int().positive(),canUseExtendedDateRanges:z35.boolean()}).optional(),members:z35.object({canInvite:z35.boolean(),maxMembers:z35.number().int().positive().nullable()}).optional(),projects:z35.object({canCreatePrivateProjects:z35.boolean(),maxPrivateProjects:z35.number().int().positive().nullable()}).optional(),domains:z35.object({canUseCustomDomains:z35.boolean(),maxDomains:z35.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z35.object({id:z35.string(),external_id:z35.string(),customerId:z35.string(),planId:z35.string(),planCode:TemplateCodeSchema,currentPeriod:z35.object({start:z35.string(),end:z35.string().nullable()}),cancelAt:z35.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z35.string(),nextPaymentAt:z35.string().nullable(),baseAmount:z35.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z35.object({totalCap:z35.number(),dailyCap:z35.number(),usedTotal:z35.number()}),CreditBalanceDTOSchema=z35.object({total:z35.number(),base:z35.number(),dailyBase:z35.number(),purchases:z35.number(),awards:z35.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z35.object({total:z35.number(),nearLimit:z35.boolean(),canChat:z35.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z35.object({dailyFreeAvailable:z35.number(),monthlyAvailable:z35.number(),purchasedAvailable:z35.number(),awardedAvailable:z35.number()}),ProjectDailyCreditAllowanceDTOSchema=z35.object({periodCap:z35.number(),dailyGrant:z35.number(),usedThisPeriod:z35.number(),remainingThisPeriod:z35.number()}),ProjectCreditBalanceDTOSchema=z35.object({projectId:z35.uuid(),organizationId:z35.string(),balance:z35.object({totalAvailable:z35.number(),nearLimit:z35.boolean(),canUseAi:z35.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z35.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z35.object({invoiceId:z35.string(),newBalance:z35.int(),creditCount:z35.int(),amountUsd:z35.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z35.object({url:z35.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z36}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=z36.object({brand:z36.string(),last4:z36.string(),exp:z36.string(),isDefault:z36.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z37}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=z37.string().superRefine((path47,ctx)=>{let segments=path47.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=z37.object({type:z37.literal("renameField"),contentType:z37.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z37.object({enabled:z37.boolean()}).strict(),ContentTypeDTOSchema=z37.object({id:z37.string(),name:z37.string(),label:z37.string(),isSingleton:z37.boolean(),i18n:ContentTypeI18nSchema,fields:z37.record(z37.string(),FieldDefinitionSchema),createdAt:z37.string(),updatedAt:z37.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z37.object({contentTypes:z37.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z37.object({id:z37.string(),entryId:z37.string(),documentId:z37.string(),slug:z37.string(),locale:z37.string().optional(),createdAt:z37.string(),updatedAt:z37.string(),__fimo:z37.object({contentType:z37.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({limit:z37.number(),offset:z37.number(),total:z37.number(),hasMore:z37.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z37.object({contentType:z37.string(),count:z37.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z37.object({counts:z37.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z37.object({count:z37.number().int().nonnegative(),sourceLocale:z37.string(),targetLocale:z37.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z37.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z37.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z37.union([z37.string(),z37.number(),z37.boolean(),z37.null()]),entryWhereOperatorSchema=z37.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z37.array(entryWhereScalarSchema).optional(),$nin:z37.array(entryWhereScalarSchema).optional(),$contains:z37.string().optional(),$startsWith:z37.string().optional(),$null:z37.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z37.object({data:z37.record(z37.string(),z37.unknown()),locale:z37.string().min(1).optional(),documentId:z37.uuid().optional()}),entryIdsSchema=z37.array(z37.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z37.object({sql:z37.string().min(1)}),BulkCreateEntriesRequestSchema=z37.object({entries:z37.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z37.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z37.object({updates:z37.array(z37.object({id:z37.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,locale:z37.string().min(1).optional()}),z37.object({where:EntryWhereSchema,locale:z37.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z37.object({data:z37.array(z37.record(z37.string(),z37.unknown())),meta:z37.object({rowCount:z37.number().int().nonnegative(),truncated:z37.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({created:z37.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({updated:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({deleted:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z38}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z38.object({index:z38.number().int().nonnegative(),contentType:z38.string(),field:z38.string(),value:z38.string(),against:z38.enum(["stored","batch"]),ownerDocumentId:z38.uuid().optional(),ownerIndex:z38.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z38.object({code:z38.literal("unique_conflict"),message:z38.string(),conflicts:z38.array(UniqueConflictSchema),truncated:z38.boolean().optional()})}});import{z as z39}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=z39.object({kind:z39.literal("unique_conflict"),contentType:z39.string(),field:z39.string(),value:z39.string(),documentCount:z39.number().int().positive(),documentIds:z39.array(z39.uuid()),documentIdsTruncated:z39.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z39.object({code:z39.literal("schema_transition_rejected"),message:z39.string(),issues:z39.array(SchemaTransitionIssueSchema),truncated:z39.boolean().optional()})}});import{z as z40}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=z40.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z40.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z40.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z40.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z40.object({field:CmsFieldNameSchema,direction:z40.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z40.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z40.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z40.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z40.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z40.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z41}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=z41.object({id:z41.string(),name:z41.string()}),AssetDTOSchema=z41.object({id:z41.string(),name:z41.string(),type:AssetTypeSchema,originalFileName:z41.string().nullable(),parentId:z41.string().nullable(),mimeType:z41.string().nullable(),fileSize:z41.number().nullable(),url:z41.string().nullable(),storageKey:z41.string().nullable(),createdAt:z41.string(),updatedAt:z41.string(),altText:z41.string().nullable().optional(),caption:z41.string().nullable().optional(),aiCaption:z41.string().nullable().optional(),aiAltText:z41.string().nullable().optional(),aiTags:z41.array(z41.string()).nullable().optional(),aiPrimaryColor:z41.string().nullable().optional(),aiProcessingStatus:z41.string().nullable().optional(),width:z41.number().nullable().optional(),height:z41.number().nullable().optional(),path:z41.array(AssetPathItemSchema).optional(),hasChildren:z41.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z41.lazy(()=>z41.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z41.array(AssetDTOSchema))}});import{z as z42}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z42.object({key:z42.string(),value:z42.string().optional(),defaultValue:z42.string(),locale:z42.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z43}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=z43.object({id:z43.string(),name:z43.string(),type:z43.enum(["file","folder"]),path:z43.string(),children:z43.lazy(()=>z43.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z43.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z43.object({path:z43.string(),exists:z43.boolean(),type:z43.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z44}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z44.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z44.object({items:z44.array(ProjectMessagePublicDTOSchema),nextCursor:z44.string().nullable()}),ChatDeletionDTOSchema=z44.object({success:z44.boolean(),deletedCount:z44.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z45}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=z45.object({url:z45.string().url(),key:z45.string(),size:z45.number(),contentType:z45.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z46}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=z46.object({canAccess:z46.boolean(),permissions:z46.record(z46.string(),z46.boolean()),role:z46.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z47}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:z47.string().trim().default(""),sort:z47.enum(["recent","name","relevance"]).default("recent"),category:z47.string().optional(),visibility:z47.enum(["public","private"]).optional()})}});import{z as z48}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=z48.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z48.enum(["fimo","external"]),PaymentStatusSchema=z48.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z48.object({id:z48.string().uuid(),domain:z48.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z48.boolean(),price:z48.number().int().nullable(),renewalPrice:z48.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z48.string().nullable(),failureReason:z48.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z48.object({domain:z48.string(),available:z48.boolean(),premium:z48.boolean(),price:z48.number().nullable(),renewalPrice:z48.number().nullable(),purchaseType:z48.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z48.object({domain:z48.string(),price:z48.number().nullable(),renewalPrice:z48.number().nullable(),premium:z48.boolean(),allowedYears:z48.array(z48.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z48.object({firstName:z48.string().max(100),lastName:z48.string().max(100),companyName:z48.string().max(100).optional(),address1:z48.string().max(255),address2:z48.string().max(255).optional(),city:z48.string().max(100),state:z48.string().max(100),zip:z48.string().max(20),country:z48.string().max(2),phone:z48.string().max(30),email:z48.union([z48.string().email().max(255),z48.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z48.object({firstName:z48.string().min(1).max(100),lastName:z48.string().min(1).max(100),companyName:z48.string().max(100).optional(),address1:z48.string().min(1).max(255),address2:z48.string().max(255).optional(),city:z48.string().min(1).max(100),state:z48.string().min(1).max(100),zip:z48.string().min(1).max(20),country:z48.string().min(1).max(2),phone:z48.string().min(1).max(30),email:z48.string().email().max(255)}),SearchDomainsRequestSchema=z48.object({keyword:z48.string().min(1).max(100),tldFilter:z48.array(z48.string()).optional()}),CheckAvailabilityRequestSchema=z48.object({domains:z48.array(z48.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=z48.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z48.object({domain:DomainNameSchema,years:z48.number().int().min(1).max(10).optional().default(3),autoRenew:z48.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z48.object({autoRenew:z48.boolean().optional()}),RenewDomainRequestSchema=z48.object({years:z48.number().int().min(1).max(10).optional().default(1),autoRenew:z48.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z48.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z48.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z48.object({verified:z48.boolean(),email:z48.string().nullable(),verifyBy:z48.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z49}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=z49.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=z49.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=z49.object({txtName:z49.string().nullable().optional(),txtValue:z49.string().nullable().optional(),httpUrl:z49.string().nullable().optional(),httpBody:z49.string().nullable().optional(),cname:z49.string().nullable().optional(),cnameTarget:z49.string().nullable().optional()}),SSLValidationErrorSchema=z49.object({message:z49.string()}),OwnershipVerificationSchema=z49.object({type:z49.string(),name:z49.string(),value:z49.string()}),ProjectDomainSSLDTOSchema=z49.object({status:z49.string(),method:z49.string().nullable(),type:z49.string().nullable(),validationRecords:z49.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z49.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z49.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z49.enum(["subdomain","apex"]),RedirectConfigSchema=z49.object({type:z49.literal("apex_to_www"),linkedDomainId:z49.string()}).nullable().optional(),ProjectDomainDTOSchema=z49.object({id:z49.string(),hostname:z49.string(),status:z49.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z49.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z49.string(),scdCnameTarget:z49.string().optional(),apexTargets:z49.array(z49.string()),dnsAutoConfigured:z49.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z49.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z49.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z49.object({hostname:z49.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:z49.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z49.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z49.object({available:z49.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z49.object({success:z49.boolean(),hostname:z49.string()}))}});import{z as z50}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=z50.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z50.object({available:z50.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z50.object({slug:z50.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z50.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z50.object({subdomain:z50.string(),subdomainUpdatedAt:z50.coerce.date()})),SubdomainSuggestionsQuerySchema=z50.object({base:z50.string().max(100).optional(),max:z50.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z50.object({suggestions:z50.array(z50.string())}))}});import{z as z51}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=z51.object({translated:z51.number().int().nonnegative(),total:z51.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z51.object({locale:z51.string(),isDefault:z51.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z51.object({defaultLocale:z51.string(),routing:z51.object({strategy:z51.literal("path-prefix"),prefixDefaultLocale:z51.boolean()}),locales:z51.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z51.object({locale:z51.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z51.object({locale:z51.string().min(1).max(40)}),ProjectLocaleMutationSchema=z51.object({locale:z51.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z51.object({locale:z51.string(),entriesDeleted:z51.number().int().nonnegative(),labelsDeleted:z51.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z52}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=z52.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z52.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=z52.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z52.number(),credits:z52.number().optional(),billingMode:z52.enum(["fimo-credits","provider-account"]).optional(),confidence:z52.enum(["exact","estimated","metered"]),basis:z52.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z53}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=z53.object({options:z53.record(z53.string(),z53.unknown()),name:z53.string().optional(),parentId:z53.string().nullable().optional(),altText:z53.string().optional(),caption:z53.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z53.string().min(1).optional(),model:z53.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=z53.object({jobId:z53.string(),status:z53.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z53.string().nullable().optional(),credits:z53.number().optional(),costUsd:z53.number().optional(),billingMode:z53.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z53.object({error:z53.string(),code:z53.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:z53.array(GenerationTaskIdSchema).optional(),availableModels:z53.array(z53.string()).optional(),issues:z53.array(z53.unknown()).optional()})}});import{z as z54}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=z54.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z54.object({name:z54.string(),key:z54.string(),description:z54.string(),type:FlagTypeSchema,required:z54.boolean(),defaultValue:z54.unknown().optional(),enumValues:z54.array(z54.string()).optional(),isArray:z54.boolean()}),AssetModelPriceSchema=z54.object({unitPrice:z54.number(),unit:z54.string(),confidence:z54.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z54.object({id:z54.string(),shortName:z54.string(),provider:z54.string(),source:z54.string(),modality:z54.enum(["image","video","audio"]),tags:z54.array(z54.string()),displayName:z54.string(),description:z54.string(),flags:z54.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z54.object({model:z54.string(),costUsd:z54.number(),credits:z54.number(),billingMode:z54.enum(["fimo-credits","provider-account"]),confidence:z54.enum(["exact","estimated","metered"]),basis:z54.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z55}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=z55.object({tourId:z55.string(),version:z55.string(),status:z55.string(),completedAt:z55.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z55.array(UserTourDTOSchema))}});import{z as z56}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=z56.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z56.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z56.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z56.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z56.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z56.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z56.enum(["user","agent","system"]),SupportReportTagSchema=z56.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z56.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z56.object({organization:z56.object({id:z56.string().trim().min(1).max(255),name:z56.string().trim().max(240).optional()}),project:z56.object({id:z56.uuid(),name:z56.string().trim().max(240).optional(),createdAt:z56.coerce.date().optional()}).optional(),environment:z56.string().trim().max(255).optional(),clientVersion:z56.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z56.object({message:z56.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z56.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z56.string().trim().max(200).optional(),limit:z56.coerce.number().int().min(1).max(100).default(50),offset:z56.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z56.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z56.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z56.uuid().nullable().optional(),note:z56.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=z56.object({message:z56.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z56.object({kind:SupportReportLinkKindSchema,label:z56.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z56.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z56.object({kind:SupportReportActorKindSchema,id:z56.string().nullable(),name:z56.string().nullable()}),SupportReportLinkDTOSchema=z56.object({id:z56.uuid(),kind:SupportReportLinkKindSchema,label:z56.string(),url:SupportReportHttpUrlSchema,externalId:z56.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z56.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z56.object({id:z56.uuid(),kind:SupportReportEventKindSchema,body:z56.string().nullable(),metadata:z56.record(z56.string(),z56.unknown()),actor:SupportReportActorDTOSchema,createdAt:z56.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z56.object({id:z56.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z56.array(z56.string()),source:SupportReportSourceSchema,message:z56.string(),reporter:z56.object({id:z56.string().nullable(),name:z56.string().nullable(),email:z56.string().nullable()}),organization:z56.object({id:z56.string().nullable(),name:z56.string()}),project:z56.object({id:z56.uuid().nullable(),name:z56.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z56.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z56.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z56.string().nullable(),deliveredAt:z56.coerce.date().nullable()}).nullable(),duplicateOfReportId:z56.uuid().nullable(),resolvedAt:z56.coerce.date().nullable(),createdAt:z56.coerce.date(),updatedAt:z56.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z56.string().nullable(),clientVersion:z56.string().nullable(),links:z56.array(SupportReportLinkDTOSchema),events:z56.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z56.object({reports:z56.array(SupportReportSummaryDTOSchema),total:z56.number().int().nonnegative(),statusCounts:z56.object({new:z56.number().int().nonnegative(),in_progress:z56.number().int().nonnegative(),waiting:z56.number().int().nonnegative(),resolved:z56.number().int().nonnegative(),duplicate:z56.number().int().nonnegative(),irrelevant:z56.number().int().nonnegative(),ignored:z56.number().int().nonnegative()}),limit:z56.number().int().positive(),offset:z56.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z56.object({id:z56.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z56.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z57}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=z57.iso.datetime({offset:!0}).pipe(z57.coerce.date()),OpsRecentChatInputSchema=z57.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z57.string().trim().min(1).max(255).optional(),limit:z57.coerce.number().int().min(1).max(200).default(100),cursor:z57.string().trim().min(1).max(2e3).optional(),slim:z57.boolean().default(!0),reason:z57.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=z57.object({id:z57.string(),messageId:z57.string(),env:z57.string(),versionId:z57.string().nullable(),userId:z57.string().nullable(),role:z57.string(),parts:z57.array(z57.record(z57.string(),z57.unknown())),metadata:z57.object({status:z57.string().optional(),traceUrl:z57.string().optional(),externalFileChanges:z57.array(z57.unknown()).optional()}),stats:z57.object({toolCount:z57.number().int().nonnegative(),failedToolCount:z57.number().int().nonnegative()}),createdAt:z57.iso.datetime({offset:!0}),project:z57.object({id:z57.string(),name:z57.string(),displayName:z57.string().nullable(),organizationId:z57.string().nullable()})}),OpsRecentChatResponseSchema=z57.object({target:z57.object({backendProfile:OpsBackendProfileSchema,projectEnv:z57.string().nullable()}),window:z57.object({from:z57.iso.datetime({offset:!0}),to:z57.iso.datetime({offset:!0})}),messages:z57.object({items:z57.array(OpsRecentChatMessageSchema),nextCursor:z57.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z58}from"zod";function createAgentRunWebhookEventDataSchema(status){return z58.object({run:z58.object({id:z58.string(),agentName:z58.string(),trigger:z58.string(),status:z58.literal(status),startedAt:z58.string().nullable(),finishedAt:z58.string().nullable(),reason:z58.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,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_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=z58.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z58.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z58.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z58.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z58.union([z58.literal(0),z58.literal(5),z58.literal(30),z58.literal(60)]),EntryChangedWebhookEventDataSchema=z58.object({reason:WebhookEntryChangeReasonSchema,operationId:z58.string().optional(),batch:z58.object({index:z58.number().int().positive(),total:z58.number().int().positive()}).optional(),changes:z58.array(z58.object({action:WebhookEntryChangeActionSchema,contentType:z58.string(),id:z58.string(),documentId:z58.string(),locale:z58.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z58.object({form:z58.object({id:z58.string(),label:z58.string()}),submission:z58.object({id:z58.string(),data:z58.record(z58.string(),z58.unknown()),submittedAt:z58.string()})}),PublishStartedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("publishing"),startedAt:z58.string()})}),PublishSucceededWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("published"),url:z58.string(),publishedAt:z58.string(),firstPublish:z58.boolean()})}),PublishFailedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("failed"),reason:z58.string()})}),PublishUnpublishedWebhookEventDataSchema=z58.object({publication:z58.object({previousUrl:z58.string(),unpublishedAt:z58.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),classification:z58.string(),summary:z58.string(),reasons:z58.array(z58.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),resolution:z58.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z58.object({report:z58.object({weekStart:z58.string(),weekEnd:z58.string(),pageviews:z58.number(),visitors:z58.number(),previousPageviews:z58.number(),previousVisitors:z58.number()})}),MediaAssetWebhookEventDataSchema=z58.object({id:z58.string().nullable(),name:z58.string().nullable(),type:z58.string(),mimeType:z58.string().nullable(),fileSize:z58.number().nullable()}),MediaUploadedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["updated","moved","analysis"]),analysis:z58.object({category:z58.string(),status:z58.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("generated"),generation:z58.object({model:z58.string(),mode:z58.string()})}),MediaProcessingFailedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["analysis","generation"]),failure:z58.object({code:z58.string()})}),DomainCreatedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string()})}),LabelChangedWebhookEventDataSchema=z58.object({changes:z58.array(z58.object({action:z58.enum(["created","updated","deleted"]),key:z58.string(),locale:z58.string(),value:z58.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),isDefault:z58.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),previousCode:z58.string()})}),LocaleDeletedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z58.object({merge:z58.object({id:z58.string(),from:EnvSchema,to:EnvSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema}),version:z58.object({id:z58.string(),name:z58.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=z58.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z58.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z58.discriminatedUnion("source",[z58.object({source:z58.literal("literal"),value:z58.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z58.object({source:z58.literal("secret"),key:z58.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z58.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z58.object({name:z58.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z58.object({name:z58.string(),source:z58.enum(["literal","secret"]),secretKey:z58.string().nullable(),secretPrefix:z58.string().nullable(),configured:z58.literal(!0)}),WebhookFilterSchema=z58.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z58.string().min(1).max(255).optional(),agentName:z58.string().min(1).max(120).optional(),mediaType:z58.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z58.string().min(1).max(255).optional(),locale:z58.string().min(1).max(120).optional()}),JsonValueSchema=z58.lazy(()=>z58.union([z58.string(),z58.number(),z58.boolean(),z58.null(),z58.array(JsonValueSchema),z58.record(z58.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z58.url(),enabled:z58.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z58.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z58.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z58.url().optional(),enabled:z58.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z58.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z58.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z58.object({eventType:WebhookEventTypeSchema.optional(),data:z58.record(z58.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z58.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z58.uuid(),name:z58.string(),eventType:WebhookEventTypeSchema,enabled:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z58.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z58.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z58.coerce.date().nullable(),deliveryStats24h:z58.object({succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z58.uuid(),projectId:z58.uuid(),env:EnvSchema,eventId:z58.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z58.number().int().positive(),test:z58.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z58.number().int().nonnegative(),responseStatus:z58.number().int().nullable(),lastErrorCode:z58.string().nullable(),lastErrorMessage:z58.string().nullable(),payloadAvailable:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z58.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z58.string().nullable(),qstashMessageId:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z58.object({items:z58.array(WebhookDeliveryDTOSchema),pagination:z58.object({page:z58.number().int().positive(),limit:z58.number().int().positive(),total:z58.number().int().nonnegative(),totalPages:z58.number().int().positive(),hasMore:z58.boolean()}),stats:z58.object({total:z58.number().int().nonnegative(),succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z58.object({id:z58.uuid(),deliveryId:z58.uuid(),attempt:z58.number().int().positive(),status:z58.enum(["delivering","succeeded","failed"]),responseStatus:z58.number().int().nullable(),durationMs:z58.number().int().nonnegative(),responseExcerpt:z58.string().nullable(),errorCode:z58.string().nullable(),errorMessage:z58.string().nullable(),createdAt:z58.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z58.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z58.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z59}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=z59.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z59.object({total:z59.number(),base:z59.number(),purchases:z59.number(),awards:z59.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z59.object({id:z59.string(),name:z59.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z59.object({type:z59.string(),brand:z59.string().nullable(),last4:z59.string().nullable(),expirationDate:z59.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z59.object({currency:z59.string(),nextPaymentAmount:z59.number().nullable(),nextPaymentAt:z59.string().nullable(),billingInterval:z59.string().nullable(),totalAmount:z59.number().nullable(),discountAmount:z59.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z59.object({id:z59.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z59.string().nullable(),currentPeriodEndsAt:z59.string().nullable(),renewsAt:z59.string().nullable(),cancelAt:z59.string().nullable(),renewAutomatically:z59.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z59.object({type:z59.enum(["low_balance","critical_balance","approaching_limit"]),message:z59.string(),estimatedPromptsRemaining:z59.number().nullable(),avgCostPerPrompt:z59.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z59.object({monthlyCredits:z59.number().nullable(),usedThisPeriod:z59.number(),remainingThisPeriod:z59.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z59.object({organizationId:z59.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z59.string().nullable(),tenureDays:z59.number().int().nonnegative(),capturedAt:z59.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z59.object({hasSubscription:z59.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z59.number().nullable(),alerts:z59.array(CreditAlertDTOSchema),portalUrl:z59.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z59.object({creditCount:z59.number().int().positive(),expiresAt:z59.string().datetime().nullable().optional(),message:z59.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("free"),amountCents:z59.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("purchase"),amountCents:z59.number().int().positive()}),CreditTopupRequestDTOSchema=z59.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z59.object({success:z59.boolean(),transactionId:z59.string().nullable(),newBalance:z59.number(),creditCount:z59.number(),type:z59.enum(["free","purchase"]),invoiceId:z59.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z60}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=z60.object({totalCredits:z60.number(),totalCostUsd:z60.number(),totalMessages:z60.number(),avgCostPerMessage:z60.number(),periodStart:z60.string().nullable(),periodEnd:z60.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z60.object({date:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z60.array(UsageByUserForProjectDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z60.object({summary:UsageSummaryDTOSchema,byProject:z60.array(UsageByProjectDTOSchema),byUser:z60.array(UsageByUserDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z61}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=z61.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z61.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z61.object({startDate:z61.string().optional(),endDate:z61.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z61.coerce.number().int().positive().default(1),limit:z61.coerce.number().int().positive().max(100).default(20),sortBy:z61.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z61.string().optional()}),UsageOverviewSummaryDTOSchema=z61.object({totalCredits:z61.number(),totalCostUsd:z61.number(),totalMessages:z61.number(),avgCostPerMessage:z61.number(),avgCreditsPerMessage:z61.number(),periodStart:z61.string(),periodEnd:z61.string(),creditsChange:z61.number().nullable(),costChange:z61.number().nullable(),messagesChange:z61.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z61.object({date:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z61.object({organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number(),projectCount:z61.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z61.object({userId:z61.string(),userName:z61.string().nullable(),userEmail:z61.string().nullable(),userImage:z61.string().nullable(),organizationId:z61.string().nullable(),organizationName:z61.string().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),projectCount:z61.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z61.object({projectId:z61.string(),projectName:z61.string(),projectDisplayName:z61.string().nullable(),organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z61.object({id:z61.string(),name:z61.string(),value:z61.number(),percentage:z61.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z61.object({day:z61.number(),hour:z61.number(),value:z61.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z61.object({summary:UsageOverviewSummaryDTOSchema,timeline:z61.array(UsageTimelinePointDTOSchema),topOrganizations:z61.array(OrganizationUsageRowDTOSchema),topUsers:z61.array(UserUsageRowDTOSchema),topProjects:z61.array(ProjectUsageRowDTOSchema),creditDistribution:z61.array(UsageDistributionItemDTOSchema),heatmap:z61.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z61.object({page:z61.number(),limit:z61.number(),totalItems:z61.number(),totalPages:z61.number(),hasMore:z61.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z61.object({organizations:z61.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z61.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z61.object({users:z61.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z61.object({projects:z61.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z61.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z61.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z61.object({credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),createdAt:z61.string(),memberCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z61.object({id:z61.string(),name:z61.string().nullable(),email:z61.string(),image:z61.string().nullable(),createdAt:z61.string(),organizationCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),displayName:z61.string().nullable(),createdAt:z61.string(),organizationId:z61.string(),organizationName:z61.string(),ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z62}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=z62.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z62.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z62.object({command:z62.string().min(1).max(1e4),cwd:z62.string().optional(),projectEnv:EnvSchema.optional(),env:z62.record(z62.string(),z62.string()).optional(),name:z62.string().optional(),waitForCompletion:z62.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z62.object({identifier:z62.string(),status:SandboxProcessStatusSchema,command:z62.string().optional(),startedAt:z62.string().optional(),exitCode:z62.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z62.object({processes:z62.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z62.object({processId:z62.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z62.object({success:z62.boolean(),message:z62.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z63}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_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_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_webhook_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit(["rev-parse","--abbrev-ref","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveEnvFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{env:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||branch==="HEAD"||!isValidEnv(branch)?null:{env:branch,source:"branch"}}catch{return null}}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let env,source,readOnly=!1;if(opts.envOverride!==void 0){if(!isValidEnv(opts.envOverride))throw new InvalidEnvOverrideError(opts.envOverride);env=opts.envOverride,source="flag"}else{let fromGit=await resolveEnvFromGit(cwd);if(fromGit)env=fromGit.env,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{if(opts.requireBranch)throw await isGitRepo(cwd)?new GitBranchUndetectedError:new NotInProjectError;env=DEFAULT_ENV,source="fallback"}}if(opts.api&&env!=="prod")try{let names=(await opts.api.listEnvs(settings.projectId)).map(e=>e.env);if(!names.includes(env)&&source==="flag")throw new EnvNotFoundError(env,names)}catch(err){if(err instanceof EnvNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,env,source,readOnly:readOnly||void 0}}function envSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--env":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"default",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 env: ${ctx.env} (from ${sourceHint}${ro})`}function envOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let env=cur.opts().env;if(typeof env=="string"&&env.length>0)return env;cur=cur.parent??null}}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let envOverride2=envOverrideFromCommand(cmd),baseApi=new FimoApiClient(loadConfig()),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2,requireBranch:bootstrapOpts.requireBranch,api:baseApi});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${envSourceBanner(ctx)}
|
|
195
|
+
${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}return selected.has("windsurf")&&writeIfMissing(".windsurfrules",agentsMdContent),selected.has("gemini-cli")&&writeIfMissing("GEMINI.md",agentsMdContent),result}function syncPerAgentVariants(targetDir,agents){let agentsMdPath=path9.join(targetDir,"AGENTS.md");if(!fs9.existsSync(agentsMdPath))throw new Error(`No AGENTS.md found in ${targetDir}. Run \`fimo create\` first, or create AGENTS.md manually before running \`fimo rules sync\`.`);let agentsMdContent=fs9.readFileSync(agentsMdPath,"utf8");return writePerAgentVariants(targetDir,agents,agentsMdContent)}function detectAgentsInProject(cwd){let detected=[];return fs9.existsSync(path9.join(cwd,"CLAUDE.md"))&&detected.push("claude-code"),fs9.existsSync(path9.join(cwd,".cursor","rules","fimo.mdc"))&&detected.push("cursor"),fs9.existsSync(path9.join(cwd,".windsurfrules"))&&detected.push("windsurf"),fs9.existsSync(path9.join(cwd,"GEMINI.md"))&&detected.push("gemini-cli"),detected}var TEMPLATE_ROOT,AGENT_TEMPLATES_ROOT,EXCLUDED_DIRS,init_scaffold=__esm({"src/cli/utils/scaffold.ts"(){init_templates();init_config();init_templates();TEMPLATE_ROOT=getTemplatePath("react-router"),AGENT_TEMPLATES_ROOT=path9.resolve(CLI_ROOT,"assets","agent-templates"),EXCLUDED_DIRS=new Set(["node_modules","dist","build",".turbo",".git"]);__name(resolveTemplateRoot,"resolveTemplateRoot");__name(resolveAgentTemplatesRoot,"resolveAgentTemplatesRoot");__name(resolveAgentTemplate,"resolveAgentTemplate");__name(listAgentTemplates,"listAgentTemplates");__name(copyAgentTemplate,"copyAgentTemplate");__name(copyTemplate,"copyTemplate");__name(pinFimoDependency,"pinFimoDependency");__name(copyTree,"copyTree");__name(writePerAgentVariants,"writePerAgentVariants");__name(syncPerAgentVariants,"syncPerAgentVariants");__name(detectAgentsInProject,"detectAgentsInProject")}});import{z as z5}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z5.ZodOptional||schema instanceof z5.ZodNullable||schema instanceof z5.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z5.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z5.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 z5.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z5.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],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z5.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 z5.ZodObject)return createObjectDTO(schema);if(schema instanceof z5.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 z6}from"zod";function createCursorPageDataSchema(dataSchema){return z6.object({items:z6.array(dataSchema),nextCursor:z6.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z6.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z6.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z7}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z7.object({page:z7.coerce.number().int().positive().default(1),limit:z7.coerce.number().int().positive().max(100).default(20)})}});import{z as z8}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectVisibilitySchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,RESERVED_CONTENT_FIELD_NAMES,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:z8.coerce.date(),positiveInt:z8.number().int().positive(),nonNegativeInt:z8.number().int().nonnegative()},BaseEntitySchema=z8.object({id:z8.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z8.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z8.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z8.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z8.enum(["public","private"]),ProjectStatusSchema=z8.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z8.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z8.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z8.enum(["owner","admin","member"]),AssetTypeSchema=z8.enum(["file","folder"]),TemplateCodeSchema=z8.enum(["Free","Premium"]),FieldTypeSchema=z8.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],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_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],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_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]))}});import{z as z9}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function isProductionEnv(env){return env===PRODUCTION_ENV}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");EnvSchema=z9.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")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z10}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=z10.preprocess(referenceValuePreprocess,z10.object({documentId:z10.uuid()})),ReferenceInputValueSchema=z10.preprocess(referenceValuePreprocess,z10.union([z10.object({documentId:z10.uuid()}),z10.object({slug:z10.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=z10.preprocess(polymorphicReferenceValuePreprocess,z10.object({contentType:z10.string().min(1),documentId:z10.uuid()})),PolymorphicReferenceInputValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.union([z10.object({contentType:z10.string().min(1),documentId:z10.uuid()}),z10.object({contentType:z10.string().min(1),slug:z10.string().min(1)})]))}});import{z as z11}from"zod";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,path47){let conditionPath=[...path47,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,path47)=>{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,path47));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path47,fieldName,variant.uid]);else walk(field.schema.fields,[...path47,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path47,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path47,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,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"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=3,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z11.union([z11.object({field:z11.string().min(1),equals:z11.union([z11.string(),z11.number(),z11.boolean()])}).strict(),z11.object({field:z11.string().min(1),in:z11.array(z11.union([z11.string(),z11.number(),z11.boolean()])).min(1)}).strict()]),commonFieldShape={label:z11.string().min(1).optional(),description:z11.string().optional(),editable:z11.boolean().optional(),required:z11.boolean().optional(),default:z11.unknown().optional(),showIf:z11.union([showIfClauseSchema,z11.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z11.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=z11.object({...commonFieldShape,type:z11.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z11.number().optional(),max:z11.number().optional(),minLength:z11.number().int().nonnegative().optional(),maxLength:z11.number().int().nonnegative().optional(),regex:z11.string().optional(),multiple:z11.boolean().optional(),allowedMimeTypes:z11.array(z11.string()).optional(),options:z11.array(z11.string().min(1)).min(1).optional(),unique:z11.boolean().optional(),i18n:z11.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!=="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=z11.object({...commonFieldShape,type:z11.literal("reference"),target:z11.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z11.array(z11.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z11.boolean().optional(),i18n:z11.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=z11.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z11.record(z11.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=z11.object({uid:z11.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z11.string().min(1),description:z11.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z11.object({fields:blockFieldsSchema}).strict(),blocksSchema=z11.object({oneOf:z11.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=z11.object({...commonFieldShape,type:z11.literal("blocks"),min:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z11.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=z11.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z12}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","cutover_step","agent_delegate","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send"],AuditActionSchema=z12.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z12.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z12.enum(AUDIT_ACTOR_KINDS)}});import{z as z13}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,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers: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=z13.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","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:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers: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=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.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=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.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=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.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=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)})}});import{z as z14}from"zod";var ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,QuestionAnswerMetadataSchema,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_common();init_create_dto();init_response();ProjectDTOSchema=BaseEntitySchema.extend({name:z14.string(),displayName:z14.string().nullable(),subdomain:z14.string().nullable().optional(),subdomainUpdatedAt:z14.date().nullable().optional(),organizationId:z14.string().nullable(),createdBy:z14.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z14.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z14.string(),thumbnailUrl:z14.string().nullable(),publishedThumbnailUrl:z14.string().nullable(),category:z14.string().nullable(),appUrl:z14.string().nullable(),lastPublishedAt:z14.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z14.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z14.object({id:z14.uuid(),name:z14.string(),displayName:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),visibility:ProjectVisibilitySchema,category:z14.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z14.object({id:z14.string(),name:z14.string(),avatar:z14.string().nullable(),color:z14.object({bg:z14.string(),text:z14.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z14.object({path:z14.string(),content:z14.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z14.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z14.object({id:z14.string(),messageId:z14.string(),versionId:z14.string().nullable(),role:ProjectChatMessageRole,parts:z14.array(z14.any()),createdAt:z14.coerce.date()}),MessageUserMetadataSchema=z14.object({id:z14.string(),name:z14.string().nullable().optional(),image:z14.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z14.object({shortTitle:z14.string().optional(),questions:z14.array(z14.object({header:z14.string(),question:z14.string(),answer:z14.string(),selectedLabels:z14.array(z14.string()),freeText:z14.string(),skipped:z14.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z14.number(),metadata:z14.object({user:MessageUserMetadataSchema,changeManifest:z14.array(z14.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z14.object({versionId:z14.uuid(),commitHash:z14.string(),name:z14.string(),description:z14.string().nullable(),kind:z14.enum(["manual","agent","restore-safety","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z14.object({versionCount:z14.number().int().nonnegative(),snapshotBytes:z14.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z14.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z14.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z14.object({content:z14.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z14.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z14.object({success:z14.boolean(),message:z14.string().optional(),warning:z14.string().optional(),durationMs:z14.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z14.object({isPublished:z14.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z14.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z14.object({success:z14.boolean(),message:z14.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z15}from"zod";var ProjectEnvStatusSchema,ProjectEnvDTOSchema,ProjectEnvDTO,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_create_dto();init_response();ProjectEnvStatusSchema=z15.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z15.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z15.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z15.string().nullable(),deletedAt:z15.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z15.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z15.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z15.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z15.object({surface:z15.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z15.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z15.number().int().nonnegative(),conflictCount:z15.number().int().nonnegative()}),EnvDiffResultSchema=z15.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z15.coerce.date(),surfaces:z15.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z16}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=z16.object({success:z16.literal(!0),downloadUrl:z16.string(),expiresAt:z16.string(),fileSize:z16.number(),duration:z16.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z16.object({success:z16.literal(!0),projectId:z16.string(),projectName:z16.string(),displayName:z16.string(),projectUrl:z16.string(),duration:z16.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z16.object({contentTypes:z16.number(),entries:z16.number(),assets:z16.number(),translations:z16.number(),forms:z16.number(),codeFiles:z16.number(),assetFiles:z16.number()}),ImportPreviewSurfaceDTOSchema=z16.object({name:z16.string(),included:z16.boolean(),count:z16.number().optional(),note:z16.string().optional()}),ImportPreviewDTOSchema=z16.object({projectName:z16.string(),displayName:z16.string().nullable(),visibility:z16.string().nullable(),category:z16.string().nullable(),exportedAt:z16.string(),version:z16.string(),envScope:z16.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z16.array(ImportPreviewSurfaceDTOSchema),fileSize:z16.number(),fileName:z16.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z16.object({success:z16.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z17}from"zod";var TriggerKindSchema,ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2,TriggerSchema2,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z17.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z17.object({type:z17.literal("manual")}),ScheduleTriggerSchema=z17.object({type:z17.literal("schedule"),cron:z17.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:z17.string().optional()}),WebhookTriggerSchema2=z17.object({type:z17.literal("webhook"),path:z17.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z17.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z18}from"zod";var ActivateRequestSchema,DeactivateRequestSchema,AgentActivationDTOSchema,AgentActivationDTO,AgentActivationsListResponseSchema,AgentActivationResponseSchema,WebhookPathTakenErrorSchema,ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_activation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-activation.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();ActivateRequestSchema=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z18.object({projectId:z18.uuid(),env:EnvSchema,agentName:z18.string().min(1),triggerIndex:z18.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema2,enabled:z18.boolean(),lastFiredAt:z18.coerce.date().nullable(),webhookPath:z18.string().nullable(),createdAt:z18.coerce.date(),updatedAt:z18.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z18.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z18.object({error:z18.literal("webhook_path_taken"),conflictAgent:z18.string(),path:z18.string()}),ManualRunRequestSchema=z18.object({args:z18.unknown().optional(),requestId:z18.string().min(1).max(128).optional()}),DispatchSkippedSchema=z18.object({skipped:z18.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z18.object({sessionId:z18.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z18.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});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,AgentListItemActivationSchema,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()}),AgentListItemActivationSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z20.string().min(1),active:z20.boolean()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),activations:z20.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,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();AgentSessionStatusSchema=z21.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z21.object({cpuMs:z21.number().nonnegative().default(0),netBytes:z21.number().nonnegative().default(0),walltimeMs:z21.number().nonnegative().default(0),llmTokensIn:z21.number().nonnegative().optional(),llmTokensOut:z21.number().nonnegative().optional()}),AgentSessionDTOSchema=z21.object({id:z21.uuid(),projectId:z21.uuid(),env:EnvSchema,agentName:z21.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z21.unknown().optional(),capabilities:z21.array(z21.string()).optional(),dataSources:z21.array(z21.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z21.string().nullable(),startedAt:z21.coerce.date().nullable(),finishedAt:z21.coerce.date().nullable(),cancelledAt:z21.coerce.date().nullable(),costUsd:z21.number().nonnegative(),costCeilingUsd:z21.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z21.boolean(),lastCheckpointId:z21.uuid().nullable(),branchEnvId:z21.uuid().nullable(),parentSessionId:z21.uuid().nullable(),terminalReason:z21.string().nullable(),errorMessage:z21.string().nullable(),report:z21.string().nullable(),createdAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z21.object({id:z21.uuid(),sessionId:z21.uuid(),checkpointIdx:z21.number().int().nonnegative(),payloadRef:z21.string(),payloadSizeBytes:z21.number().int().nonnegative(),checksum:z21.string().length(64),createdAt:z21.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z21.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z21.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z21.object({session:AgentSessionDTOSchema,checkpoints:z21.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z21.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z21.object({reason:z21.string().min(1).max(120).optional()})}});import{z as z22}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=z22.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z22.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z22.object({id:z22.uuid(),envId:z22.uuid(),sessionId:z22.uuid().nullable(),skillName:z22.string().min(1),classification:AgentBranchClassificationSchema,rationale:z22.string().nullable(),summary:z22.string().nullable(),surfaceDeltas:z22.record(z22.string(),z22.unknown()),createdAt:z22.coerce.date(),decidedAt:z22.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z22.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z22.object({path:z22.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z22.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z22.object({code:z22.literal("merge_conflict"),message:z22.string(),conflicts:z22.record(z22.string(),z22.number().int().nonnegative())})}});import{z as z23}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,BindProjectChannelRequestSchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolOptionsSchema,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,ProjectChannelBindingResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z23.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z23.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z23.enum(["secret_text"]),IntegrationCredentialUsageSchema=z23.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z23.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z23.object({mode:IntegrationAuthModeSchema,label:z23.string().min(1),description:z23.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z23.object({id:z23.string().min(1),label:z23.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z23.boolean()}),IntegrationToolDefinitionDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),description:z23.string().min(1)}),IntegrationRecipeDTOSchema=z23.object({title:z23.string().min(1),description:z23.string().min(1),command:z23.string().min(1).optional()}),IntegrationInfoDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),summary:z23.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z23.array(IntegrationAuthModeDTOSchema),credentials:z23.array(IntegrationCredentialDefinitionDTOSchema),tools:z23.array(IntegrationToolDefinitionDTOSchema),recipes:z23.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),installed:z23.boolean(),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z23.string().nullable(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),installedAt:z23.coerce.date().nullable(),updatedAt:z23.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z23.string(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z23.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z23.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z23.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z23.object({value:z23.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z23.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z23.object({id:z23.uuid(),organizationId:z23.string().min(1),integrationKey:z23.string().min(1),alias:z23.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z23.string().min(1),externalAccountName:z23.string().nullable(),externalBotUserId:z23.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z23.array(z23.string()),connectedAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z23.object({alias:z23.string().min(1).max(120).optional(),token:z23.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z23.object({integrationKey:z23.string().min(1),connectUrl:z23.string().url(),expiresAt:z23.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z23.object({ref:z23.string().min(1),connectionAlias:z23.string().min(1).optional(),agentName:z23.string().min(1).max(160).nullable().optional(),force:z23.boolean().optional()}),ProjectChannelBindingDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),connectionId:z23.uuid(),externalWorkspaceId:z23.string().min(1),externalChannelId:z23.string().min(1),externalChannelName:z23.string().nullable(),agentName:z23.string().nullable(),enabled:z23.boolean(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z23.object({markdown:z23.boolean().optional(),summary:z23.boolean().optional(),links:z23.boolean().optional(),images:z23.boolean().optional(),html:z23.union([z23.literal("cleaned"),z23.literal("raw"),z23.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z23.object({url:z23.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z23.object({query:z23.string().min(1),maxResults:z23.number().int().positive().max(20).optional(),sources:z23.array(z23.enum(["web","news","images"])).min(1).max(3).optional(),categories:z23.array(z23.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z23.enum(["hour","day","week","month","year"]).optional(),location:z23.string().min(1).max(160).optional(),country:z23.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z23.object({url:z23.string().url(),search:z23.string().min(1).optional(),limit:z23.number().int().positive().max(200).optional(),includeSubdomains:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z23.object({url:z23.string().url(),limit:z23.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z23.object({text:z23.string().min(1).max(200).optional(),cron:z23.string().min(1).max(120).optional(),timezone:z23.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z23.object({type:z23.enum(["scrape","crawl"]).default("scrape"),urls:z23.array(z23.string().url()).min(1).max(50),scrapeOptions:z23.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z23.object({name:z23.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z23.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z23.string().min(1).max(2e3).optional(),judgeEnabled:z23.boolean().optional(),retentionDays:z23.number().int().min(1).max(365).optional(),notification:z23.object({email:z23.object({enabled:z23.boolean().default(!0),recipients:z23.array(z23.string().email()).min(1).max(20),includeDiffs:z23.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z23.object({monitorId:z23.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z23.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z23.object({connectionAlias:z23.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z23.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.list"),input:z23.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z23.object({provider:z23.string().min(1),providerCredits:z23.number().nonnegative().optional(),providerCostUsd:z23.number().nonnegative().optional(),requests:z23.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z23.object({credits:z23.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()}),FirecrawlSearchToolOutputSchema=z23.object({query:z23.string(),provider:z23.literal("firecrawl"),warning:z23.string().optional(),results:z23.array(z23.object({title:z23.string(),url:z23.string(),snippet:z23.string().optional(),content:z23.string().optional(),score:z23.number().optional(),publishedAt:z23.string().optional()}))}),FirecrawlMapToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),count:z23.number(),links:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),description:z23.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),total:z23.number(),pages:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()})),warning:z23.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z23.object({cron:z23.string().optional(),text:z23.string().optional(),timezone:z23.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z23.object({id:z23.string().optional(),urls:z23.array(z23.string()).optional(),scrapeOptions:z23.record(z23.string(),z23.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z23.object({id:z23.string(),name:z23.string(),status:z23.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z23.string().nullable().optional(),lastRunAt:z23.string().nullable().optional(),currentCheckId:z23.string().nullable().optional(),targets:z23.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z23.string().nullable().optional(),judgeEnabled:z23.boolean().optional(),estimatedCreditsPerMonth:z23.number().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z23.object({id:z23.string(),monitorId:z23.string(),scheduledFor:z23.string().nullable().optional(),startedAt:z23.string().nullable().optional(),finishedAt:z23.string().nullable().optional(),estimatedCredits:z23.number().optional(),reservedCredits:z23.number().optional(),actualCredits:z23.number().optional(),billingStatus:z23.string().nullable().optional(),summary:z23.object({totalPages:z23.number().optional(),same:z23.number().optional(),changed:z23.number().optional(),new:z23.number().optional(),removed:z23.number().optional(),error:z23.number().optional()}).passthrough().optional(),error:z23.string().nullable().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitors:z23.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),deleted:z23.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),checks:z23.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),check:FirecrawlMonitorCheckOutputSchema,next:z23.string().optional()}),FirecrawlToolKeySchema=z23.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z23.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z23.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z23.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z23.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z23.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema)}});import{z as z24}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,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_create_dto();init_response();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set(["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES","FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME","VITE_API_URL","VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"]),ProjectSecretKeySchema=z24.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=z24.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z24.uuid(),env:z24.string().min(1),name:z24.string().min(1),cron:z24.string().min(1),command:z24.string().min(1),secretKeys:z24.array(z24.string().min(1)),enabled:z24.boolean(),lastRunAt:z24.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z24.string().nullable()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z24.object({name:z24.string().min(1).max(120),cron:z24.string().min(1).max(120),command:z24.string().min(1).max(500),secretKeys:z24.array(ProjectSecretKeySchema).default([])}),UpdateProjectScheduleRequestSchema=z24.object({name:z24.string().min(1).max(120).optional(),cron:z24.string().min(1).max(120).optional(),command:z24.string().min(1).max(500).optional(),secretKeys:z24.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z24.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z24.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z24.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z24.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z24.object({maxRuns:z24.number().int().positive(),retentionDays:z24.number().int().positive().nullable(),outputRetentionDays:z24.number().int().positive(),maxOutputBytes:z24.number().int().positive()}),ProjectScheduleUsageSchema=z24.object({runCount:z24.number().int().nonnegative(),runsWithOutput:z24.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z24.object({id:z24.uuid(),scheduleId:z24.uuid(),projectId:z24.uuid(),env:z24.string().min(1),scheduleName:z24.string().min(1),command:z24.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z24.object({id:z24.string().min(1),name:z24.string().min(1)}).nullable(),queuedAt:z24.coerce.date(),startedAt:z24.coerce.date().nullable(),finishedAt:z24.coerce.date().nullable(),exitCode:z24.number().int().nullable(),errorCode:z24.string().nullable(),error:z24.string().nullable(),outputBytes:z24.number().int().nonnegative(),outputTruncated:z24.boolean(),outputExpiresAt:z24.coerce.date().nullable(),metadataExpiresAt:z24.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z24.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z24.coerce.date().nullable(),items:z24.array(z24.object({key:z24.string().min(1),updatedAt:z24.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z24.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z24.object({trigger:z24.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z24.object({limit:z24.coerce.number().int().min(1).max(100).default(25),cursor:z24.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z24.object({items:z24.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z24.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z24.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z24.object({items:z24.array(ProjectScheduleRunDTOSchema),nextCursor:z24.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z25}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=z25.object({id:z25.uuid(),occurredAt:z25.coerce.date(),projectId:z25.uuid().nullable(),env:z25.string().nullable(),actor:z25.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z25.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z25.unknown().optional(),ipAddress:z25.string().nullable().optional(),userAgent:z25.string().nullable().optional(),error:z25.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z25.object({rows:z25.array(AuditLogRowDTOSchema),nextCursor:z25.string().nullable()})),AuditLogQuerySchema=z25.object({env:z25.string().optional(),action:AuditActionSchema.optional(),actor:z25.string().optional(),from:z25.coerce.date().optional(),to:z25.coerce.date().optional(),limit:z25.coerce.number().int().min(1).max(200).optional(),cursor:z25.string().optional()})}});import{z as z26}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,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,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=z26.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z26.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z26.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z26.object({verb:SurfaceDeltaVerbSchema,key:z26.string(),detail:z26.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z26.record(z26.string(),z26.unknown()).optional()}),PerSurfaceDeltaSchema=z26.object({surface:SurfaceNameSchema,status:z26.enum(["ok","timed_out","failed","unchanged"]),durationMs:z26.number().int().nonnegative().optional(),changedCount:z26.number().int().nonnegative(),conflictCount:z26.number().int().nonnegative(),items:z26.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z26.boolean().optional(),error:z26.string().optional()}),CrossSurfaceFindingSchema=z26.object({id:z26.string(),kind:z26.string(),description:z26.string(),severity:z26.enum(["warning","error"]),source:z26.object({surface:SurfaceNameSchema,key:z26.string()}),target:z26.object({surface:SurfaceNameSchema,key:z26.string()}),actions:z26.array(z26.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z26.object({env:EnvSchema,vs:EnvSchema,syncState:z26.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),agents:z26.array(z26.object({id:z26.string(),name:z26.string(),status:z26.enum(["active","paused","failed"]),lastRunAt:z26.coerce.date().nullable()})).optional(),crossSurface:z26.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z26.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),crossSurface:z26.array(CrossSurfaceFindingSchema).optional(),fingerprint:z26.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z26.object({path:z26.string(),state:z26.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z26.string(),additions:z26.number().int().nonnegative(),deletions:z26.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z26.object({oid:z26.string().optional(),content:z26.string().optional(),truncated:z26.boolean(),binary:z26.boolean()}),CodeConflictDetailSchema=z26.object({path:z26.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z26.string(),targetTipSha:z26.string(),mergeBaseSha:z26.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z26.object({id:z26.string(),slug:z26.string(),contentType:z26.string(),data:z26.record(z26.string(),z26.unknown()),updatedAt:z26.coerce.date()}),ContentRowDiffSchema=z26.object({collection:z26.string(),rowId:z26.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z26.object({name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),fields:z26.record(z26.string(),z26.unknown())}),SchemaTypeDiffSchema=z26.object({typeName:z26.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z26.object({id:z26.string(),name:z26.string(),type:z26.enum(["file","folder"]),mimeType:z26.string().nullable(),storageKey:z26.string().nullable(),url:z26.string().nullable(),fileSize:z26.number().nullable(),width:z26.number().nullable(),height:z26.number().nullable(),altText:z26.string().nullable(),caption:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AssetDiffSchema=z26.object({assetId:z26.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z26.object({locale:z26.string(),key:z26.string(),parent:z26.string().nullable(),child:z26.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z26.object({formName:z26.string(),label:z26.string().nullable(),schemaFingerprint:z26.string(),fields:z26.record(z26.string(),z26.unknown()),settings:z26.record(z26.string(),z26.unknown()).optional()}),FormSchemaDiffSchema=z26.object({formName:z26.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),triggerKind:z26.string(),triggerSpec:z26.record(z26.string(),z26.unknown()),enabled:z26.boolean(),emailRecipients:z26.array(z26.string()).nullable(),qstashScheduleId:z26.string().nullable()}),ActivationDiffSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z26.enum(CONFLICT_KINDS),ConflictSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),kind:ConflictKindSchema.optional(),description:z26.string(),parentValue:z26.unknown().optional(),childValue:z26.unknown().optional(),conflictingFields:z26.array(z26.string()).optional(),code:z26.object({path:z26.string(),unresolvable:z26.boolean().optional(),reason:z26.string().optional()}).optional()}),FieldPickSchema=z26.object({field:z26.string(),choice:z26.enum(["parent","child","pick","ai-pick"]),pickedValue:z26.unknown().optional(),aiSessionId:z26.string().optional()}),ConflictResolutionSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),choice:z26.enum(["parent","child","pick"]),pickedValue:z26.unknown().optional(),fieldPicks:z26.array(FieldPickSchema).optional()}),MergeResultSchema=z26.object({ok:z26.boolean(),mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z26.array(z26.object({surface:SurfaceNameSchema,count:z26.number().int().nonnegative()})),conflicts:z26.array(ConflictSchema).optional(),summary:z26.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z26.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z26.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z26.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z26.boolean().optional()}),ResolvedStrategySchema=z26.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z26.boolean()}),MergeRequestSchema=z26.object({from:EnvSchema,allowDirectMerge:z26.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z26.object({mergeId:z26.string().uuid(),streamUrl:z26.string(),strategy:ResolvedStrategySchema,acceptedAt:z26.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z26.object({mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z26.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z26.array(ConflictSchema),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedBy:z26.string().nullable(),lastEditedAt:z26.coerce.date().nullable(),initiator:z26.object({userId:z26.string().nullable(),role:z26.string().nullable(),agentName:z26.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z26.object({resolutions:z26.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z26.object({mergeId:z26.string().uuid(),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedAt:z26.coerce.date(),lastEditedBy:z26.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z26.object({mergeId:z26.string().uuid(),resolutions:z26.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z26.object({mergeId:z26.string().uuid()}),PublishReleaseRequestSchema=z26.object({version:z26.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z26.string().max(2e4).optional()}),PublishReleaseResultSchema=z26.object({releaseTag:z26.string(),sha:z26.string(),publishedAt:z26.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z27}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=z27.object({surface:SurfaceNameSchema,key:z27.string(),label:z27.string()}),InlineSchema=z27.object({text:z27.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z27.discriminatedUnion("type",[z27.object({type:z27.literal("paragraph"),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("preview"),ref:DiffRefSchema,caption:z27.string().optional()}),z27.object({type:z27.literal("code"),code:z27.string(),lang:z27.string().optional(),caption:z27.string().optional()}),z27.object({type:z27.literal("risk"),level:z27.enum(["warning","error"]),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("list"),items:z27.array(z27.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z27.object({headline:z27.string(),blocks:z27.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z27.object({summary:EnvDiffSummarySchema,fingerprint:z27.string(),generatedAt:z27.coerce.date(),cached:z27.boolean().optional(),credits:z27.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z28}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=z28.object({date:z28.string(),visitors:z28.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z28.object({key:z28.string(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z28.object({path:z28.string(),pageName:z28.string().nullable().optional(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z28.object({preset:z28.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z28.string(),requestedTo:z28.string(),effectiveFrom:z28.string(),effectiveTo:z28.string(),isRetentionLimited:z28.boolean(),groupBy:z28.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z28.object({date:z28.string(),content:z28.string(),updatedAt:z28.string(),updatedByUserId:z28.string()}),ProjectPageviewAnalyticsDTOSchema=z28.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative(),bounceRate:z28.number().min(0).max(100),viewsPerVisit:z28.number().nonnegative(),averageVisitDurationSeconds:z28.number().nonnegative(),visitorsSeries:z28.array(ProjectDailyVisitorsDTOSchema),topPages:z28.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z28.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z29}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=z29.object({id:z29.string(),email:z29.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z29.coerce.date(),createdAt:z29.coerce.date(),inviterUserId:z29.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z29.object({id:z29.string(),token:z29.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z29.object({success:z29.boolean(),projectId:z29.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z30}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=z30.object({id:z30.string(),name:z30.string(),image:z30.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z30.object({count:z30.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z30.object({counts:z30.object({signed_up:z30.int(),activated:z30.int()}),credits:z30.object({total:z30.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z30.email(),emailVerified:z30.boolean(),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z31}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,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=z31.object({id:z31.string(),principalType:ProjectPrincipalTypeSchema,principalId:z31.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z31.coerce.date(),expiresAt:z31.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z31.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z31.record(z31.string(),z31.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z31.object({access:z31.array(ProjectAccessItemDTOSchema),invites:z31.array(ProjectInviteDTOSchema),organization:z31.object({name:z31.string().nullable(),logo:z31.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z31.object({success:z31.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z31.object({success:z31.boolean(),projectId:z31.uuid()}))}});import{z as z32}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=z32.object({publicationStatus:PublicationStatusSchema,appUrl:z32.string().nullable(),lastPublishedAt:z32.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z33}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewBootstrapDTOSchema,PreviewBootstrapDTO,PreviewBootstrapResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z33.object({url:z33.url(),expiresAt:z33.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewBootstrapDTOSchema=z33.discriminatedUnion("source",[z33.object({source:z33.literal("artifact"),artifact:SandboxSessionDTOSchema,dev:z33.null()}),z33.object({source:z33.literal("dev"),artifact:z33.null(),dev:SandboxSessionDTOSchema})]),PreviewBootstrapDTO=createDTO(PreviewBootstrapDTOSchema),PreviewBootstrapResponseSchema=createResponseSchema(PreviewBootstrapDTOSchema)}});import{z as z34}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:z34.string(),slug:z34.string().nullable(),logo:z34.string().nullable(),metadata:z34.record(z34.string(),z34.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z34.object({id:z34.string(),name:z34.string(),email:z34.email(),image:z34.string().nullable()}),OrganizationMemberDTOSchema=z34.object({id:z34.string(),userId:z34.string(),organizationId:z34.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z34.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z35}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,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=z35.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z35.object({reason:CancellationReasonCodeSchema,details:z35.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z35.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z35.object({included:z35.number().optional(),unitPrice:z35.number().optional(),dailyCap:z35.number().nullable().optional()}),EntitlementsDTOSchema=z35.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z35.object({retentionDays:z35.number().int().positive(),canUseExtendedDateRanges:z35.boolean()}).optional(),history:z35.object({retentionDays:z35.number().int().positive()}).optional(),members:z35.object({canInvite:z35.boolean(),maxMembers:z35.number().int().positive().nullable()}).optional(),projects:z35.object({canCreatePrivateProjects:z35.boolean(),maxPrivateProjects:z35.number().int().positive().nullable()}).optional(),domains:z35.object({canUseCustomDomains:z35.boolean(),maxDomains:z35.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z35.object({id:z35.string(),external_id:z35.string(),customerId:z35.string(),planId:z35.string(),planCode:TemplateCodeSchema,currentPeriod:z35.object({start:z35.string(),end:z35.string().nullable()}),cancelAt:z35.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z35.string(),nextPaymentAt:z35.string().nullable(),baseAmount:z35.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z35.object({totalCap:z35.number(),dailyCap:z35.number(),usedTotal:z35.number()}),CreditBalanceDTOSchema=z35.object({total:z35.number(),base:z35.number(),dailyBase:z35.number(),purchases:z35.number(),awards:z35.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z35.object({total:z35.number(),nearLimit:z35.boolean(),canChat:z35.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z35.object({dailyFreeAvailable:z35.number(),monthlyAvailable:z35.number(),purchasedAvailable:z35.number(),awardedAvailable:z35.number()}),ProjectDailyCreditAllowanceDTOSchema=z35.object({periodCap:z35.number(),dailyGrant:z35.number(),usedThisPeriod:z35.number(),remainingThisPeriod:z35.number()}),ProjectCreditBalanceDTOSchema=z35.object({projectId:z35.uuid(),organizationId:z35.string(),balance:z35.object({totalAvailable:z35.number(),nearLimit:z35.boolean(),canUseAi:z35.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z35.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z35.object({invoiceId:z35.string(),newBalance:z35.int(),creditCount:z35.int(),amountUsd:z35.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z35.object({url:z35.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z36}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=z36.object({brand:z36.string(),last4:z36.string(),exp:z36.string(),isDefault:z36.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z37}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=z37.string().superRefine((path47,ctx)=>{let segments=path47.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=z37.object({type:z37.literal("renameField"),contentType:z37.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z37.object({enabled:z37.boolean()}).strict(),ContentTypeDTOSchema=z37.object({id:z37.string(),name:z37.string(),label:z37.string(),isSingleton:z37.boolean(),i18n:ContentTypeI18nSchema,fields:z37.record(z37.string(),FieldDefinitionSchema),createdAt:z37.string(),updatedAt:z37.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z37.object({contentTypes:z37.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z37.object({id:z37.string(),entryId:z37.string(),documentId:z37.string(),slug:z37.string(),locale:z37.string().optional(),createdAt:z37.string(),updatedAt:z37.string(),__fimo:z37.object({contentType:z37.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({limit:z37.number(),offset:z37.number(),total:z37.number(),hasMore:z37.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z37.object({contentType:z37.string(),count:z37.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z37.object({counts:z37.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z37.object({count:z37.number().int().nonnegative(),sourceLocale:z37.string(),targetLocale:z37.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z37.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z37.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z37.union([z37.string(),z37.number(),z37.boolean(),z37.null()]),entryWhereOperatorSchema=z37.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z37.array(entryWhereScalarSchema).optional(),$nin:z37.array(entryWhereScalarSchema).optional(),$contains:z37.string().optional(),$startsWith:z37.string().optional(),$null:z37.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z37.object({data:z37.record(z37.string(),z37.unknown()),locale:z37.string().min(1).optional(),documentId:z37.uuid().optional()}),entryIdsSchema=z37.array(z37.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z37.object({sql:z37.string().min(1)}),BulkCreateEntriesRequestSchema=z37.object({entries:z37.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z37.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z37.object({updates:z37.array(z37.object({id:z37.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,locale:z37.string().min(1).optional()}),z37.object({where:EntryWhereSchema,locale:z37.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z37.object({data:z37.array(z37.record(z37.string(),z37.unknown())),meta:z37.object({rowCount:z37.number().int().nonnegative(),truncated:z37.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({created:z37.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({updated:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({deleted:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z38}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z38.object({index:z38.number().int().nonnegative(),contentType:z38.string(),field:z38.string(),value:z38.string(),against:z38.enum(["stored","batch"]),ownerDocumentId:z38.uuid().optional(),ownerIndex:z38.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z38.object({code:z38.literal("unique_conflict"),message:z38.string(),conflicts:z38.array(UniqueConflictSchema),truncated:z38.boolean().optional()})}});import{z as z39}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=z39.object({kind:z39.literal("unique_conflict"),contentType:z39.string(),field:z39.string(),value:z39.string(),documentCount:z39.number().int().positive(),documentIds:z39.array(z39.uuid()),documentIdsTruncated:z39.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z39.object({code:z39.literal("schema_transition_rejected"),message:z39.string(),issues:z39.array(SchemaTransitionIssueSchema),truncated:z39.boolean().optional()})}});import{z as z40}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=z40.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z40.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z40.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z40.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z40.object({field:CmsFieldNameSchema,direction:z40.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z40.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z40.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z40.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z40.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z40.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z41}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=z41.object({id:z41.string(),name:z41.string()}),AssetDTOSchema=z41.object({id:z41.string(),name:z41.string(),type:AssetTypeSchema,originalFileName:z41.string().nullable(),parentId:z41.string().nullable(),mimeType:z41.string().nullable(),fileSize:z41.number().nullable(),url:z41.string().nullable(),storageKey:z41.string().nullable(),createdAt:z41.string(),updatedAt:z41.string(),altText:z41.string().nullable().optional(),caption:z41.string().nullable().optional(),aiCaption:z41.string().nullable().optional(),aiAltText:z41.string().nullable().optional(),aiTags:z41.array(z41.string()).nullable().optional(),aiPrimaryColor:z41.string().nullable().optional(),aiProcessingStatus:z41.string().nullable().optional(),width:z41.number().nullable().optional(),height:z41.number().nullable().optional(),path:z41.array(AssetPathItemSchema).optional(),hasChildren:z41.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z41.lazy(()=>z41.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z41.array(AssetDTOSchema))}});import{z as z42}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z42.object({key:z42.string(),value:z42.string().optional(),defaultValue:z42.string(),locale:z42.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z43}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=z43.object({id:z43.string(),name:z43.string(),type:z43.enum(["file","folder"]),path:z43.string(),children:z43.lazy(()=>z43.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z43.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z43.object({path:z43.string(),exists:z43.boolean(),type:z43.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z44}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z44.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z44.object({items:z44.array(ProjectMessagePublicDTOSchema),nextCursor:z44.string().nullable()}),ChatDeletionDTOSchema=z44.object({success:z44.boolean(),deletedCount:z44.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z45}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=z45.object({url:z45.string().url(),key:z45.string(),size:z45.number(),contentType:z45.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z46}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=z46.object({canAccess:z46.boolean(),permissions:z46.record(z46.string(),z46.boolean()),role:z46.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z47}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:z47.string().trim().default(""),sort:z47.enum(["recent","name","relevance"]).default("recent"),category:z47.string().optional(),visibility:z47.enum(["public","private"]).optional()})}});import{z as z48}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=z48.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z48.enum(["fimo","external"]),PaymentStatusSchema=z48.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z48.object({id:z48.string().uuid(),domain:z48.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z48.boolean(),price:z48.number().int().nullable(),renewalPrice:z48.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z48.string().nullable(),failureReason:z48.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z48.object({domain:z48.string(),available:z48.boolean(),premium:z48.boolean(),price:z48.number().nullable(),renewalPrice:z48.number().nullable(),purchaseType:z48.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z48.object({domain:z48.string(),price:z48.number().nullable(),renewalPrice:z48.number().nullable(),premium:z48.boolean(),allowedYears:z48.array(z48.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z48.object({firstName:z48.string().max(100),lastName:z48.string().max(100),companyName:z48.string().max(100).optional(),address1:z48.string().max(255),address2:z48.string().max(255).optional(),city:z48.string().max(100),state:z48.string().max(100),zip:z48.string().max(20),country:z48.string().max(2),phone:z48.string().max(30),email:z48.union([z48.string().email().max(255),z48.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z48.object({firstName:z48.string().min(1).max(100),lastName:z48.string().min(1).max(100),companyName:z48.string().max(100).optional(),address1:z48.string().min(1).max(255),address2:z48.string().max(255).optional(),city:z48.string().min(1).max(100),state:z48.string().min(1).max(100),zip:z48.string().min(1).max(20),country:z48.string().min(1).max(2),phone:z48.string().min(1).max(30),email:z48.string().email().max(255)}),SearchDomainsRequestSchema=z48.object({keyword:z48.string().min(1).max(100),tldFilter:z48.array(z48.string()).optional()}),CheckAvailabilityRequestSchema=z48.object({domains:z48.array(z48.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=z48.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z48.object({domain:DomainNameSchema,years:z48.number().int().min(1).max(10).optional().default(3),autoRenew:z48.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z48.object({autoRenew:z48.boolean().optional()}),RenewDomainRequestSchema=z48.object({years:z48.number().int().min(1).max(10).optional().default(1),autoRenew:z48.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z48.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z48.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z48.object({verified:z48.boolean(),email:z48.string().nullable(),verifyBy:z48.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z49}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=z49.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=z49.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=z49.object({txtName:z49.string().nullable().optional(),txtValue:z49.string().nullable().optional(),httpUrl:z49.string().nullable().optional(),httpBody:z49.string().nullable().optional(),cname:z49.string().nullable().optional(),cnameTarget:z49.string().nullable().optional()}),SSLValidationErrorSchema=z49.object({message:z49.string()}),OwnershipVerificationSchema=z49.object({type:z49.string(),name:z49.string(),value:z49.string()}),ProjectDomainSSLDTOSchema=z49.object({status:z49.string(),method:z49.string().nullable(),type:z49.string().nullable(),validationRecords:z49.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z49.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z49.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z49.enum(["subdomain","apex"]),RedirectConfigSchema=z49.object({type:z49.literal("apex_to_www"),linkedDomainId:z49.string()}).nullable().optional(),ProjectDomainDTOSchema=z49.object({id:z49.string(),hostname:z49.string(),status:z49.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z49.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z49.string(),scdCnameTarget:z49.string().optional(),apexTargets:z49.array(z49.string()),dnsAutoConfigured:z49.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z49.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z49.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z49.object({hostname:z49.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:z49.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z49.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z49.object({available:z49.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z49.object({success:z49.boolean(),hostname:z49.string()}))}});import{z as z50}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=z50.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z50.object({available:z50.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z50.object({slug:z50.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z50.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z50.object({subdomain:z50.string(),subdomainUpdatedAt:z50.coerce.date()})),SubdomainSuggestionsQuerySchema=z50.object({base:z50.string().max(100).optional(),max:z50.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z50.object({suggestions:z50.array(z50.string())}))}});import{z as z51}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=z51.object({translated:z51.number().int().nonnegative(),total:z51.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z51.object({locale:z51.string(),isDefault:z51.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z51.object({defaultLocale:z51.string(),routing:z51.object({strategy:z51.literal("path-prefix"),prefixDefaultLocale:z51.boolean()}),locales:z51.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z51.object({locale:z51.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z51.object({locale:z51.string().min(1).max(40)}),ProjectLocaleMutationSchema=z51.object({locale:z51.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z51.object({locale:z51.string(),entriesDeleted:z51.number().int().nonnegative(),labelsDeleted:z51.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z52}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=z52.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z52.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=z52.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z52.number(),credits:z52.number().optional(),billingMode:z52.enum(["fimo-credits","provider-account"]).optional(),confidence:z52.enum(["exact","estimated","metered"]),basis:z52.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z53}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=z53.object({options:z53.record(z53.string(),z53.unknown()),name:z53.string().optional(),parentId:z53.string().nullable().optional(),altText:z53.string().optional(),caption:z53.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z53.string().min(1).optional(),model:z53.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=z53.object({jobId:z53.string(),status:z53.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z53.string().nullable().optional(),credits:z53.number().optional(),costUsd:z53.number().optional(),billingMode:z53.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z53.object({error:z53.string(),code:z53.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:z53.array(GenerationTaskIdSchema).optional(),availableModels:z53.array(z53.string()).optional(),issues:z53.array(z53.unknown()).optional()})}});import{z as z54}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=z54.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z54.object({name:z54.string(),key:z54.string(),description:z54.string(),type:FlagTypeSchema,required:z54.boolean(),defaultValue:z54.unknown().optional(),enumValues:z54.array(z54.string()).optional(),isArray:z54.boolean()}),AssetModelPriceSchema=z54.object({unitPrice:z54.number(),unit:z54.string(),confidence:z54.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z54.object({id:z54.string(),shortName:z54.string(),provider:z54.string(),source:z54.string(),modality:z54.enum(["image","video","audio"]),tags:z54.array(z54.string()),displayName:z54.string(),description:z54.string(),flags:z54.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z54.object({model:z54.string(),costUsd:z54.number(),credits:z54.number(),billingMode:z54.enum(["fimo-credits","provider-account"]),confidence:z54.enum(["exact","estimated","metered"]),basis:z54.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z55}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=z55.object({tourId:z55.string(),version:z55.string(),status:z55.string(),completedAt:z55.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z55.array(UserTourDTOSchema))}});import{z as z56}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=z56.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z56.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z56.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z56.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z56.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z56.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z56.enum(["user","agent","system"]),SupportReportTagSchema=z56.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z56.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z56.object({organization:z56.object({id:z56.string().trim().min(1).max(255),name:z56.string().trim().max(240).optional()}),project:z56.object({id:z56.uuid(),name:z56.string().trim().max(240).optional(),createdAt:z56.coerce.date().optional()}).optional(),environment:z56.string().trim().max(255).optional(),clientVersion:z56.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z56.object({message:z56.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z56.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z56.string().trim().max(200).optional(),limit:z56.coerce.number().int().min(1).max(100).default(50),offset:z56.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z56.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z56.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z56.uuid().nullable().optional(),note:z56.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=z56.object({message:z56.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z56.object({kind:SupportReportLinkKindSchema,label:z56.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z56.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z56.object({kind:SupportReportActorKindSchema,id:z56.string().nullable(),name:z56.string().nullable()}),SupportReportLinkDTOSchema=z56.object({id:z56.uuid(),kind:SupportReportLinkKindSchema,label:z56.string(),url:SupportReportHttpUrlSchema,externalId:z56.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z56.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z56.object({id:z56.uuid(),kind:SupportReportEventKindSchema,body:z56.string().nullable(),metadata:z56.record(z56.string(),z56.unknown()),actor:SupportReportActorDTOSchema,createdAt:z56.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z56.object({id:z56.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z56.array(z56.string()),source:SupportReportSourceSchema,message:z56.string(),reporter:z56.object({id:z56.string().nullable(),name:z56.string().nullable(),email:z56.string().nullable()}),organization:z56.object({id:z56.string().nullable(),name:z56.string()}),project:z56.object({id:z56.uuid().nullable(),name:z56.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z56.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z56.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z56.string().nullable(),deliveredAt:z56.coerce.date().nullable()}).nullable(),duplicateOfReportId:z56.uuid().nullable(),resolvedAt:z56.coerce.date().nullable(),createdAt:z56.coerce.date(),updatedAt:z56.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z56.string().nullable(),clientVersion:z56.string().nullable(),links:z56.array(SupportReportLinkDTOSchema),events:z56.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z56.object({reports:z56.array(SupportReportSummaryDTOSchema),total:z56.number().int().nonnegative(),statusCounts:z56.object({new:z56.number().int().nonnegative(),in_progress:z56.number().int().nonnegative(),waiting:z56.number().int().nonnegative(),resolved:z56.number().int().nonnegative(),duplicate:z56.number().int().nonnegative(),irrelevant:z56.number().int().nonnegative(),ignored:z56.number().int().nonnegative()}),limit:z56.number().int().positive(),offset:z56.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z56.object({id:z56.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z56.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z57}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=z57.iso.datetime({offset:!0}).pipe(z57.coerce.date()),OpsRecentChatInputSchema=z57.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z57.string().trim().min(1).max(255).optional(),limit:z57.coerce.number().int().min(1).max(200).default(100),cursor:z57.string().trim().min(1).max(2e3).optional(),slim:z57.boolean().default(!0),reason:z57.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=z57.object({id:z57.string(),messageId:z57.string(),env:z57.string(),versionId:z57.string().nullable(),userId:z57.string().nullable(),role:z57.string(),parts:z57.array(z57.record(z57.string(),z57.unknown())),metadata:z57.object({status:z57.string().optional(),traceUrl:z57.string().optional(),externalFileChanges:z57.array(z57.unknown()).optional()}),stats:z57.object({toolCount:z57.number().int().nonnegative(),failedToolCount:z57.number().int().nonnegative()}),createdAt:z57.iso.datetime({offset:!0}),project:z57.object({id:z57.string(),name:z57.string(),displayName:z57.string().nullable(),organizationId:z57.string().nullable()})}),OpsRecentChatResponseSchema=z57.object({target:z57.object({backendProfile:OpsBackendProfileSchema,projectEnv:z57.string().nullable()}),window:z57.object({from:z57.iso.datetime({offset:!0}),to:z57.iso.datetime({offset:!0})}),messages:z57.object({items:z57.array(OpsRecentChatMessageSchema),nextCursor:z57.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z58}from"zod";function createAgentRunWebhookEventDataSchema(status){return z58.object({run:z58.object({id:z58.string(),agentName:z58.string(),trigger:z58.string(),status:z58.literal(status),startedAt:z58.string().nullable(),finishedAt:z58.string().nullable(),reason:z58.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,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_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=z58.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z58.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z58.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z58.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z58.union([z58.literal(0),z58.literal(5),z58.literal(30),z58.literal(60)]),EntryChangedWebhookEventDataSchema=z58.object({reason:WebhookEntryChangeReasonSchema,operationId:z58.string().optional(),batch:z58.object({index:z58.number().int().positive(),total:z58.number().int().positive()}).optional(),changes:z58.array(z58.object({action:WebhookEntryChangeActionSchema,contentType:z58.string(),id:z58.string(),documentId:z58.string(),locale:z58.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z58.object({form:z58.object({id:z58.string(),label:z58.string()}),submission:z58.object({id:z58.string(),data:z58.record(z58.string(),z58.unknown()),submittedAt:z58.string()})}),PublishStartedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("publishing"),startedAt:z58.string()})}),PublishSucceededWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("published"),url:z58.string(),publishedAt:z58.string(),firstPublish:z58.boolean()})}),PublishFailedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("failed"),reason:z58.string()})}),PublishUnpublishedWebhookEventDataSchema=z58.object({publication:z58.object({previousUrl:z58.string(),unpublishedAt:z58.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),classification:z58.string(),summary:z58.string(),reasons:z58.array(z58.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),resolution:z58.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z58.object({report:z58.object({weekStart:z58.string(),weekEnd:z58.string(),pageviews:z58.number(),visitors:z58.number(),previousPageviews:z58.number(),previousVisitors:z58.number()})}),MediaAssetWebhookEventDataSchema=z58.object({id:z58.string().nullable(),name:z58.string().nullable(),type:z58.string(),mimeType:z58.string().nullable(),fileSize:z58.number().nullable()}),MediaUploadedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["updated","moved","analysis"]),analysis:z58.object({category:z58.string(),status:z58.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("generated"),generation:z58.object({model:z58.string(),mode:z58.string()})}),MediaProcessingFailedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["analysis","generation"]),failure:z58.object({code:z58.string()})}),DomainCreatedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string()})}),LabelChangedWebhookEventDataSchema=z58.object({changes:z58.array(z58.object({action:z58.enum(["created","updated","deleted"]),key:z58.string(),locale:z58.string(),value:z58.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),isDefault:z58.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),previousCode:z58.string()})}),LocaleDeletedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z58.object({merge:z58.object({id:z58.string(),from:EnvSchema,to:EnvSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema}),version:z58.object({versionId:z58.uuid(),name:z58.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=z58.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z58.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z58.discriminatedUnion("source",[z58.object({source:z58.literal("literal"),value:z58.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z58.object({source:z58.literal("secret"),key:z58.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z58.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z58.object({name:z58.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z58.object({name:z58.string(),source:z58.enum(["literal","secret"]),secretKey:z58.string().nullable(),secretPrefix:z58.string().nullable(),configured:z58.literal(!0)}),WebhookFilterSchema=z58.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z58.string().min(1).max(255).optional(),agentName:z58.string().min(1).max(120).optional(),mediaType:z58.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z58.string().min(1).max(255).optional(),locale:z58.string().min(1).max(120).optional()}),JsonValueSchema=z58.lazy(()=>z58.union([z58.string(),z58.number(),z58.boolean(),z58.null(),z58.array(JsonValueSchema),z58.record(z58.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z58.url(),enabled:z58.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z58.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z58.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z58.url().optional(),enabled:z58.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z58.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z58.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z58.object({eventType:WebhookEventTypeSchema.optional(),data:z58.record(z58.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z58.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z58.uuid(),name:z58.string(),eventType:WebhookEventTypeSchema,enabled:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z58.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z58.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z58.coerce.date().nullable(),deliveryStats24h:z58.object({succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z58.uuid(),projectId:z58.uuid(),env:EnvSchema,eventId:z58.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z58.number().int().positive(),test:z58.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z58.number().int().nonnegative(),responseStatus:z58.number().int().nullable(),lastErrorCode:z58.string().nullable(),lastErrorMessage:z58.string().nullable(),payloadAvailable:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z58.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z58.string().nullable(),qstashMessageId:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z58.object({items:z58.array(WebhookDeliveryDTOSchema),pagination:z58.object({page:z58.number().int().positive(),limit:z58.number().int().positive(),total:z58.number().int().nonnegative(),totalPages:z58.number().int().positive(),hasMore:z58.boolean()}),stats:z58.object({total:z58.number().int().nonnegative(),succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z58.object({id:z58.uuid(),deliveryId:z58.uuid(),attempt:z58.number().int().positive(),status:z58.enum(["delivering","succeeded","failed"]),responseStatus:z58.number().int().nullable(),durationMs:z58.number().int().nonnegative(),responseExcerpt:z58.string().nullable(),errorCode:z58.string().nullable(),errorMessage:z58.string().nullable(),createdAt:z58.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z58.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z58.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z59}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=z59.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z59.object({total:z59.number(),base:z59.number(),purchases:z59.number(),awards:z59.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z59.object({id:z59.string(),name:z59.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z59.object({type:z59.string(),brand:z59.string().nullable(),last4:z59.string().nullable(),expirationDate:z59.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z59.object({currency:z59.string(),nextPaymentAmount:z59.number().nullable(),nextPaymentAt:z59.string().nullable(),billingInterval:z59.string().nullable(),totalAmount:z59.number().nullable(),discountAmount:z59.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z59.object({id:z59.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z59.string().nullable(),currentPeriodEndsAt:z59.string().nullable(),renewsAt:z59.string().nullable(),cancelAt:z59.string().nullable(),renewAutomatically:z59.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z59.object({type:z59.enum(["low_balance","critical_balance","approaching_limit"]),message:z59.string(),estimatedPromptsRemaining:z59.number().nullable(),avgCostPerPrompt:z59.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z59.object({monthlyCredits:z59.number().nullable(),usedThisPeriod:z59.number(),remainingThisPeriod:z59.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z59.object({organizationId:z59.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z59.string().nullable(),tenureDays:z59.number().int().nonnegative(),capturedAt:z59.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z59.object({hasSubscription:z59.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z59.number().nullable(),alerts:z59.array(CreditAlertDTOSchema),portalUrl:z59.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z59.object({creditCount:z59.number().int().positive(),expiresAt:z59.string().datetime().nullable().optional(),message:z59.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("free"),amountCents:z59.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("purchase"),amountCents:z59.number().int().positive()}),CreditTopupRequestDTOSchema=z59.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z59.object({success:z59.boolean(),transactionId:z59.string().nullable(),newBalance:z59.number(),creditCount:z59.number(),type:z59.enum(["free","purchase"]),invoiceId:z59.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z60}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=z60.object({totalCredits:z60.number(),totalCostUsd:z60.number(),totalMessages:z60.number(),avgCostPerMessage:z60.number(),periodStart:z60.string().nullable(),periodEnd:z60.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z60.object({date:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z60.array(UsageByUserForProjectDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z60.object({summary:UsageSummaryDTOSchema,byProject:z60.array(UsageByProjectDTOSchema),byUser:z60.array(UsageByUserDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z61}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=z61.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z61.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z61.object({startDate:z61.string().optional(),endDate:z61.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z61.coerce.number().int().positive().default(1),limit:z61.coerce.number().int().positive().max(100).default(20),sortBy:z61.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z61.string().optional()}),UsageOverviewSummaryDTOSchema=z61.object({totalCredits:z61.number(),totalCostUsd:z61.number(),totalMessages:z61.number(),avgCostPerMessage:z61.number(),avgCreditsPerMessage:z61.number(),periodStart:z61.string(),periodEnd:z61.string(),creditsChange:z61.number().nullable(),costChange:z61.number().nullable(),messagesChange:z61.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z61.object({date:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z61.object({organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number(),projectCount:z61.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z61.object({userId:z61.string(),userName:z61.string().nullable(),userEmail:z61.string().nullable(),userImage:z61.string().nullable(),organizationId:z61.string().nullable(),organizationName:z61.string().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),projectCount:z61.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z61.object({projectId:z61.string(),projectName:z61.string(),projectDisplayName:z61.string().nullable(),organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z61.object({id:z61.string(),name:z61.string(),value:z61.number(),percentage:z61.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z61.object({day:z61.number(),hour:z61.number(),value:z61.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z61.object({summary:UsageOverviewSummaryDTOSchema,timeline:z61.array(UsageTimelinePointDTOSchema),topOrganizations:z61.array(OrganizationUsageRowDTOSchema),topUsers:z61.array(UserUsageRowDTOSchema),topProjects:z61.array(ProjectUsageRowDTOSchema),creditDistribution:z61.array(UsageDistributionItemDTOSchema),heatmap:z61.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z61.object({page:z61.number(),limit:z61.number(),totalItems:z61.number(),totalPages:z61.number(),hasMore:z61.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z61.object({organizations:z61.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z61.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z61.object({users:z61.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z61.object({projects:z61.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z61.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z61.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z61.object({credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),createdAt:z61.string(),memberCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z61.object({id:z61.string(),name:z61.string().nullable(),email:z61.string(),image:z61.string().nullable(),createdAt:z61.string(),organizationCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),displayName:z61.string().nullable(),createdAt:z61.string(),organizationId:z61.string(),organizationName:z61.string(),ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z62}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=z62.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z62.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z62.object({command:z62.string().min(1).max(1e4),cwd:z62.string().optional(),projectEnv:EnvSchema.optional(),env:z62.record(z62.string(),z62.string()).optional(),name:z62.string().optional(),waitForCompletion:z62.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z62.object({identifier:z62.string(),status:SandboxProcessStatusSchema,command:z62.string().optional(),startedAt:z62.string().optional(),exitCode:z62.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z62.object({processes:z62.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z62.object({processId:z62.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z62.object({success:z62.boolean(),message:z62.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z63}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_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_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_webhook_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit(["rev-parse","--abbrev-ref","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveEnvFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{env:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||branch==="HEAD"||!isValidEnv(branch)?null:{env:branch,source:"branch"}}catch{return null}}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let env,source,readOnly=!1;if(opts.envOverride!==void 0){if(!isValidEnv(opts.envOverride))throw new InvalidEnvOverrideError(opts.envOverride);env=opts.envOverride,source="flag"}else{let fromGit=await resolveEnvFromGit(cwd);if(fromGit)env=fromGit.env,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{if(opts.requireBranch)throw await isGitRepo(cwd)?new GitBranchUndetectedError:new NotInProjectError;env=DEFAULT_ENV,source="fallback"}}if(opts.api&&env!=="prod")try{let names=(await opts.api.listEnvs(settings.projectId)).map(e=>e.env);if(!names.includes(env)&&source==="flag")throw new EnvNotFoundError(env,names)}catch(err){if(err instanceof EnvNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,env,source,readOnly:readOnly||void 0}}function envSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--env":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"default",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 env: ${ctx.env} (from ${sourceHint}${ro})`}function envOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let env=cur.opts().env;if(typeof env=="string"&&env.length>0)return env;cur=cur.parent??null}}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let envOverride2=envOverrideFromCommand(cmd),baseApi=new FimoApiClient(loadConfig()),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2,requireBranch:bootstrapOpts.requireBranch,api:baseApi});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${envSourceBanner(ctx)}
|
|
196
196
|
`)}if(bootstrapOpts.refuseReadOnly&&ctx.readOnly)throw new Error(`Refusing to run a mutating command against read-only env '${ctx.env}'. Switch off the release/* tag or pass --env <writable-env>.`);return{ctx,api:baseApi.withEnv(ctx.env)}}var NotInProjectError,InvalidEnvOverrideError,EnvNotFoundError,GitBranchUndetectedError,init_project_context=__esm({"src/cli/utils/project-context.ts"(){init_esm();init_api();init_config();init_git();init_project();NotInProjectError=class extends Error{static{__name(this,"NotInProjectError")}constructor(){super("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project."),this.name="NotInProjectError"}};__name(projectSettingsFromEnv,"projectSettingsFromEnv");InvalidEnvOverrideError=class extends Error{static{__name(this,"InvalidEnvOverrideError")}value;constructor(value){super(`--env value '${value}' is invalid. Env names must match /^[a-zA-Z0-9._/-]+$/, not start with '-', and be \u2264255 chars.`),this.name="InvalidEnvOverrideError",this.value=value}},EnvNotFoundError=class extends Error{static{__name(this,"EnvNotFoundError")}env;knownEnvs;constructor(env,knownEnvs){super(`Env '${env}' not found on the server. Known envs: ${knownEnvs.length>0?knownEnvs.join(", "):"(none yet)"}.`),this.name="EnvNotFoundError",this.env=env,this.knownEnvs=knownEnvs}},GitBranchUndetectedError=class extends Error{static{__name(this,"GitBranchUndetectedError")}constructor(){super("In a git repository but no branch could be detected (detached HEAD or empty repo). Pass --env <name> to target an env explicitly."),this.name="GitBranchUndetectedError"}};__name(resolveEnvFromGit,"resolveEnvFromGit");__name(getProjectContext,"getProjectContext");__name(envSourceBanner,"envSourceBanner");__name(envOverrideFromCommand,"envOverrideFromCommand");__name(bootstrapProjectCommand,"bootstrapProjectCommand")}});var isAmbiguous,isFullWidth,isWide,init_utils=__esm({"../../node_modules/.pnpm/fast-string-truncated-width@1.2.1/node_modules/fast-string-truncated-width/dist/utils.js"(){isAmbiguous=__name(x=>x===161||x===164||x===167||x===168||x===170||x===173||x===174||x>=176&&x<=180||x>=182&&x<=186||x>=188&&x<=191||x===198||x===208||x===215||x===216||x>=222&&x<=225||x===230||x>=232&&x<=234||x===236||x===237||x===240||x===242||x===243||x>=247&&x<=250||x===252||x===254||x===257||x===273||x===275||x===283||x===294||x===295||x===299||x>=305&&x<=307||x===312||x>=319&&x<=322||x===324||x>=328&&x<=331||x===333||x===338||x===339||x===358||x===359||x===363||x===462||x===464||x===466||x===468||x===470||x===472||x===474||x===476||x===593||x===609||x===708||x===711||x>=713&&x<=715||x===717||x===720||x>=728&&x<=731||x===733||x===735||x>=768&&x<=879||x>=913&&x<=929||x>=931&&x<=937||x>=945&&x<=961||x>=963&&x<=969||x===1025||x>=1040&&x<=1103||x===1105||x===8208||x>=8211&&x<=8214||x===8216||x===8217||x===8220||x===8221||x>=8224&&x<=8226||x>=8228&&x<=8231||x===8240||x===8242||x===8243||x===8245||x===8251||x===8254||x===8308||x===8319||x>=8321&&x<=8324||x===8364||x===8451||x===8453||x===8457||x===8467||x===8470||x===8481||x===8482||x===8486||x===8491||x===8531||x===8532||x>=8539&&x<=8542||x>=8544&&x<=8555||x>=8560&&x<=8569||x===8585||x>=8592&&x<=8601||x===8632||x===8633||x===8658||x===8660||x===8679||x===8704||x===8706||x===8707||x===8711||x===8712||x===8715||x===8719||x===8721||x===8725||x===8730||x>=8733&&x<=8736||x===8739||x===8741||x>=8743&&x<=8748||x===8750||x>=8756&&x<=8759||x===8764||x===8765||x===8776||x===8780||x===8786||x===8800||x===8801||x>=8804&&x<=8807||x===8810||x===8811||x===8814||x===8815||x===8834||x===8835||x===8838||x===8839||x===8853||x===8857||x===8869||x===8895||x===8978||x>=9312&&x<=9449||x>=9451&&x<=9547||x>=9552&&x<=9587||x>=9600&&x<=9615||x>=9618&&x<=9621||x===9632||x===9633||x>=9635&&x<=9641||x===9650||x===9651||x===9654||x===9655||x===9660||x===9661||x===9664||x===9665||x>=9670&&x<=9672||x===9675||x>=9678&&x<=9681||x>=9698&&x<=9701||x===9711||x===9733||x===9734||x===9737||x===9742||x===9743||x===9756||x===9758||x===9792||x===9794||x===9824||x===9825||x>=9827&&x<=9829||x>=9831&&x<=9834||x===9836||x===9837||x===9839||x===9886||x===9887||x===9919||x>=9926&&x<=9933||x>=9935&&x<=9939||x>=9941&&x<=9953||x===9955||x===9960||x===9961||x>=9963&&x<=9969||x===9972||x>=9974&&x<=9977||x===9979||x===9980||x===9982||x===9983||x===10045||x>=10102&&x<=10111||x>=11094&&x<=11097||x>=12872&&x<=12879||x>=57344&&x<=63743||x>=65024&&x<=65039||x===65533||x>=127232&&x<=127242||x>=127248&&x<=127277||x>=127280&&x<=127337||x>=127344&&x<=127373||x===127375||x===127376||x>=127387&&x<=127404||x>=917760&&x<=917999||x>=983040&&x<=1048573||x>=1048576&&x<=1114109,"isAmbiguous"),isFullWidth=__name(x=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,"isFullWidth"),isWide=__name(x=>x>=4352&&x<=4447||x===8986||x===8987||x===9001||x===9002||x>=9193&&x<=9196||x===9200||x===9203||x===9725||x===9726||x===9748||x===9749||x>=9800&&x<=9811||x===9855||x===9875||x===9889||x===9898||x===9899||x===9917||x===9918||x===9924||x===9925||x===9934||x===9940||x===9962||x===9970||x===9971||x===9973||x===9978||x===9981||x===9989||x===9994||x===9995||x===10024||x===10060||x===10062||x>=10067&&x<=10069||x===10071||x>=10133&&x<=10135||x===10160||x===10175||x===11035||x===11036||x===11088||x===11093||x>=11904&&x<=11929||x>=11931&&x<=12019||x>=12032&&x<=12245||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12353&&x<=12438||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=19968&&x<=42124||x>=42128&&x<=42182||x>=43360&&x<=43388||x>=44032&&x<=55203||x>=63744&&x<=64255||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=94176&&x<=94180||x===94192||x===94193||x>=94208&&x<=100343||x>=100352&&x<=101589||x>=101632&&x<=101640||x>=110576&&x<=110579||x>=110581&&x<=110587||x===110589||x===110590||x>=110592&&x<=110882||x===110898||x>=110928&&x<=110930||x===110933||x>=110948&&x<=110951||x>=110960&&x<=111355||x===126980||x===127183||x===127374||x>=127377&&x<=127386||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x===127568||x===127569||x>=127584&&x<=127589||x>=127744&&x<=127776||x>=127789&&x<=127797||x>=127799&&x<=127868||x>=127870&&x<=127891||x>=127904&&x<=127946||x>=127951&&x<=127955||x>=127968&&x<=127984||x===127988||x>=127992&&x<=128062||x===128064||x>=128066&&x<=128252||x>=128255&&x<=128317||x>=128331&&x<=128334||x>=128336&&x<=128359||x===128378||x===128405||x===128406||x===128420||x>=128507&&x<=128591||x>=128640&&x<=128709||x===128716||x>=128720&&x<=128722||x>=128725&&x<=128727||x>=128732&&x<=128735||x===128747||x===128748||x>=128756&&x<=128764||x>=128992&&x<=129003||x===129008||x>=129292&&x<=129338||x>=129340&&x<=129349||x>=129351&&x<=129535||x>=129648&&x<=129660||x>=129664&&x<=129672||x>=129680&&x<=129725||x>=129727&&x<=129733||x>=129742&&x<=129755||x>=129760&&x<=129768||x>=129776&&x<=129784||x>=131072&&x<=196605||x>=196608&&x<=262141,"isWide")}});var ANSI_RE,CONTROL_RE,TAB_RE,EMOJI_RE,LATIN_RE,MODIFIER_RE,NO_TRUNCATION,getStringTruncatedWidth,dist_default,init_dist2=__esm({"../../node_modules/.pnpm/fast-string-truncated-width@1.2.1/node_modules/fast-string-truncated-width/dist/index.js"(){init_utils();ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,TAB_RE=/\t{1,1000}/y,EMOJI_RE=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=new RegExp("\\p{M}+","gu"),NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=__name((input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=widthOptions.ansiWidth??0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,AMBIGUOUS_WIDTH=widthOptions.ambiguousWidth??1,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=widthOptions.fullWidthWidth??2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,indexPrev=0,index2=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:for(;;){if(unmatchedEnd>unmatchedStart||index2>=length&&index2>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index2);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint)?widthExtra=FULL_WIDTH_WIDTH:isWide(codePoint)?widthExtra=WIDE_WIDTH:AMBIGUOUS_WIDTH!==REGULAR_WIDTH&&isAmbiguous(codePoint)?widthExtra=AMBIGUOUS_WIDTH:widthExtra=REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra)),width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index2>=length)break;if(LATIN_RE.lastIndex=index2,LATIN_RE.test(input)){if(lengthExtra=LATIN_RE.lastIndex-index2,widthExtra=lengthExtra*REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/REGULAR_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=LATIN_RE.lastIndex;continue}if(ANSI_RE.lastIndex=index2,ANSI_RE.test(input)){if(width+ANSI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2)),width+ANSI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=ANSI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=ANSI_RE.lastIndex;continue}if(CONTROL_RE.lastIndex=index2,CONTROL_RE.test(input)){if(lengthExtra=CONTROL_RE.lastIndex-index2,widthExtra=lengthExtra*CONTROL_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/CONTROL_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=CONTROL_RE.lastIndex;continue}if(TAB_RE.lastIndex=index2,TAB_RE.test(input)){if(lengthExtra=TAB_RE.lastIndex-index2,widthExtra=lengthExtra*TAB_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/TAB_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=TAB_RE.lastIndex;continue}if(EMOJI_RE.lastIndex=index2,EMOJI_RE.test(input)){if(width+EMOJI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2)),width+EMOJI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=EMOJI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=EMOJI_RE.lastIndex;continue}index2+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},"getStringTruncatedWidth"),dist_default=getStringTruncatedWidth}});var NO_TRUNCATION2,fastStringWidth,dist_default2,init_dist3=__esm({"../../node_modules/.pnpm/fast-string-width@1.1.0/node_modules/fast-string-width/dist/index.js"(){init_dist2();NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=__name((input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,"fastStringWidth"),dist_default2=fastStringWidth}});function wrapAnsi(string,columns,options){return String(string).normalize().split(CRLF_OR_LF).map(line=>exec(line,columns,options)).join(`
|
|
197
197
|
`)}var ESC,CSI,END_CODE,ANSI_ESCAPE_BELL,ANSI_CSI,ANSI_OSC,ANSI_SGR_TERMINATOR,ANSI_ESCAPE_LINK,GROUP_REGEX,getClosingCode,wrapAnsiCode,wrapAnsiHyperlink,wrapWord,stringVisibleTrimSpacesRight,exec,CRLF_OR_LF,init_main=__esm({"../../node_modules/.pnpm/fast-wrap-ansi@0.1.6/node_modules/fast-wrap-ansi/lib/main.js"(){init_dist3();ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=__name(openingCode=>{if(openingCode>=30&&openingCode<=37||openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47||openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0},"getClosingCode"),wrapAnsiCode=__name(code2=>`${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`,"wrapAnsiCode"),wrapAnsiHyperlink=__name(url=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,"wrapAnsiHyperlink"),wrapWord=__name((rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;for(;!currentCharacter.done;){let character=currentCharacter.value,characterLength=dist_default2(character);visible+characterLength<=columns?rows[rows.length-1]+=character:(rows.push(character),visible=0),(character===ESC||character===CSI)&&(isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1)),isInsideEscape?isInsideLinkEscape?character===ANSI_ESCAPE_BELL&&(isInsideEscape=!1,isInsideLinkEscape=!1):character===ANSI_SGR_TERMINATOR&&(isInsideEscape=!1):(visible+=characterLength,visible===columns&&!nextCharacter.done&&(rows.push(""),visible=0)),currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1&&(rows[rows.length-2]+=rows.pop())},"wrapWord"),stringVisibleTrimSpacesRight=__name(string=>{let words=string.split(" "),last2=words.length;for(;last2&&!dist_default2(words[last2-1]);)last2--;return last2===words.length?string:words.slice(0,last2).join(" ")+words.slice(last2).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index2=0;index2<words.length;index2++){let word=words[index2];if(options.trim!==!1){let row2=rows.at(-1)??"",trimmed=row2.trimStart();row2.length!==trimmed.length&&(rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed))}index2!==0&&(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1)&&(rows.push(""),rowLength=0),(rowLength||options.trim===!1)&&(rows[rows.length-1]+=" ",rowLength++));let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);Math.floor((wordLength-1)/columns)<breaksStartingThisLine&&rows.push(""),wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}options.trim!==!1&&(rows=rows.map(row2=>stringVisibleTrimSpacesRight(row2)));let preString=rows.join(`
|
|
198
198
|
`),inSurrogate=!1;for(let i=0;i<preString.length;i++){let character=preString[i];if(returnValue+=character,!inSurrogate)inSurrogate=character>="\uD800"&&character<="\uDBFF";else continue;if(character===ESC||character===CSI){GROUP_REGEX.lastIndex=i+1;let groups=GROUP_REGEX.exec(preString)?.groups;if(groups?.code!==void 0){let code2=Number.parseFloat(groups.code);escapeCode=code2===END_CODE?void 0:code2}else groups?.uri!==void 0&&(escapeUrl=groups.uri.length===0?void 0:groups.uri)}if(preString[i+1]===`
|
|
@@ -1203,7 +1203,16 @@ username=${cred.username}
|
|
|
1203
1203
|
password=${cred.token}
|
|
1204
1204
|
`;return cred.expiresAt&&(out+=`password_expiry_utc=${Math.floor(cred.expiresAt/1e3)}
|
|
1205
1205
|
`),out}__name(buildCredentialOutput,"buildCredentialOutput");async function readStdin(){if(process.stdin.isTTY)return"";let chunks=[];for await(let chunk of process.stdin)chunks.push(chunk);return Buffer.concat(chunks).toString("utf8")}__name(readStdin,"readStdin");async function gitCredentialCommand(operation){if(operation!=="get")return;let input=parseCredentialInput(await readStdin());if(input.protocol!=="https")return;let ctx;try{ctx=await getProjectContext()}catch{return}let cred;try{cred=await new FimoApiClient().getGitCredential(ctx.projectId,ctx.env)}catch(err){process.stderr.write(`fimo: could not obtain git credentials \u2014 ${err instanceof Error?err.message:String(err)}
|
|
1206
|
-
`);return}let out=buildCredentialOutput(input,cred);out&&process.stdout.write(out)}__name(gitCredentialCommand,"gitCredentialCommand");
|
|
1206
|
+
`);return}let out=buildCredentialOutput(input,cred);out&&process.stdout.write(out)}__name(gitCredentialCommand,"gitCredentialCommand");init_dist5();init_esm();init_dist();init_api();init_config();init_interactive();init_project_context();function addScopeOptions(command){return command.option("--project <id>","Project id (defaults to the linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions,"addScopeOptions");function registerHistoryCommands(program2){let history=program2.command("history").description("Create, inspect, and restore project history").addHelpText("after",`
|
|
1207
|
+
Examples:
|
|
1208
|
+
fimo history list
|
|
1209
|
+
fimo history list --limit 20 --cursor <cursor>
|
|
1210
|
+
fimo history show <version-id>
|
|
1211
|
+
fimo history create "Before content migration"
|
|
1212
|
+
fimo history restore <version-id> --yes
|
|
1213
|
+
`);addScopeOptions(history.command("list").description("List restore points for the current environment").option("--limit <count>","Maximum restore points to return (1-100)","20").option("--cursor <cursor>","Opaque cursor returned by the previous page")).action((options,command)=>historyListCommand(options,command)),addScopeOptions(history.command("show <versionId>").description("Show one restore point")).action((versionId,options,command)=>historyShowCommand(versionId,options,command)),addScopeOptions(history.command("create <name>").description("Save the current code and content as a restore point").option("--description <text>","Optional description")).action((name,options,command)=>historyCreateCommand(name,options,command)),addScopeOptions(history.command("restore <versionId>").description("Restore code and content from a restore point").option("-y, --yes","Skip the confirmation prompt")).action((versionId,options,command)=>historyRestoreCommand(versionId,options,command))}__name(registerHistoryCommands,"registerHistoryCommands");async function resolveScope(options,command){let envOverride2=envOverrideFromCommand(command),baseApi=new FimoApiClient(loadConfig());if(options.project){let env=envOverride2??DEFAULT_ENV;if(!isValidEnv(env))throw new Error(`Invalid environment '${env}'.`);return{api:baseApi.withEnv(env),projectId:options.project,env}}let context=await getProjectContext({cwd:options.cwd,envOverride:envOverride2,api:baseApi});return{api:baseApi.withEnv(context.env),projectId:context.projectId,env:context.env}}__name(resolveScope,"resolveScope");function parseLimit(value){let limit=Number(value??20);if(!Number.isInteger(limit)||limit<1||limit>100)throw new Error("--limit must be an integer between 1 and 100.");return limit}__name(parseLimit,"parseLimit");async function runHistoryCommand(command,operation){try{await operation()}catch(error){if(error instanceof ApiRequestError){ui.error({command,code:error.code??"HISTORY_REQUEST_FAILED",message:error.detail,...error.code==="HISTORY_BUSY"?{hint:"Retry after the current history operation finishes."}:error.code==="RESTORE_INCOMPLETE"?{hint:"Retry the restore after checking that active editors have stopped writing."}:{}});return}throw error}}__name(runHistoryCommand,"runHistoryCommand");async function historyListCommand(options,command){await runHistoryCommand("history list",async()=>{let scope=await resolveScope(options,command),limit=parseLimit(options.limit),[page,summary2]=await Promise.all([scope.api.listProjectVersions(scope.projectId,{limit,cursor:options.cursor}),scope.api.getProjectHistorySummary(scope.projectId)]),result={...page,...summary2},hint=page.nextCursor?buildHistoryListHint(page.nextCursor,scope.env,limit,options):void 0;ui.result({command:"history list",data:result,render:__name(()=>renderHistoryList(result,scope.env),"render"),...hint?{hint}:{}})})}__name(historyListCommand,"historyListCommand");function buildHistoryListHint(nextCursor,env,limit,options){let args=["fimo","history","list","--env",env,"--limit",String(limit),"--cursor",nextCursor];return options.project&&args.push("--project",options.project),options.cwd&&args.push("--cwd",options.cwd),`More: ${args.map(formatCommandArgument).join(" ")}`}__name(buildHistoryListHint,"buildHistoryListHint");function formatCommandArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(formatCommandArgument,"formatCommandArgument");async function historyShowCommand(versionId,options,command){await runHistoryCommand("history show",async()=>{let scope=await resolveScope(options,command),version=await scope.api.getProjectVersion(scope.projectId,versionId);ui.result({command:"history show",data:version,render:__name(()=>renderHistoryVersion(version,scope.env),"render")})})}__name(historyShowCommand,"historyShowCommand");async function historyCreateCommand(name,options,command){await runHistoryCommand("history create",async()=>{let scope=await resolveScope(options,command),version=await scope.api.createProjectVersion(scope.projectId,{name,description:options.description});ui.ok({command:"history create",headline:`Saved restore point "${version.name}".`,details:{version_id:version.versionId,env:scope.env,created_at:formatTimestamp(version.createdAt)}})})}__name(historyCreateCommand,"historyCreateCommand");async function historyRestoreCommand(versionId,options,command){await runHistoryCommand("history restore",async()=>{let scope=await resolveScope(options,command),version=await scope.api.getProjectVersion(scope.projectId,versionId);if(!options.yes){assertInteractive("Pass --yes to restore without a prompt.","history restore");let confirmed=await ot2({message:`Restore "${version.name}" on ${scope.env}? Current code and content will be saved as a safety point first.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"history restore",message:"Cancelled."});return}}let result=await scope.api.restoreProjectVersion(scope.projectId,versionId);ui.ok({command:"history restore",headline:`Restored "${version.name}" on ${scope.env}.`,details:{version_id:version.versionId,env:scope.env,duration_ms:result.durationMs??null},...result.warning?{warnings:[result.warning]}:{}})})}__name(historyRestoreCommand,"historyRestoreCommand");function renderHistoryList(result,env){let lines=[`History \xB7 ${env}`,""];if(result.items.length===0)lines.push("No restore points yet.");else{lines.push("ID CREATED KIND NAME");for(let version of result.items)lines.push(`${version.versionId.padEnd(36)} ${formatTimestamp(version.createdAt).padEnd(16)} ${version.kind.padEnd(15)} ${version.name}`)}return lines.push("",`Usage: ${result.usage.versionCount} restore points \xB7 ${formatBytes2(result.usage.snapshotBytes)} compressed`,`Retention: ${result.retentionDays} days`),lines.join(`
|
|
1214
|
+
`)}__name(renderHistoryList,"renderHistoryList");function renderHistoryVersion(version,env){return[version.name,"",`Version ID: ${version.versionId}`,`Environment: ${env}`,`Kind: ${version.kind}`,`Created: ${formatTimestamp(version.createdAt)}`,`Commit: ${version.commitHash}`,`Description: ${version.description??"None"}`].join(`
|
|
1215
|
+
`)}__name(renderHistoryVersion,"renderHistoryVersion");function formatTimestamp(value){let date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?String(value):date.toISOString().slice(0,16).replace("T"," ")}__name(formatTimestamp,"formatTimestamp");function formatBytes2(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KiB`:`${(bytes/(1024*1024)).toFixed(1)} MiB`}__name(formatBytes2,"formatBytes");init_init();init_dist5();import path34 from"node:path";init_dist();init_open();init_api();init_auth();init_config();init_interactive();init_project();function registerIntegrationsCommands(program2){let integrations=program2.command("integrations").description("Manage project integrations").addHelpText("after",`
|
|
1207
1216
|
Examples:
|
|
1208
1217
|
fimo integrations list
|
|
1209
1218
|
fimo integrations info firecrawl
|
|
@@ -1259,16 +1268,29 @@ Run \`fimo integrations <command> --help\` for command-specific help.
|
|
|
1259
1268
|
`)}
|
|
1260
1269
|
`}__name(mergeEnvFile,"mergeEnvFile");function renderManagedEnvBlock(rows){return[FIMO_VARS_START,"# Generated by fimo vars pull. Do not put secrets in this block.",...rows.map(row2=>`${row2.key}=${quoteEnvValue(row2.value??"")}`),FIMO_VARS_END]}__name(renderManagedEnvBlock,"renderManagedEnvBlock");function quoteEnvValue(value){return/^[A-Za-z0-9_./:@-]*$/.test(value)?value:JSON.stringify(value)}__name(quoteEnvValue,"quoteEnvValue");init_dist5();init_dist();init_api();init_auth();init_config();init_auth_errors();init_interactive();import fs39 from"node:fs";import path42 from"node:path";function resolveCwd2(options){return options.cwd?path42.resolve(options.cwd):process.cwd()}__name(resolveCwd2,"resolveCwd");function readLocalConfig(options){let cwd=resolveCwd2(options),settingsPath=path42.join(cwd,".fimo.settings.json");return fs39.existsSync(settingsPath)?JSON.parse(fs39.readFileSync(settingsPath,"utf-8")):null}__name(readLocalConfig,"readLocalConfig");function resolveProjectId5(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.settings.json` found in the current directory.",hint:"Pass a project ID explicitly, or cd into a linked project."}),null)}__name(resolveProjectId5,"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=resolveProjectId5(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.settings.json` 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=path42.join(cwd,"fimo-config.json"),config={};if(fs39.existsSync(configPath))try{config=JSON.parse(fs39.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},fs39.writeFileSync(configPath,JSON.stringify(config,null,2)+`
|
|
1261
1270
|
`),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=resolveProjectId5(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(),ui.error({command:"projects publish",code:"PROJECT_PUBLISH_FAILED",message:`Publish failed: ${error instanceof Error?error.message:String(error)}`});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}})}__name(projectsPublishCommand,"projectsPublishCommand");async function projectsUnpublishCommand(projectIdArg,options){let cfg=loadConfig(),api=new FimoApiClient(cfg),projectId=resolveProjectId5(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_esm();init_dist();init_api();init_auth_errors();init_project_context();init_project();async function publishCommand(options,cmd){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 fs40 from"node:fs";import path43 from"node:path";async function rulesSyncCommand(options={}){let cwd=path43.resolve(options.cwd??process.cwd()),agentsMdPath=path43.join(cwd,"AGENTS.md");if(!fs40.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(`
|
|
1262
|
-
`))},"render")})}__name(rulesSyncCommand,"rulesSyncCommand");init_esm();init_dist();init_api();init_config();init_project_context();init_project();function registerSchedulesCommands(program2){let schedules=program2.command("schedules").description("Manage
|
|
1271
|
+
`))},"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 collect(value,previous){return[...previous??[],value]}__name(collect,"collect");function addScopeOptions2(command){return command.option("--env <env>","Target env (defaults to the current git branch)").option("--project <id>","Project id (defaults to .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions2,"addScopeOptions");function registerSchedulesCommands(program2){let schedules=program2.command("schedules").description("Manage recurring project commands").addHelpText("after",`
|
|
1263
1272
|
Examples:
|
|
1264
|
-
fimo schedules create nightly
|
|
1265
|
-
fimo schedules create smoke --cron "*/15 * * * *" --do "pnpm test"
|
|
1273
|
+
fimo schedules create nightly --cron "0 2 * * *" --do "fimo validate" --secret CMS_TOKEN
|
|
1266
1274
|
fimo schedules list
|
|
1267
|
-
fimo schedules
|
|
1268
|
-
fimo schedules
|
|
1275
|
+
fimo schedules show nightly
|
|
1276
|
+
fimo schedules run nightly
|
|
1277
|
+
fimo schedules runs nightly --status failed
|
|
1278
|
+
fimo schedules runs show <run-id>
|
|
1279
|
+
|
|
1280
|
+
Delivery:
|
|
1281
|
+
Runs use at-least-once delivery. If a completion response is lost, the same run may execute again.
|
|
1282
|
+
Side-effecting commands should use FIMO_SCHEDULE_RUN_ID as their idempotency key.
|
|
1269
1283
|
|
|
1270
1284
|
Run \`fimo schedules <command> --help\` for command-specific help.
|
|
1271
|
-
`);schedules.command("create <name>").description("Create a scheduled command").requiredOption("--cron <expr>",'Cron expression, e.g. "0 2 * * *"').requiredOption("--do <command>","Command to run inside the
|
|
1285
|
+
`);addScopeOptions2(schedules.command("create <name>").description("Create a scheduled command").requiredOption("--cron <expr>",'Cron expression, e.g. "0 2 * * *"').requiredOption("--do <command>","Command to run inside the environment").option("--secret <key>","Expose a project secret to the command; repeat for multiple keys",collect)).action((name,opts)=>createCommand2(name,opts)),addScopeOptions2(schedules.command("list").description("List schedules for an environment")).action(opts=>listCommand3(opts)),addScopeOptions2(schedules.command("show <schedule>").description("Show a schedule configuration")).action((schedule,opts)=>showCommand(schedule,opts)),addScopeOptions2(schedules.command("update <schedule>").description("Update a schedule configuration").option("--name <name>","Change the schedule name").option("--cron <expr>","Change the cron expression").option("--do <command>","Change the command").option("--secret <key>","Replace exposed project secrets; repeat for multiple keys",collect).option("--clear-secrets","Remove all project secrets from the schedule")).action((schedule,opts)=>updateCommand(schedule,opts)),addScopeOptions2(schedules.command("run <schedule>").description("Run a schedule now").option("--no-wait","Return after the run is queued")).action((schedule,opts)=>runCommand2(schedule,opts)),addScopeOptions2(schedules.command("pause <schedule>").description("Pause future cron runs")).action((schedule,opts)=>toggleCommand(schedule,!1,opts)),addScopeOptions2(schedules.command("resume <schedule>").description("Resume future cron runs")).action((schedule,opts)=>toggleCommand(schedule,!0,opts));let runs=addScopeOptions2(schedules.command("runs [schedule]").description("List runs for a schedule").option("--limit <count>","Maximum runs per page (1-100)").option("--cursor <cursor>","Continue from an opaque cursor").option("--status <status>","Filter by queued, running, succeeded, failed, or skipped").option("--all","Fetch all pages"));runs.action((schedule,opts,command)=>{if(!schedule){command.help();return}return runsCommand(schedule,opts)}),addScopeOptions2(runs.command("show <runId>").description("Show run details and captured output")).action((runId,opts,command)=>runShowCommand(runId,{...command.parent?.opts(),...opts})),addScopeOptions2(schedules.command("delete <schedule>").description("Delete a schedule")).action((schedule,opts)=>deleteCommand(schedule,opts))}__name(registerSchedulesCommands,"registerSchedulesCommands");async function resolveScope2(opts){let baseApi=new FimoApiClient(loadConfig()),env=opts.env;if(!env)try{env=(await getProjectContext({cwd:opts.cwd})).env}catch(error){if(!opts.project)throw error;env=DEFAULT_ENV}if(opts.project)return{projectId:opts.project,api:baseApi.withEnv(env)};let cwd=resolveProjectCwd(opts.cwd);return{projectId:loadProjectSettings(cwd).projectId,api:baseApi.withEnv(env)}}__name(resolveScope2,"resolveScope");async function resolveScheduleId(api,projectId,reference){if(UUID_PATTERN.test(reference))return reference;let schedule=(await api.listSchedules(projectId)).find(candidate=>candidate.name===reference);if(!schedule)throw new ScheduleCommandError("SCHEDULE_NOT_FOUND",`Schedule '${reference}' was not found in this environment.`);return schedule.id}__name(resolveScheduleId,"resolveScheduleId");async function createCommand2(name,opts){let parsed=CreateProjectScheduleRequestSchema.safeParse({name,cron:opts.cron,command:opts.do,secretKeys:opts.secret??[]});if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid schedule.");let{projectId,api}=await resolveScope2(opts),schedule=await api.createSchedule(projectId,parsed.data);renderSchedule("schedules create",schedule)}__name(createCommand2,"createCommand");async function listCommand3(opts){let{projectId,api}=await resolveScope2(opts);renderScheduleList("schedules list",await api.getSchedulesOverview(projectId))}__name(listCommand3,"listCommand");async function showCommand(reference,opts){let{projectId,api}=await resolveScope2(opts),scheduleId=await resolveScheduleId(api,projectId,reference);renderScheduleDetail("schedules show",await api.getSchedule(projectId,scheduleId))}__name(showCommand,"showCommand");async function updateCommand(reference,opts){if(opts.secret!==void 0&&opts.clearSecrets)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED","Use either --secret or --clear-secrets, not both.");let request={...opts.name!==void 0?{name:opts.name}:{},...opts.cron!==void 0?{cron:opts.cron}:{},...opts.do!==void 0?{command:opts.do}:{},...opts.clearSecrets?{secretKeys:[]}:opts.secret!==void 0?{secretKeys:opts.secret}:{}},parsed=UpdateProjectScheduleRequestSchema.safeParse(request);if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid schedule update.");let{projectId,api}=await resolveScope2(opts),scheduleId=await resolveScheduleId(api,projectId,reference);renderSchedule("schedules update",await api.updateSchedule(projectId,scheduleId,parsed.data))}__name(updateCommand,"updateCommand");async function toggleCommand(reference,enabled,opts){let{projectId,api}=await resolveScope2(opts),scheduleId=await resolveScheduleId(api,projectId,reference),schedule=await api.setScheduleEnabled(projectId,scheduleId,enabled);renderSchedule(enabled?"schedules resume":"schedules pause",schedule)}__name(toggleCommand,"toggleCommand");async function runCommand2(reference,opts){let{projectId,api}=await resolveScope2(opts),scheduleId=await resolveScheduleId(api,projectId,reference),run;try{run=await api.runSchedule(projectId,scheduleId)}catch(error){if(error instanceof ApiRequestError&&error.status===409&&error.code==="run_in_progress"){let activeRunId=readActiveRunId(error.body);ui.error({command:"schedules run",code:"SCHEDULE_RUN_IN_PROGRESS",message:activeRunId?`Schedule already has an active run: ${activeRunId}`:"Schedule already has an active run.",hint:activeRunId?`Inspect it with: fimo schedules runs show ${activeRunId}`:void 0});return}throw error}if(opts.wait===!1){renderRun("schedules run",run);return}let progress=spinner(`Run ${run.id} is ${run.status}`),deadline=Date.now()+RUN_POLL_TIMEOUT_MS,detail=await api.getScheduleRun(projectId,run.id);for(;!TERMINAL_RUN_STATUSES.includes(detail.status)&&Date.now()<deadline;)progress.update(`Run ${run.id} is ${detail.status}`),await new Promise(resolve9=>setTimeout(resolve9,RUN_POLL_INTERVAL_MS)),detail=await api.getScheduleRun(projectId,run.id);if(progress.stop(),!TERMINAL_RUN_STATUSES.includes(detail.status))throw new ScheduleCommandError("SCHEDULE_RUN_TIMEOUT",`Run ${run.id} did not finish within ${RUN_POLL_TIMEOUT_MS/6e4} minutes.`);if(detail.status!=="succeeded"){let error=detail.error??"No error details were returned.";ui.error({command:"schedules run",code:"SCHEDULE_RUN_FAILED",message:`Schedule run ${detail.id} finished with status ${detail.status}: ${error}`,hint:`Inspect run ${detail.id} (status: ${detail.status}, error: ${error}) with: fimo schedules runs show ${detail.id}`});return}renderRunDetail("schedules run",detail)}__name(runCommand2,"runCommand");async function runsCommand(reference,opts){let parsed=ProjectScheduleRunsQuerySchema.safeParse({limit:opts.limit,cursor:opts.cursor,status:opts.status});if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid run query.");let{projectId,api}=await resolveScope2(opts),scheduleId=await resolveScheduleId(api,projectId,reference),page=await api.listScheduleRuns(projectId,scheduleId,parsed.data);if(opts.all){let items=[...page.items];for(;page.nextCursor;)page=await api.listScheduleRuns(projectId,scheduleId,{limit:parsed.data.limit,cursor:page.nextCursor,status:parsed.data.status}),items.push(...page.items);page={...page,items,nextCursor:null}}renderRuns("schedules runs",page)}__name(runsCommand,"runsCommand");async function runShowCommand(runId,opts){let{projectId,api}=await resolveScope2(opts);renderRunDetail("schedules runs show",await api.getScheduleRun(projectId,runId))}__name(runShowCommand,"runShowCommand");async function deleteCommand(reference,opts){let{projectId,api}=await resolveScope2(opts),scheduleId=await resolveScheduleId(api,projectId,reference),result=await api.deleteSchedule(projectId,scheduleId);ui.result({command:"schedules delete",data:result,render:__name(()=>`Deleted schedule ${reference} (${scheduleId})`,"render")})}__name(deleteCommand,"deleteCommand");function renderSchedule(command,schedule){ui.result({command,data:schedule,render:__name(()=>renderFields({ID:schedule.id,Name:schedule.name,Environment:schedule.env,Cron:schedule.cron,Command:schedule.command,Enabled:schedule.enabled?"yes":"no",Secrets:schedule.secretKeys.join(", ")||"none"}),"render")})}__name(renderSchedule,"renderSchedule");function renderScheduleList(command,data2){ui.result({command,data:data2,render:__name(()=>renderTable(["ID","NAME","CRON","COMMAND","ENABLED","LAST STATUS"],data2.items.map(schedule=>[schedule.id,schedule.name,schedule.cron,schedule.command,schedule.enabled?"yes":"no",schedule.lastStatus??""])),"render")})}__name(renderScheduleList,"renderScheduleList");function renderScheduleDetail(command,data2){ui.result({command,data:data2,render:__name(()=>`${renderFields({ID:data2.schedule.id,Name:data2.schedule.name,Environment:data2.schedule.env,Cron:data2.schedule.cron,Command:data2.schedule.command,Enabled:data2.schedule.enabled?"yes":"no",Secrets:data2.schedule.secretKeys.join(", ")||"none",Runs:data2.usage.runCount,"Runs with output":data2.usage.runsWithOutput,"Maximum runs":data2.policy.maxRuns,"Metadata retention":data2.policy.retentionDays===null?"pending":`${data2.policy.retentionDays} days`,"Output retention":`${data2.policy.outputRetentionDays} days`,"Maximum output":`${data2.policy.maxOutputBytes} bytes`})}
|
|
1286
|
+
`,"render")})}__name(renderScheduleDetail,"renderScheduleDetail");function renderRun(command,run){ui.result({command,data:run,render:__name(()=>renderFields({"Run ID":run.id,Schedule:run.scheduleName,Command:run.command,Status:run.status,Trigger:run.trigger,Queued:String(run.queuedAt)}),"render")})}__name(renderRun,"renderRun");function renderRuns(command,data2){ui.result({command,data:data2,render:__name(()=>`${renderTable(["RUN ID","STATUS","TRIGGER","ACTOR","QUEUED","STARTED","FINISHED"],data2.items.map(run=>[run.id,run.status,run.trigger,run.triggeredBy?.name??"",String(run.queuedAt),run.startedAt?String(run.startedAt):"",run.finishedAt?String(run.finishedAt):""]))}
|
|
1287
|
+
|
|
1288
|
+
${renderFields({"Run count":data2.usage.runCount,"Runs with output":data2.usage.runsWithOutput,"Maximum runs":data2.policy.maxRuns,"Metadata retention":data2.policy.retentionDays===null?"pending":`${data2.policy.retentionDays} days`,"Output retention":`${data2.policy.outputRetentionDays} days`,"Maximum output":`${data2.policy.maxOutputBytes} bytes`,"Next cursor":data2.nextCursor??"none"})}`,"render")})}__name(renderRuns,"renderRuns");function renderRunDetail(command,run){ui.result({command,data:run,render:__name(()=>{let fields=renderFields({"Run ID":run.id,"Schedule ID":run.scheduleId,Schedule:run.scheduleName,Command:run.command,Environment:run.env,Status:run.status,Trigger:run.trigger,Actor:run.triggeredBy?.name??"",Queued:String(run.queuedAt),Started:run.startedAt?String(run.startedAt):"",Finished:run.finishedAt?String(run.finishedAt):"","Exit code":run.exitCode??"","Error code":run.errorCode??"",Error:run.error??"","Output bytes":run.outputBytes,"Output truncated":run.outputTruncated?"yes":"no","Output expires":run.outputExpiresAt?String(run.outputExpiresAt):"","Metadata expires":run.metadataExpiresAt?String(run.metadataExpiresAt):"","Secret snapshot":run.secretSnapshot.state,Secrets:run.secretSnapshot.items.map(item=>`${item.key} (${item.resolution})`).join(", ")||"none"});return run.output?`${fields}
|
|
1289
|
+
|
|
1290
|
+
Output
|
|
1291
|
+
${run.output}`:fields},"render")})}__name(renderRunDetail,"renderRunDetail");function renderFields(fields){let width=Math.max(...Object.keys(fields).map(key=>key.length));return Object.entries(fields).map(([key,value])=>`${key.padEnd(width)} ${String(value)}`).join(`
|
|
1292
|
+
`)}__name(renderFields,"renderFields");function renderTable(headers,rows){if(rows.length===0)return"No results.";let widths=headers.map((header,index2)=>Math.max(header.length,...rows.map(row2=>String(row2[index2]??"").length)));return[headers,...rows].map(row2=>row2.map((value,index2)=>String(value).padEnd(widths[index2])).join(" ").trimEnd()).join(`
|
|
1293
|
+
`)}__name(renderTable,"renderTable");function readActiveRunId(body){if(!body||typeof body!="object")return;let value=body.activeRunId;return typeof value=="string"?value:void 0}__name(readActiveRunId,"readActiveRunId");init_dist();init_sync_schemas();import fs41 from"node:fs";import path44 from"node:path";init_api();init_project_context();init_project();var SchemaCommandError=class extends Error{static{__name(this,"SchemaCommandError")}code;constructor(code2,message){super(message),this.name="SchemaCommandError",this.code=code2}};function renameOperation(contentType,value){let separator=value.indexOf("="),from=value.slice(0,separator).trim(),to=value.slice(separator+1).trim();if(separator<=0||!from||!to||to.includes("="))throw new SchemaCommandError("SCHEMA_RENAME_INVALID",`Invalid --rename "${value}". Use --rename old.path=new.path.`);return{type:"renameField",contentType,from,to}}__name(renameOperation,"renameOperation");function toApiShape(schema){return{name:schema.uid,label:schema.name,isSingleton:schema.isSingleton??!1,i18n:schema.i18n??{enabled:!0},fields:schema.fields}}__name(toApiShape,"toApiShape");function renderPrettyJson8(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson8,"renderPrettyJson");function isUniqueConflictIssue(issue){if(!issue||typeof issue!="object"||Array.isArray(issue))return!1;let candidate=issue;return candidate.kind==="unique_conflict"&&typeof candidate.contentType=="string"&&typeof candidate.field=="string"&&typeof candidate.value=="string"&&typeof candidate.documentCount=="number"&&Array.isArray(candidate.documentIds)&&candidate.documentIds.every(id=>typeof id=="string")&&(candidate.documentIdsTruncated===void 0||typeof candidate.documentIdsTruncated=="boolean")}__name(isUniqueConflictIssue,"isUniqueConflictIssue");function getUniqueConflictIssues(body){if(!body||typeof body!="object"||Array.isArray(body))return null;let issues=body.issues;return Array.isArray(issues)?issues.filter(isUniqueConflictIssue):null}__name(getUniqueConflictIssues,"getUniqueConflictIssues");function renderSchemaTransitionRejected(body,issues){currentMode().format==="json"?ui.result({command:"schemas push",data:body,render:__name(()=>"","render")}):ui.table({command:"schemas push",headline:"Schema push rejected. Nothing was written.",columns:[{key:"content_type",label:"CONTENT TYPE"},{key:"field",label:"FIELD"},{key:"value",label:"VALUE"},{key:"documents",label:"DOCUMENTS"},{key:"document_ids",label:"DOCUMENT IDS"}],rows:issues.map(issue=>{let remaining=Math.max(issue.documentCount-issue.documentIds.length,0),truncationNote=remaining>0?`... and ${remaining} more`:"... and more";return{content_type:issue.contentType,field:issue.field,value:issue.value,documents:issue.documentCount,document_ids:issue.documentIdsTruncated?[...issue.documentIds,truncationNote].join(", "):issue.documentIds.join(", ")}})}),process.exitCode=1}__name(renderSchemaTransitionRejected,"renderSchemaTransitionRejected");async function schemaListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.list",{projectId:ctx.projectId,env:ctx.env});let result=await api.listSchemas(ctx.projectId);ui.result({command:"schemas list",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaListCommand,"schemaListCommand");async function schemaGetCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getSchema(ctx.projectId,typeName);ui.result({command:"schemas get",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaGetCommand,"schemaGetCommand");async function schemaPushCommand(typeName,options,cmd){if((options.rename?.length??0)>0&&!typeName)throw new SchemaCommandError("SCHEMA_RENAME_REQUIRES_TYPE","--rename requires one schema name: fimo schemas push <typeName> --rename old.path=new.path.");let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.push",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),schemasDir=path44.join(cwd,"src/schemas"),allSchemaFiles=fs41.readdirSync(schemasDir).filter(file=>file.endsWith(".json")),files=typeName?[`${typeName}.json`]:allSchemaFiles,schemaUids=new Set(allSchemaFiles.flatMap(file=>{try{let schema=JSON.parse(fs41.readFileSync(path44.join(schemasDir,file),"utf-8"));return typeof schema.uid=="string"?[schema.uid]:[]}catch{return[]}})),schemas3=files.map(file=>{let filePath=path44.join(schemasDir,file);if(!fs41.existsSync(filePath))throw new Error(`Schema file not found: ${filePath}`);let issues=validateSchemaFile(filePath,path44.join("src/schemas",file),schemaUids);if(issues.length>0)throw new Error(issues.map(issue=>`${issue.file}: ${issue.message}`).join(`
|
|
1272
1294
|
`));return JSON.parse(fs41.readFileSync(filePath,"utf-8"))});syncSchemas({cwd,verbose:!1});let operations=schemas3.length===1?(options.rename??[]).map(value=>renameOperation(schemas3[0].uid,value)):[],results;try{results=await api.upsertSchemas(ctx.projectId,schemas3.map(schema=>toApiShape(schema)),operations)}catch(error){if(error instanceof ApiRequestError&&error.code==="schema_transition_rejected"){let issues=getUniqueConflictIssues(error.body);if(issues){renderSchemaTransitionRejected(error.body,issues);return}}throw error}let payload=results.length===1?results[0]:results;ui.result({command:"schemas push",data:payload,render:__name(()=>renderPrettyJson8(payload),"render")})}__name(schemaPushCommand,"schemaPushCommand");async function schemaDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteSchema(ctx.projectId,typeName);ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaDeleteCommand,"schemaDeleteCommand");init_skills();init_status();init_dist5();init_dist();init_api();init_config();init_auth_errors();init_interactive();init_project_context();init_version();import{readFileSync as readFileSync11}from"node:fs";import path45 from"node:path";var MAX_SUPPORT_MESSAGE_LENGTH=2e4;function registerSupportCommands(program2){program2.command("support").description("Contact Fimo support").command("report").description("Report a Fimo problem or high-impact feature request with project and environment context").argument("[message...]","What happened or capability is missing; use --message-file for longer or agent-written reports").option("--message-file <path>","Read the report from a UTF-8 text file").option("-C, --cwd <dir>","Project directory").option("--preview","Print the exact support payload without sending it").option("-y, --yes","Send without prompting").addHelpText("after",`
|
|
1273
1295
|
Examples:
|
|
1274
1296
|
fimo support report "Preview deployment fails after validation"
|
|
@@ -1279,7 +1301,7 @@ Examples:
|
|
|
1279
1301
|
Report: ${result.id}
|
|
1280
1302
|
Project: ${reportContext.projectName}
|
|
1281
1303
|
Environment: ${reportContext.environment}`,"render")})}catch(error){rethrowCliAuthError(error),ui.error({command:"support report",code:"SUPPORT_REPORT_FAILED",message:error instanceof Error?error.message:"The support report could not be sent.",hint:"Try again later, or contact Fimo support through the app."})}}__name(supportReportCommand,"supportReportCommand");function resolveSupportMessage(messageParts,messageFile){if(messageParts.length>0&&messageFile)return ui.error({command:"support report",code:"SUPPORT_MESSAGE_CONFLICT",message:"Pass the report as text or with --message-file, not both."}),null;let message=messageParts.join(" ").trim();if(messageFile)try{message=readFileSync11(path45.resolve(messageFile),"utf8").trim()}catch(error){return ui.error({command:"support report",code:"SUPPORT_MESSAGE_READ_FAILED",message:error instanceof Error?error.message:"The report file could not be read."}),null}return message||(ui.error({command:"support report",code:"SUPPORT_MESSAGE_REQUIRED",message:"Describe what went wrong or which capability is missing, or pass --message-file <path>."}),null)}__name(resolveSupportMessage,"resolveSupportMessage");function buildSupportMessage(context){return[context.message,"","Fimo CLI context",`Project: ${context.projectName} (${context.projectId})`,`Environment: ${context.environment}`,`Fimo CLI: ${context.cliVersion}`].join(`
|
|
1282
|
-
`)}__name(buildSupportMessage,"buildSupportMessage");init_dist5();init_dist();init_api();init_auth();init_config();init_interactive();async function switchCommand(options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),orgs2=await new FimoApiClient(cfg).listOrganizations();if(orgs2.length===0){ui.error({command:"orgs switch",code:"NO_ORGANIZATIONS",message:"No organization found for this account."});return}if(options.org){let target2=orgs2.find(org=>org.id===options.org)??orgs2.find(org=>org.slug===options.org);if(!target2){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:`No organization matched "${options.org}".`,hint:"Run `fimo orgs list` to see available orgs."});return}setActiveOrganization({id:target2.id,name:target2.name,slug:target2.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target2.name}`,details:{id:target2.id,name:target2.name,slug:target2.slug}});return}assertInteractive("Pass --org <id-or-slug>.","orgs switch"),mt("Switch active organization");let currentId=creds.activeOrganization?.id,selected=await _t({message:"Select an organization",initialValue:currentId,options:orgs2.map(org=>({value:org.id,label:org.name,hint:org.id===currentId?"current":org.slug}))});if(q(selected)){ui.info({command:"orgs switch",message:"Cancelled."});return}let target=orgs2.find(org=>org.id===selected);if(!target){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:"Selected organization not found."});return}setActiveOrganization({id:target.id,name:target.name,slug:target.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target.name}`,details:{id:target.id,name:target.name,slug:target.slug}})}__name(switchCommand,"switchCommand");init_esm();init_dist();init_api();init_config();init_project_context();init_project();import{readFile as readFile4}from"node:fs/promises";import{resolve as resolve8}from"node:path";var WebhookCommandError=class extends Error{static{__name(this,"WebhookCommandError")}code;constructor(code2,message){super(message),this.name="WebhookCommandError",this.code=code2}};function
|
|
1304
|
+
`)}__name(buildSupportMessage,"buildSupportMessage");init_dist5();init_dist();init_api();init_auth();init_config();init_interactive();async function switchCommand(options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),orgs2=await new FimoApiClient(cfg).listOrganizations();if(orgs2.length===0){ui.error({command:"orgs switch",code:"NO_ORGANIZATIONS",message:"No organization found for this account."});return}if(options.org){let target2=orgs2.find(org=>org.id===options.org)??orgs2.find(org=>org.slug===options.org);if(!target2){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:`No organization matched "${options.org}".`,hint:"Run `fimo orgs list` to see available orgs."});return}setActiveOrganization({id:target2.id,name:target2.name,slug:target2.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target2.name}`,details:{id:target2.id,name:target2.name,slug:target2.slug}});return}assertInteractive("Pass --org <id-or-slug>.","orgs switch"),mt("Switch active organization");let currentId=creds.activeOrganization?.id,selected=await _t({message:"Select an organization",initialValue:currentId,options:orgs2.map(org=>({value:org.id,label:org.name,hint:org.id===currentId?"current":org.slug}))});if(q(selected)){ui.info({command:"orgs switch",message:"Cancelled."});return}let target=orgs2.find(org=>org.id===selected);if(!target){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:"Selected organization not found."});return}setActiveOrganization({id:target.id,name:target.name,slug:target.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target.name}`,details:{id:target.id,name:target.name,slug:target.slug}})}__name(switchCommand,"switchCommand");init_esm();init_dist();init_api();init_config();init_project_context();init_project();import{readFile as readFile4}from"node:fs/promises";import{resolve as resolve8}from"node:path";var WebhookCommandError=class extends Error{static{__name(this,"WebhookCommandError")}code;constructor(code2,message){super(message),this.name="WebhookCommandError",this.code=code2}};function addScopeOptions3(command){return command.option("--project <id>","Project id (defaults to .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions3,"addScopeOptions");function collect2(value,previous){return[...previous??[],value]}__name(collect2,"collect");function registerWebhooksCommands(program2){let webhooks=program2.command("webhooks").description("Manage outbound project webhooks").addHelpText("after",`
|
|
1283
1305
|
Examples:
|
|
1284
1306
|
fimo webhooks events
|
|
1285
1307
|
fimo webhooks events form.submitted
|
|
@@ -1289,10 +1311,10 @@ Examples:
|
|
|
1289
1311
|
fimo webhooks deliveries <webhook-id>
|
|
1290
1312
|
|
|
1291
1313
|
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.
|
|
1292
|
-
`);addScopeOptions(webhooks.command("events [eventType]").description("List events or describe one event and its example payload")).action((eventType,opts,command)=>eventsCommand(eventType,opts,command)),addScopeOptions(webhooks.command("list").description("List project webhooks")).action((opts,command)=>listCommand4(opts,command)),addScopeOptions(webhooks.command("get <webhookId>").description("Show a webhook configuration")).action((webhookId,opts,command)=>getCommand(webhookId,opts,command)),addScopeOptions(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",collect).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 <main|all>","Deliver events from main or all environments","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)=>createCommand3(name,opts,command)),addScopeOptions(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",collect).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 <main|all>","Deliver events from main or all environments").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)=>updateCommand(webhookId,opts,command)),addScopeOptions(webhooks.command("delete <webhookId>").description("Delete an outbound webhook")).action((webhookId,opts,command)=>deleteCommand2(webhookId,opts,command)),addScopeOptions(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)),addScopeOptions(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)),addScopeOptions(webhooks.command("delivery <webhookId> <deliveryId>").description("Show a delivery and all attempts")).action((webhookId,deliveryId,opts,command)=>deliveryCommand(webhookId,deliveryId,opts,command)),addScopeOptions(webhooks.command("retry <webhookId> <deliveryId>").description("Retry an exhausted failed delivery now")).action((webhookId,deliveryId,opts,command)=>retryCommand2(webhookId,deliveryId,opts,command)),addScopeOptions(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 resolveScope2(opts,_command){return{projectId:opts.project??(await getProjectContext({cwd:opts.cwd})).projectId,api:new FimoApiClient(loadConfig())}}__name(resolveScope2,"resolveScope");async function eventsCommand(eventType,opts,command){let{api,projectId}=await resolveScope2(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 listCommand4(opts,command){let{api,projectId}=await resolveScope2(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(listCommand4,"listCommand");async function getCommand(webhookId,opts,command){let{api,projectId}=await resolveScope2(opts,command);renderJson("webhooks get",await api.getProjectWebhook(projectId,webhookId))}__name(getCommand,"getCommand");async function createCommand3(name,opts,command){let{api,projectId}=await resolveScope2(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(createCommand3,"createCommand");async function updateCommand(webhookId,opts,command){let{api,projectId}=await resolveScope2(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(updateCommand,"updateCommand");async function deleteCommand2(webhookId,opts,command){let{api,projectId}=await resolveScope2(opts,command);await api.deleteProjectWebhook(projectId,webhookId),ui.ok({command:"webhooks delete",headline:`Deleted webhook ${webhookId}`,details:{project_id:projectId,webhook_id:webhookId}})}__name(deleteCommand2,"deleteCommand");async function testCommand(webhookId,opts,command){let{api,projectId}=await resolveScope2(opts,command),data2=opts.data===void 0?void 0:parseJsonObject2(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 resolveScope2(opts,command),limit=opts.limit===void 0?void 0:parseLimit(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 resolveScope2(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 resolveScope2(opts,command);renderJson("webhooks retry",await api.retryProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(retryCommand2,"retryCommand");async function rotateSecretCommand(webhookId,opts,command){let{api,projectId}=await resolveScope2(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 path47=resolve8(resolveProjectCwd(cwd),value.slice(1));try{input=await readFile4(path47,"utf8")}catch{throw new WebhookCommandError("WEBHOOK_INPUT_READ_FAILED",`Could not read ${flag2} input from '${path47}'.`)}}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 parseJsonObject2(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(parseJsonObject2,"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 parseLimit(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(parseLimit,"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","validate","describe"]},{title:"Projects & teams",commands:["projects","orgs","invite","credits","referral","rename","delete","unpublish"]},{title:"Environments & releases",commands:["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"]},{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(`
|
|
1314
|
+
`);addScopeOptions3(webhooks.command("events [eventType]").description("List events or describe one event and its example payload")).action((eventType,opts,command)=>eventsCommand(eventType,opts,command)),addScopeOptions3(webhooks.command("list").description("List project webhooks")).action((opts,command)=>listCommand4(opts,command)),addScopeOptions3(webhooks.command("get <webhookId>").description("Show a webhook configuration")).action((webhookId,opts,command)=>getCommand(webhookId,opts,command)),addScopeOptions3(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",collect2).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 <main|all>","Deliver events from main or all environments","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)=>createCommand3(name,opts,command)),addScopeOptions3(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",collect2).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 <main|all>","Deliver events from main or all environments").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)=>updateCommand2(webhookId,opts,command)),addScopeOptions3(webhooks.command("delete <webhookId>").description("Delete an outbound webhook")).action((webhookId,opts,command)=>deleteCommand2(webhookId,opts,command)),addScopeOptions3(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)),addScopeOptions3(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)),addScopeOptions3(webhooks.command("delivery <webhookId> <deliveryId>").description("Show a delivery and all attempts")).action((webhookId,deliveryId,opts,command)=>deliveryCommand(webhookId,deliveryId,opts,command)),addScopeOptions3(webhooks.command("retry <webhookId> <deliveryId>").description("Retry an exhausted failed delivery now")).action((webhookId,deliveryId,opts,command)=>retryCommand2(webhookId,deliveryId,opts,command)),addScopeOptions3(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 resolveScope3(opts,_command){return{projectId:opts.project??(await getProjectContext({cwd:opts.cwd})).projectId,api:new FimoApiClient(loadConfig())}}__name(resolveScope3,"resolveScope");async function eventsCommand(eventType,opts,command){let{api,projectId}=await resolveScope3(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 listCommand4(opts,command){let{api,projectId}=await resolveScope3(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(listCommand4,"listCommand");async function getCommand(webhookId,opts,command){let{api,projectId}=await resolveScope3(opts,command);renderJson("webhooks get",await api.getProjectWebhook(projectId,webhookId))}__name(getCommand,"getCommand");async function createCommand3(name,opts,command){let{api,projectId}=await resolveScope3(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(createCommand3,"createCommand");async function updateCommand2(webhookId,opts,command){let{api,projectId}=await resolveScope3(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(updateCommand2,"updateCommand");async function deleteCommand2(webhookId,opts,command){let{api,projectId}=await resolveScope3(opts,command);await api.deleteProjectWebhook(projectId,webhookId),ui.ok({command:"webhooks delete",headline:`Deleted webhook ${webhookId}`,details:{project_id:projectId,webhook_id:webhookId}})}__name(deleteCommand2,"deleteCommand");async function testCommand(webhookId,opts,command){let{api,projectId}=await resolveScope3(opts,command),data2=opts.data===void 0?void 0:parseJsonObject2(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 resolveScope3(opts,command),limit=opts.limit===void 0?void 0:parseLimit2(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 resolveScope3(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 resolveScope3(opts,command);renderJson("webhooks retry",await api.retryProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(retryCommand2,"retryCommand");async function rotateSecretCommand(webhookId,opts,command){let{api,projectId}=await resolveScope3(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 path47=resolve8(resolveProjectCwd(cwd),value.slice(1));try{input=await readFile4(path47,"utf8")}catch{throw new WebhookCommandError("WEBHOOK_INPUT_READ_FAILED",`Could not read ${flag2} input from '${path47}'.`)}}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 parseJsonObject2(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(parseJsonObject2,"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 parseLimit2(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(parseLimit2,"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","validate","describe"]},{title:"Projects & teams",commands:["projects","orgs","invite","credits","referral","rename","delete","unpublish"]},{title:"Environments & releases",commands:["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"]},{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(`
|
|
1293
1315
|
`)}__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(`
|
|
1294
1316
|
`).map(line=>` ${line}`).join(`
|
|
1295
|
-
`)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs42.readFileSync(path46.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(fs42.readFileSync(path46.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("--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);registerSupportCommands(program);registerWebhooksCommands(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("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("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("--template-root <path>","Override template directory when creating").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("--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("Create or reuse a Fimo project, crawl a live site, and write migration artifacts").argument("<url>","Published source site URL").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("--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 current migration manifest").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 current migration manifest").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 generated migration toward the source site").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 regular Fimo CLI commands for importing reviewed migration artifacts").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("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);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 project (reads .fimo.settings.json)").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("--template-root <path>","Override template directory").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 project from .fimo.settings.json)").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","Show preview URLs + deleted envs").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("--agents","Limit to the agents/activations 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").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 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=`
|
|
1317
|
+
`)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs42.readFileSync(path46.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(fs42.readFileSync(path46.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("--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);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("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("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("--template-root <path>","Override template directory when creating").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("--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("Create or reuse a Fimo project, crawl a live site, and write migration artifacts").argument("<url>","Published source site URL").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("--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 current migration manifest").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 current migration manifest").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 generated migration toward the source site").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 regular Fimo CLI commands for importing reviewed migration artifacts").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("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);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 project (reads .fimo.settings.json)").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("--template-root <path>","Override template directory").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 project from .fimo.settings.json)").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","Show preview URLs + deleted envs").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("--agents","Limit to the agents/activations 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").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 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=`
|
|
1296
1318
|
Supported agents:
|
|
1297
1319
|
Universal (always covered via AGENTS.md, no per-agent file needed):
|
|
1298
1320
|
Codex, OpenCode, Aider, and other AGENTS.md-native tools
|